-------------------------------------------------------------------------------- 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 unicode_width src/lib.rs --error-format=json --json=diagnostic-rendered-ansi,artifacts,future-incompat --crate-type lib --emit=dep-info,metadata,link -C opt-level=3 -C embed-bitcode=no --cfg feature="default" -C metadata=60e206579899f5d5 -C extra-filename=-60e206579899f5d5 --out-dir /usr/home/liquid/tmp/.tmpuKxzaj/target/release/deps -L dependency=/usr/home/liquid/tmp/.tmpuKxzaj/target/release/deps -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-unicode-width-0.1.9-Opt-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 197,373,352 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 10,308,534 ( 5.22%) ./elf/dl-lookup.c:_dl_lookup_symbol_x 5,555,401 ( 2.81%) ./malloc/malloc.c:_int_malloc 4,927,096 ( 2.50%) ./malloc/malloc.c:_int_free 4,843,695 ( 2.45%) ./elf/dl-lookup.c:do_lookup_x 4,141,271 ( 2.10%) ./elf/../sysdeps/x86_64/dl-machine.h:_dl_relocate_object 3,283,347 ( 1.66%) ./malloc/malloc.c:malloc 3,041,415 ( 1.54%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 2,139,033 ( 1.08%) ./elf/do-rel.h:_dl_relocate_object 1,990,381 ( 1.01%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/opaque.rs:>::decode 1,671,154 ( 0.85%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>::decode 1,619,973 ( 0.82%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::decode 1,438,664 ( 0.73%) ./malloc/malloc.c:free 1,437,784 ( 0.73%) ???:SetImpliedBits(llvm::FeatureBitset&, llvm::FeatureBitset const&, llvm::ArrayRef) 1,056,240 ( 0.54%) ./malloc/malloc.c:malloc_consolidate 866,116 ( 0.44%) ./elf/dl-lookup.c:check_match 798,159 ( 0.40%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 723,023 ( 0.37%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:, >::decode::{closure#0}>, ::imported_source_files::{closure#3}::{closure#0}> as core::iter::traits::iterator::Iterator>::fold::<(), core::iter::traits::iterator::Iterator::for_each::call as alloc::vec::spec_extend::SpecExtend, >::decode::{closure#0}>, ::imported_source_files::{closure#3}::{closure#0}>>>::spec_extend::{closure#0}>::{closure#0}> 722,827 ( 0.37%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/mod.rs:::next_token 720,640 ( 0.37%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::new_imported_source_file 719,048 ( 0.36%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:::new_imported_source_file 655,899 ( 0.33%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::get:: 641,989 ( 0.33%) ???:llvm::PassRegistry::enumerateWith(llvm::PassRegistrationListener*) 585,557 ( 0.30%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 565,350 ( 0.29%) ./malloc/malloc.c:unlink_chunk.constprop.0 559,345 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs:>::try_read_immediate 531,119 ( 0.27%) ./string/../sysdeps/x86_64/strcmp.S:strcmp 520,505 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/decoder.rs:, >::decode::{closure#0}>, ::imported_source_files::{closure#3}::{closure#0}> as core::iter::traits::iterator::Iterator>::fold::<(), core::iter::traits::iterator::Iterator::for_each::call as alloc::vec::spec_extend::SpecExtend, >::decode::{closure#0}>, ::imported_source_files::{closure#3}::{closure#0}>>>::spec_extend::{closure#0}>::{closure#0}> 511,764 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/coercion.rs:::coerce 504,101 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::parse_token_tree 503,366 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs:::advance_token 502,024 ( 0.25%) ???:llvm::StringMapImpl::LookupBucketFor(llvm::StringRef) 479,637 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:, >::decode::{closure#0}>, ::imported_source_files::{closure#3}::{closure#0}> as core::iter::traits::iterator::Iterator>::fold::<(), core::iter::traits::iterator::Iterator::for_each::call as alloc::vec::spec_extend::SpecExtend, >::decode::{closure#0}>, ::imported_source_files::{closure#3}::{closure#0}>>>::spec_extend::{closure#0}>::{closure#0}> 476,964 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::check 470,330 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs:::span_data_to_lines_and_cols 454,248 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp/ring.rs:>::pop_first 435,344 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/hir/map/mod.rs:::attrs 423,861 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp.rs:::advance_left 420,636 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/vec_deque/mod.rs:>::push_back 416,215 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/middle/region.rs:::temporary_scope 403,134 ( 0.20%) ./malloc/malloc.c:realloc 402,434 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/freshen.rs:::fold_ty 392,796 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::short_write_process_buffer:: 391,687 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 387,794 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 385,287 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 376,490 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::hash_stable 362,239 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/cx/expr.rs:::mirror_expr_inner 362,084 ( 0.18%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 344,410 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/encoder.rs:>::encode 335,910 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/unescape.rs:rustc_lexer::unescape::scan_escape 335,352 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::maybe_lint_level_root_bounded 334,798 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 330,122 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/hir/map/mod.rs:::find_parent_node 325,950 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/layout.rs:<&rustc_middle::ty::TyS as rustc_target::abi::TyAbiInterface<_>>::ty_and_layout_field::field_ty_or_layout::> 325,482 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:::advance_left 325,380 ( 0.16%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:::node_type_opt 318,855 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/layout.rs:<&rustc_middle::ty::TyS as rustc_target::abi::TyAbiInterface>>::ty_and_layout_field 316,898 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::shallow_resolve_ty 312,018 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs:rustc_const_eval::transform::check_consts::qualifs::in_operand::::qualif_local::{closure#0}> 303,056 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/middle/region.rs:>>::get:: 302,181 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/undo_log.rs:::rollback_to 300,617 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/undo_log.rs:>::reverse 298,387 ( 0.15%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (core::result::Result, rustc_middle::ty::layout::LayoutError>, rustc_query_system::dep_graph::graph::DepNodeIndex), core::hash::BuildHasherDefault>>::from_key_hashed_nocheck::> 298,364 ( 0.15%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>, (), core::hash::BuildHasherDefault>>::from_hash::>>::{closure#0}> 294,036 ( 0.15%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>>::from_key_hashed_nocheck:: 290,029 ( 0.15%) ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S:__memcmp_avx2_movbe 287,106 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next_with_spacing 284,416 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs:::parse_assoc_expr_with 281,233 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::insert 280,585 ( 0.14%) /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}> 273,138 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/rustc-hash-1.1.0/src/lib.rs:<&str as core::hash::Hash>::hash:: 272,460 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::_intern_substs 269,618 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs:::read_scalar:: 268,381 ( 0.14%) ./malloc/malloc.c:_int_realloc 267,656 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/cx/expr.rs:::make_mirror_unadjusted 266,990 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::_intern_substs 266,733 ( 0.14%) ???:llvm::PMTopLevelManager::setLastUser(llvm::ArrayRef, llvm::Pass*) 265,414 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/regionck.rs:::visit_expr 265,171 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/build/expr/as_operand.rs:::as_operand 264,594 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::commit_from 262,434 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:>::hash_stable 258,844 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/validity.rs:>::try_visit_primitive 258,241 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/levels.rs:::push 254,511 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:::is_trivially_sized 253,230 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::start_snapshot 252,524 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/source_map.rs:::new_imported_source_file 250,816 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs:::collect_tokens_for_expr::<::parse_dot_or_call_expr::{closure#0}>::{closure#0} 250,226 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/char/mod.rs:::next 250,132 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::eq 245,604 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/writeback.rs:::visit_node_id 244,881 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs:::attrs 244,342 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/sub.rs:::tys 243,414 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>, (), core::hash::BuildHasherDefault>>::from_hash::>>::{closure#0}> 242,722 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::force_allocation_maybe_sized 241,715 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/validity.rs:>::aggregate_field_path_elem 238,468 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:>::decode 238,468 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:>::decode 238,468 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/range.rs:>::decode 236,144 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/coercion.rs:::try_coerce 235,602 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/type_variable.rs:::probe 233,320 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs:::get_bytes_internal:: 228,206 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/mod.rs:::check_static_ptr 226,347 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::insert::>::{closure#0}> 226,005 ( 0.11%) ???:llvm::PMTopLevelManager::AUFoldingSetNode::Profile(llvm::FoldingSetNodeID&, llvm::AnalysisUsage const&) 223,846 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/expr.rs:::check_expr_with_expectation_and_args 222,826 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/memory.rs:>::get_global_alloc 221,502 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/memory.rs:>::get 221,269 ( 0.11%) ./stdlib/cxa_finalize.c:__cxa_finalize 220,634 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::push 217,106 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs:::start_snapshot 215,526 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::commit_if_ok::, rustc_middle::ty::error::TypeError, ::sub<&rustc_middle::ty::TyS>::{closure#0}> 214,488 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::reserve_rehash::>::{closure#0}> 211,360 ( 0.11%) ???:(anonymous namespace)::GetCFGOnlyPasses::passEnumerate(llvm::PassInfo const*) [clone .llvm.764396836974782617] 211,249 ( 0.11%) /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:: 210,390 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/../../stdarch/crates/core_arch/src/x86/sse2.rs:>>::from_key_hashed_nocheck:: 202,741 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp.rs:::scan_string 201,412 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs:>::eval_operand 200,790 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs:::get_relocations:: 199,570 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:>::truncate 199,199 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::iter::traits::collect::Extend<&rustc_middle::ty::TyS>>::extend::> 198,700 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_hir_pretty/src/lib.rs:::print_expr 197,767 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::copy_op_no_validate -------------------------------------------------------------------------------- -- 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) { 79,584 ( 0.04%) self.hash = self.hash.rotate_left(5).bitxor(i).wrapping_mul(K); . } . } . . impl Hasher for FxHasher { . #[inline] 4,028 ( 0.00%) 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()); . 17,883 ( 0.01%) let mut hash = FxHasher { hash: self.hash }; . assert!(size_of::() <= 8); 250,863 ( 0.13%) while bytes.len() >= size_of::() { . hash.add_to_hash(read_usize(bytes) as usize); . bytes = &bytes[size_of::()..]; . } 35,740 ( 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..]; . } 35,740 ( 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..]; . } 37,881 ( 0.02%) if (size_of::() > 1) && bytes.len() >= 1 { 8,387 ( 0.00%) hash.add_to_hash(bytes[0] as usize); . } 4,116 ( 0.00%) self.hash = hash.hash; 4,028 ( 0.00%) } . . #[inline] . fn write_u8(&mut self, i: u8) { 2,603 ( 0.00%) self.add_to_hash(i as usize); . } . . #[inline] . fn write_u16(&mut self, i: u16) { 1 ( 0.00%) self.add_to_hash(i as usize); . } . . #[inline] . fn write_u32(&mut self, i: u32) { 247,919 ( 0.13%) 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 ---------------------------------------- 10 ( 0.00%) -------------------------------------------------------------------------------- -- 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)] 57,696 ( 0.03%) fn intern_ty(&self, kind: TyKind<'tcx>) -> Ty<'tcx> { . self.type_ 36,060 ( 0.02%) .intern(kind, |kind| { 1,326 ( 0.00%) let flags = super::flags::FlagComputation::for_kind(&kind); . . let ty_struct = TyS { 2,652 ( 0.00%) kind, . flags: flags.flags, . outer_exclusive_binder: flags.outer_exclusive_binder, . }; . . Interned(self.arena.alloc(ty_struct)) . }) . .0 64,908 ( 0.03%) } . . #[inline(never)] 41,072 ( 0.02%) fn intern_predicate( . &self, . kind: Binder<'tcx, PredicateKind<'tcx>>, . ) -> &'tcx PredicateInner<'tcx> { . self.predicate 35,938 ( 0.02%) .intern(kind, |kind| { 3,066 ( 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 46,206 ( 0.02%) } . } . . 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) { 50,932 ( 0.03%) 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) . } . 34,670 ( 0.02%) pub fn get(&self, id: hir::HirId) -> Option<&V> { 6,939 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); 6,939 ( 0.00%) self.data.get(&id.local_id) 27,740 ( 0.01%) } . . 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; . 54 ( 0.00%) fn index(&self, key: hir::HirId) -> &V { . self.get(key).expect("LocalTableInContext: key not found") 36 ( 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> { 192 ( 0.00%) pub fn new(hir_owner: LocalDefId) -> TypeckResults<'tcx> { 2,272 ( 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(), . } 192 ( 0.00%) } . . /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node. 552 ( 0.00%) pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res { 368 ( 0.00%) match *qpath { 1,104 ( 0.00%) hir::QPath::Resolved(_, ref path) => path.res, . hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self . .type_dependent_def(id) . .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), . } 920 ( 0.00%) } . . pub fn type_dependent_defs( . &self, . ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorReported>> { 18 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.type_dependent_defs } . } . 27 ( 0.00%) pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> { 54 ( 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()) 54 ( 0.00%) } . 108 ( 0.00%) pub fn type_dependent_def_id(&self, id: HirId) -> Option { . self.type_dependent_def(id).map(|(_, def_id)| def_id) 108 ( 0.00%) } . 3,434 ( 0.00%) pub fn type_dependent_defs_mut( . &mut self, . ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorReported>> { 3,434 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.type_dependent_defs } 3,434 ( 0.00%) } . . pub fn field_indices(&self) -> LocalTableInContext<'_, usize> { . LocalTableInContext { hir_owner: self.hir_owner, data: &self.field_indices } . } . . pub fn field_indices_mut(&mut self) -> LocalTableInContextMut<'_, usize> { . LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.field_indices } . } . . pub fn user_provided_types(&self) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> { 78 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.user_provided_types } 39 ( 0.00%) } . . pub fn user_provided_types_mut( . &mut self, . ) -> LocalTableInContextMut<'_, CanonicalUserType<'tcx>> { . LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.user_provided_types } . } . . pub fn node_types(&self) -> LocalTableInContext<'_, Ty<'tcx>> { 6,892 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.node_types } 3,446 ( 0.00%) } . . pub fn node_types_mut(&mut self) -> LocalTableInContextMut<'_, Ty<'tcx>> { 13,676 ( 0.01%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_types } 6,838 ( 0.00%) } . 76,962 ( 0.04%) pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> { 12,827 ( 0.01%) self.node_type_opt(id).unwrap_or_else(|| { . bug!("node_type: no type for node `{}`", tls::with(|tcx| tcx.hir().node_to_string(id))) . }) 64,135 ( 0.03%) } . 16,269 ( 0.01%) pub fn node_type_opt(&self, id: hir::HirId) -> Option> { 16,269 ( 0.01%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_types.get(&id.local_id).cloned() 32,538 ( 0.02%) } . . pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> { 94 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_substs } 47 ( 0.00%) } . 3,466 ( 0.00%) pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> { 3,466 ( 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()) 6,932 ( 0.00%) } . 3,401 ( 0.00%) pub fn node_substs_opt(&self, id: hir::HirId) -> Option> { 3,401 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_substs.get(&id.local_id).cloned() 6,802 ( 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> { 76 ( 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> { 13,474 ( 0.01%) self.node_type(expr.hir_id) . } . . pub fn expr_ty_opt(&self, expr: &hir::Expr<'_>) -> Option> { 13,639 ( 0.01%) self.node_type_opt(expr.hir_id) . } . . pub fn adjustments(&self) -> LocalTableInContext<'_, Vec>> { 6,758 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.adjustments } 3,379 ( 0.00%) } . . pub fn adjustments_mut( . &mut self, . ) -> LocalTableInContextMut<'_, Vec>> { 6,884 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.adjustments } 3,442 ( 0.00%) } . 6,756 ( 0.00%) pub fn expr_adjustments(&self, expr: &hir::Expr<'_>) -> &[ty::adjustment::Adjustment<'tcx>] { 13,512 ( 0.01%) validate_hir_id_for_typeck_results(self.hir_owner, expr.hir_id); . self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..]) 13,512 ( 0.01%) } . . /// Returns the type of `expr`, considering any `Adjustment` . /// entry recorded for that expression. 10 ( 0.00%) pub fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> { 2 ( 0.00%) self.expr_adjustments(expr).last().map_or_else(|| self.expr_ty(expr), |adj| adj.target) . } . 20 ( 0.00%) pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr<'_>) -> Option> { 4 ( 0.00%) self.expr_adjustments(expr).last().map(|adj| adj.target).or_else(|| self.expr_ty_opt(expr)) 12 ( 0.00%) } . 18 ( 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. 36 ( 0.00%) if let hir::ExprKind::Path(_) = expr.kind { . return false; . } . 44 ( 0.00%) matches!(self.type_dependent_defs().get(expr.hir_id), Some(Ok((DefKind::AssocFn, _)))) 36 ( 0.00%) } . 192 ( 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 . }) 256 ( 0.00%) } . . pub fn pat_binding_modes(&self) -> LocalTableInContext<'_, BindingMode> { 164 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_binding_modes } 50 ( 0.00%) } . . pub fn pat_binding_modes_mut(&mut self) -> LocalTableInContextMut<'_, BindingMode> { 80 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_binding_modes } 40 ( 0.00%) } . . pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec>> { 242 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_adjustments } 121 ( 0.00%) } . . pub fn pat_adjustments_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { 64 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_adjustments } 32 ( 0.00%) } . . /// For a given closure, returns the iterator of `ty::CapturedPlace`s that are captured . /// by the closure. 100 ( 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() 125 ( 0.00%) } . . pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, HirPlace<'tcx>)> { 16 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.closure_kind_origins } 8 ( 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>> { 52 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.liberated_fn_sigs } 26 ( 0.00%) } . . pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<'_, ty::FnSig<'tcx>> { 36 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.liberated_fn_sigs } 18 ( 0.00%) } . . pub fn fru_field_types(&self) -> LocalTableInContext<'_, Vec>> { 16 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.fru_field_types } 8 ( 0.00%) } . . pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { . LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.fru_field_types } . } . 6 ( 0.00%) pub fn is_coercion_cast(&self, hir_id: hir::HirId) -> bool { 2 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, hir_id); . self.coercion_casts.contains(&hir_id.local_id) 4 ( 0.00%) } . . pub fn set_coercion_cast(&mut self, id: ItemLocalId) { . self.coercion_casts.insert(id); . } . . pub fn coercion_casts(&self) -> &ItemLocalSet { 8 ( 0.00%) &self.coercion_casts 8 ( 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 832 ---------------------------------------- . } . . /// 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. 14 ( 0.00%) pub fn is_identity(&self) -> bool { 28 ( 0.00%) match self.value { . UserType::Ty(_) => false, . UserType::TypeOf(_, user_substs) => { 14 ( 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() { 54 ( 0.00%) GenericArgKind::Type(ty) => match ty.kind() { . ty::Bound(debruijn, b) => { . // We only allow a `ty::INNERMOST` index in substitutions. 27 ( 0.00%) assert_eq!(*debruijn, ty::INNERMOST); . cvar == b.var . } . _ => false, . }, . 2 ( 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, . }, . -- line 867 ---------------------------------------- -- line 872 ---------------------------------------- . cvar == b . } . _ => false, . }, . } . }) . } . } 28 ( 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. . #[derive(Copy, Clone, Debug, PartialEq, TyEncodable, TyDecodable)] 126 ( 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> { 500 ( 0.00%) pub fn typeck_opt_const_arg( . self, . def: ty::WithOptConstParam, . ) -> &'tcx TypeckResults<'tcx> { 200 ( 0.00%) if let Some(param_did) = def.const_param_did { . self.typeck_const_arg((def.did, param_did)) . } else { . self.typeck(def.did) . } 400 ( 0.00%) } . 33 ( 0.00%) pub fn alloc_steal_thir(self, thir: Thir<'tcx>) -> &'tcx Steal> { 11 ( 0.00%) self.arena.alloc(Steal::new(thir)) 44 ( 0.00%) } . 220 ( 0.00%) pub fn alloc_steal_mir(self, mir: Body<'tcx>) -> &'tcx Steal> { 44 ( 0.00%) self.arena.alloc(Steal::new(mir)) 308 ( 0.00%) } . 44 ( 0.00%) pub fn alloc_steal_promoted( . self, . promoted: IndexVec>, . ) -> &'tcx Steal>> { 11 ( 0.00%) self.arena.alloc(Steal::new(promoted)) 55 ( 0.00%) } . 72 ( 0.00%) pub fn alloc_adt_def( . self, . did: DefId, . kind: AdtKind, . variants: IndexVec, . repr: ReprOptions, . ) -> &'tcx ty::AdtDef { 128 ( 0.00%) self.intern_adt_def(ty::AdtDef::new(self, did, kind, variants, repr)) 32 ( 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? 112 ( 0.00%) pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound, Bound) { 56 ( 0.00%) let attrs = self.get_attrs(def_id); 238 ( 0.00%) let get = |name| { 56 ( 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); 8 ( 0.00%) if let Some( . &[ . ast::NestedMetaItem::Literal(ast::Lit { 4 ( 0.00%) kind: ast::LitKind::Int(a, _), .. . }), . ], 2 ( 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 . } 280 ( 0.00%) }; 84 ( 0.00%) ( 84 ( 0.00%) get(sym::rustc_layout_scalar_valid_range_start), 42 ( 0.00%) get(sym::rustc_layout_scalar_valid_range_end), . ) 112 ( 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 }) . } . 49 ( 0.00%) pub fn consider_optimizing String>(self, msg: T) -> bool { 7 ( 0.00%) let cname = self.crate_name(LOCAL_CRATE); 52 ( 0.00%) self.sess.consider_optimizing(cname.as_str(), msg) 56 ( 0.00%) } . . /// Obtain all lang items of this crate and all dependencies (recursively) 79,779 ( 0.04%) pub fn lang_items(self) -> &'tcx rustc_hir::lang_items::LanguageItems { . self.get_lang_items(()) 102,573 ( 0.05%) } . . /// 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. . pub fn get_diagnostic_item(self, name: Symbol) -> Option { . self.all_diagnostic_items(()).name_to_id.get(&name).copied() . } . . /// Obtain the diagnostic item's name 196 ( 0.00%) pub fn get_diagnostic_name(self, id: DefId) -> Option { . self.diagnostic_items(id.krate).id_to_name.get(&id).copied() 224 ( 0.00%) } . . /// Check whether the diagnostic item with the given `name` has the given `DefId`. 385 ( 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) 440 ( 0.00%) } . 147 ( 0.00%) pub fn stability(self) -> &'tcx stability::Index<'tcx> { . self.stability_index(()) 189 ( 0.00%) } . 17,822 ( 0.01%) pub fn features(self) -> &'tcx rustc_feature::Features { . self.features_query(()) 20,368 ( 0.01%) } . . pub fn def_key(self, id: DefId) -> rustc_hir::definitions::DefKey { . // Accessing the DefKey is ok, since it is part of DefPathHash. 272 ( 0.00%) if let Some(id) = id.as_local() { . self.untracked_resolutions.definitions.def_key(id) . } else { 142 ( 0.00%) self.untracked_resolutions.cstore.def_key(id) . } . } . . /// 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`. -- line 1272 ---------------------------------------- -- line 1277 ---------------------------------------- . } else { . self.untracked_resolutions.cstore.def_path(id) . } . } . . #[inline] . pub fn def_path_hash(self, def_id: DefId) -> rustc_hir::definitions::DefPathHash { . // Accessing the DefPathHash is ok, it is incr. comp. stable. 97 ( 0.00%) if let Some(def_id) = def_id.as_local() { . self.untracked_resolutions.definitions.def_path_hash(def_id) . } else { 8 ( 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 { 2,370 ( 0.00%) &*self.untracked_resolutions.cstore 1,185 ( 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> { 4 ( 0.00%) let resolutions = &self.gcx.untracked_resolutions; 18 ( 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.) 16 ( 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=...` . 24 ( 0.00%) if self.features().nll { . return BorrowckMode::Mir; . } . 8 ( 0.00%) self.sess.opts.borrowck_mode 32 ( 0.00%) } . . /// If `true`, we should use lazy normalization for constants, otherwise . /// we still evaluate them eagerly. . #[inline] . pub fn lazy_normalization(self) -> bool { . let features = self.features(); . // Note: We only use lazy normalization for generic const expressions. . features.generic_const_exprs -- line 1434 ---------------------------------------- -- line 1554 ---------------------------------------- . 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")`). 132 ( 0.00%) pub fn article_and_description(self, def_id: DefId) -> (&'static str, &'static str) { 96 ( 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"), . }, 216 ( 0.00%) def_kind => (def_kind.article(), def_kind.descr(def_id)), . } 108 ( 0.00%) } . . pub fn type_length_limit(self) -> Limit { . self.limits(()).type_length_limit . } . 22,127 ( 0.01%) pub fn recursion_limit(self) -> Limit { . self.limits(()).recursion_limit 25,288 ( 0.01%) } . . pub fn move_size_limit(self) -> Limit { . self.limits(()).move_size_limit . } . 84 ( 0.00%) pub fn const_eval_limit(self) -> Limit { . self.limits(()).const_eval_limit 96 ( 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 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(); 3,195 ( 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(); 16,841 ( 0.01%) 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 1805 ---------------------------------------- . /// 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 { 8,260 ( 0.00%) assert!(ptr_eq(context.tcx.gcx, tcx.gcx)); . let context: &ImplicitCtxt<'_, '_> = mem::transmute(context); 8,210 ( 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> { 6,607 ( 0.00%) &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)`. 2,676 ( 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,663 ( 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)`. 892 ( 0.00%) self.0.kind.hash(s) . } . } . . impl<'tcx, T> Borrow<[T]> for Interned<'tcx, List> { . fn borrow<'a>(&'a self) -> &'a [T] { 16,737 ( 0.01%) &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)`. 1,061 ( 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 { 1,517 ( 0.00%) &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)`. 5,789 ( 0.00%) self.0.hash(s) . } . } . . impl<'tcx> TyCtxt<'tcx> { 21,262 ( 0.01%) pub fn $method(self, v: $ty) -> &'tcx $ty { 14,010 ( 0.01%) self.interners.$name.intern(v, |v| { 1,242 ( 0.00%) Interned(self.interners.arena.alloc(v)) . }).0 23,751 ( 0.01%) } . })+ . } . } . . 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> { 177,153 ( 0.09%) $(pub fn $method(self, v: &[$ty]) -> &'tcx List<$ty> { . self.interners.$field.intern_ref(v, || { . Interned(List::from_arena(&*self.arena, v)) . }).0 156,933 ( 0.08%) })+ . } . ); . } . . 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 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,248 ( 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> { 49,081 ( 0.02%) self.interners.intern_ty(st) . } . . #[inline] . pub fn mk_predicate(self, binder: Binder<'tcx, PredicateKind<'tcx>>) -> Predicate<'tcx> { 58,083 ( 0.03%) let inner = self.interners.intern_predicate(binder); . Predicate { inner } . } . . #[inline] 8,776 ( 0.00%) pub fn reuse_or_mk_predicate( . self, . pred: Predicate<'tcx>, . binder: Binder<'tcx, PredicateKind<'tcx>>, . ) -> Predicate<'tcx> { 487 ( 0.00%) if pred.kind() != binder { self.mk_predicate(binder) } else { pred } 8,776 ( 0.00%) } . . pub fn mk_mach_int(self, tm: IntTy) -> Ty<'tcx> { . 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, . } . } . . pub fn mk_mach_uint(self, tm: UintTy) -> Ty<'tcx> { 57 ( 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, . } 57 ( 0.00%) } . . pub fn mk_mach_float(self, tm: FloatTy) -> Ty<'tcx> { . match tm { . FloatTy::F32 => self.types.f32, . FloatTy::F64 => self.types.f64, . } . } . -- line 2248 ---------------------------------------- -- line 2329 ---------------------------------------- . } . . #[inline] . pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> { . self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Not }) . } . . #[inline] 23 ( 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))) 24 ( 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> { . let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect(); 24 ( 0.00%) self.mk_ty(Tuple(self.intern_substs(&kinds))) . } . . pub fn mk_tup], Ty<'tcx>>>(self, iter: I) -> I::Output { 600 ( 0.00%) iter.intern_with(|ts| { 7,986 ( 0.00%) let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect(); 8,200 ( 0.00%) self.mk_ty(Tuple(self.intern_substs(&kinds))) 540 ( 0.00%) }) . } . . #[inline] . pub fn mk_unit(self) -> Ty<'tcx> { . self.types.unit . } . . #[inline] -- line 2364 ---------------------------------------- -- line 2368 ---------------------------------------- . . #[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> { 68 ( 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 2445 ---------------------------------------- . self.mk_ty(Param(ParamTy { index, name })) . } . . #[inline] . pub fn mk_const_param(self, index: u32, name: Symbol, ty: Ty<'tcx>) -> &'tcx Const<'tcx> { . self.mk_const(ty::Const { val: ty::ConstKind::Param(ParamConst { index, name }), ty }) . } . 231 ( 0.00%) pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 165 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { . self.mk_region(ty::ReEarlyBound(param.to_early_bound_region_data())).into() . } 66 ( 0.00%) GenericParamDefKind::Type { .. } => self.mk_ty_param(param.index, param.name).into(), . GenericParamDefKind::Const { .. } => { . self.mk_const_param(param.index, param.name, self.type_of(param.def_id)).into() . } . } 231 ( 0.00%) } . . #[inline] . pub fn mk_opaque(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . self.mk_ty(Opaque(def_id, substs)) . } . 2,591 ( 0.00%) pub fn mk_place_field(self, place: Place<'tcx>, f: Field, ty: Ty<'tcx>) -> Place<'tcx> { 2,591 ( 0.00%) self.mk_place_elem(place, PlaceElem::Field(f, ty)) 5,182 ( 0.00%) } . . pub fn mk_place_deref(self, place: Place<'tcx>) -> Place<'tcx> { . self.mk_place_elem(place, PlaceElem::Deref) . } . 8 ( 0.00%) pub fn mk_place_downcast( . self, . place: Place<'tcx>, . adt_def: &'tcx AdtDef, . variant_index: VariantIdx, . ) -> Place<'tcx> { 8 ( 0.00%) self.mk_place_elem( . place, 16 ( 0.00%) PlaceElem::Downcast(Some(adt_def.variants[variant_index].name), variant_index), . ) 16 ( 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. 23,391 ( 0.01%) 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) } 25,990 ( 0.01%) } . . pub fn intern_poly_existential_predicates( . self, . eps: &[ty::Binder<'tcx, ExistentialPredicate<'tcx>>], . ) -> &'tcx List>> { . assert!(!eps.is_empty()); . assert!( . eps.array_windows() -- line 2518 ---------------------------------------- -- line 2521 ---------------------------------------- . ); . self._intern_poly_existential_predicates(eps) . } . . 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. 250 ( 0.00%) if preds.is_empty() { . // The macro-generated method below asserts we don't intern an empty slice. . List::empty() . } else { 50 ( 0.00%) self._intern_predicates(preds) . } 400 ( 0.00%) } . . pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List> { 511 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_type_list(ts) } 22 ( 0.00%) } . . pub fn intern_substs(self, ts: &[GenericArg<'tcx>]) -> &'tcx List> { 27,128 ( 0.01%) if ts.is_empty() { List::empty() } else { self._intern_substs(ts) } 182 ( 0.00%) } . . 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> { 5,285 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_place_elems(ts) } 78 ( 0.00%) } . . pub fn intern_canonical_var_infos( . self, . ts: &[CanonicalVarInfo<'tcx>], . ) -> CanonicalVarInfos<'tcx> { 325 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_canonical_var_infos(ts) } 10 ( 0.00%) } . . pub fn intern_bound_variable_kinds( . self, . ts: &[ty::BoundVariableKind], . ) -> &'tcx List { 173 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_bound_variable_kinds(ts) } 268 ( 0.00%) } . . 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 { 121 ( 0.00%) inputs_and_output: self.intern_type_list(xs), 18 ( 0.00%) c_variadic, 29 ( 0.00%) unsafety, 14 ( 0.00%) abi, 30 ( 0.00%) }) . } . . pub fn mk_poly_existential_predicates< . I: InternAs< . [ty::Binder<'tcx, ExistentialPredicate<'tcx>>], . &'tcx List>>, . >, . >( -- line 2591 ---------------------------------------- -- line 2598 ---------------------------------------- . pub fn mk_predicates], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { . iter.intern_with(|xs| self.intern_predicates(xs)) . } . . pub fn mk_type_list], &'tcx List>>>(self, iter: I) -> I::Output { 200 ( 0.00%) iter.intern_with(|xs| self.intern_type_list(xs)) . } . . pub fn mk_substs], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 12,861 ( 0.01%) iter.intern_with(|xs| self.intern_substs(xs)) . } . . pub fn mk_place_elems], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 54 ( 0.00%) iter.intern_with(|xs| self.intern_place_elems(xs)) . } . 4,249 ( 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())) 8,498 ( 0.00%) } . . pub fn mk_bound_variable_kinds< . I: InternAs<[ty::BoundVariableKind], &'tcx List>, . >( . self, . iter: I, . ) -> I::Output { 1,103 ( 0.00%) 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. 47,012 ( 0.02%) pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId { 47,012 ( 0.02%) let hir = self.hir(); . loop { 58,653 ( 0.03%) if id == bound { . return bound; . } . 64,175 ( 0.03%) 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); 38,505 ( 0.02%) if next == id { . bug!("lint traversal reached the root of the crate"); . } . id = next; . } 67,160 ( 0.03%) } . 336 ( 0.00%) pub fn lint_level_at_node( . self, . lint: &'static Lint, . mut id: hir::HirId, . ) -> (Level, LintLevelSource) { . let sets = self.lint_levels(()); . loop { 1,614 ( 0.00%) if let Some(pair) = sets.level_and_source(lint, id, self.sess) { . return pair; . } 114 ( 0.00%) let next = self.hir().get_parent_node(id); 342 ( 0.00%) if next == id { . bug!("lint traversal reached the root of the crate"); . } . id = next; . } 336 ( 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>), . ) { 46 ( 0.00%) let (level, src) = self.lint_level_at_node(lint, hir_id); 8 ( 0.00%) struct_lint_level(self.sess, lint, level, src, Some(span.into()), decorate); . } . . 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); . } . 63 ( 0.00%) pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx [TraitCandidate]> { 18 ( 0.00%) let map = self.in_scope_traits_map(id.owner)?; . let candidates = map.get(&id.local_id)?; 18 ( 0.00%) Some(&*candidates) 72 ( 0.00%) } . 105 ( 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()) 135 ( 0.00%) } . 54 ( 0.00%) pub fn is_late_bound(self, id: HirId) -> bool { . self.is_late_bound_map(id.owner) 6 ( 0.00%) .map_or(false, |(owner, set)| owner == id.owner && set.contains(&id.local_id)) 48 ( 0.00%) } . 315 ( 0.00%) pub fn object_lifetime_defaults(self, id: HirId) -> Option> { . self.object_lifetime_defaults_map(id.owner) 405 ( 0.00%) } . 135 ( 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(), . ) 135 ( 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 30 ( 0.00%) pub fn is_const_fn(self, def_id: DefId) -> bool { 3 ( 0.00%) if self.is_const_fn_raw(def_id) { . match self.lookup_const_stability(def_id) { . Some(stability) if stability.level.is_unstable() => { . // has a `rustc_const_unstable` attribute, check whether the user enabled the . // corresponding feature gate. . self.features() . .declared_lib_features . .iter() . .any(|&(sym, _)| sym == stability.feature) -- line 2741 ---------------------------------------- -- line 2743 ---------------------------------------- . // 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 . } 27 ( 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; 2,584 ( 0.00%) fn intern_with(self, f: F) -> Self::Output . where . F: FnOnce(&[T]) -> R, . { 58,526 ( 0.03%) E::intern_with(self, f) 2,790 ( 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; 32,186 ( 0.02%) 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`. 37,973 ( 0.02%) match iter.size_hint() { . (0, Some(0)) => { . assert!(iter.next().is_none()); . f(&[]) . } . (1, Some(1)) => { . let t0 = iter.next().unwrap(); . assert!(iter.next().is_none()); 1,830 ( 0.00%) f(&[t0]) . } . (2, Some(2)) => { . let t0 = iter.next().unwrap(); . let t1 = iter.next().unwrap(); 14 ( 0.00%) assert!(iter.next().is_none()); 5,814 ( 0.00%) f(&[t0, t1]) . } 16 ( 0.00%) _ => f(&iter.collect::>()), . } 35,713 ( 0.02%) } . } . . impl<'a, T, R> InternIteratorElement for &'a T . where . T: Clone + 'a, . { . type Output = R; 114 ( 0.00%) fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output { . // This code isn't hot. 12 ( 0.00%) f(&iter.cloned().collect::>()) 102 ( 0.00%) } . } . . impl InternIteratorElement for Result { . type Output = Result; 3,391 ( 0.00%) 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. 3,044 ( 0.00%) Ok(match iter.size_hint() { . (0, Some(0)) => { . assert!(iter.next().is_none()); . f(&[]) . } . (1, Some(1)) => { . let t0 = iter.next().unwrap()?; . assert!(iter.next().is_none()); 290 ( 0.00%) f(&[t0]) . } . (2, Some(2)) => { 56 ( 0.00%) let t0 = iter.next().unwrap()?; 56 ( 0.00%) let t1 = iter.next().unwrap()?; 84 ( 0.00%) assert!(iter.next().is_none()); 284 ( 0.00%) f(&[t0, t1]) . } 345 ( 0.00%) _ => f(&iter.collect::, _>>()?), . }) 3,842 ( 0.00%) } . } . . // 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 { 8,260 ( 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()) . }; . 11 ( 0.00%) providers.lookup_stability = |tcx, id| tcx.stability().local_stability(id.expect_local()); 2 ( 0.00%) providers.lookup_const_stability = . |tcx, id| tcx.stability().local_const_stability(id.expect_local()); 2 ( 0.00%) providers.lookup_deprecation_entry = 152 ( 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()) . }; . } 113,596 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/memory.rs -------------------------------------------------------------------------------- Ir -- line 114 ---------------------------------------- . . /// Lets us implement `HasDataLayout`, which is awfully convenient. . pub tcx: TyCtxt<'tcx>, . } . . impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for Memory<'mir, 'tcx, M> { . #[inline] . fn data_layout(&self) -> &TargetDataLayout { 653 ( 0.00%) &self.tcx.data_layout . } . } . . /// A reference to some allocation that was already bounds-checked for the given region . /// and had the on-access machine hooks run. . #[derive(Copy, Clone)] . pub struct AllocRef<'a, 'tcx, Tag, Extra> { . alloc: &'a Allocation, -- line 130 ---------------------------------------- -- line 138 ---------------------------------------- . alloc: &'a mut Allocation, . range: AllocRange, . tcx: TyCtxt<'tcx>, . alloc_id: AllocId, . } . . impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { . pub fn new(tcx: TyCtxt<'tcx>, extra: M::MemoryExtra) -> Self { 132 ( 0.00%) Memory { . alloc_map: M::MemoryMap::default(), . extra_fn_ptr_map: FxHashMap::default(), . dead_alloc_map: FxHashMap::default(), . extra, . tcx, . } . } . -- line 154 ---------------------------------------- -- line 157 ---------------------------------------- . /// for any other pointers, nor for TLS statics. . /// . /// Using the resulting pointer represents a *direct* access to that memory . /// (e.g. by directly using a `static`), . /// as opposed to access through a pointer that was created by the program. . /// . /// This function can fail only if `ptr` points to an `extern static`. . #[inline] 96 ( 0.00%) pub fn global_base_pointer( . &self, . ptr: Pointer, . ) -> InterpResult<'tcx, Pointer> { . // We know `offset` is relative to the allocation, so we can use `into_parts`. . let (alloc_id, offset) = ptr.into_parts(); . // We need to handle `extern static`. 32 ( 0.00%) match self.tcx.get_global_alloc(alloc_id) { . Some(GlobalAlloc::Static(def_id)) if self.tcx.is_thread_local_static(def_id) => { . bug!("global memory cannot point to thread-local static") . } . Some(GlobalAlloc::Static(def_id)) if self.tcx.is_foreign_item(def_id) => { . return M::extern_static_base_pointer(self, def_id); . } . _ => {} . } . // And we need to get the tag. 24 ( 0.00%) Ok(M::tag_alloc_base_pointer(self, Pointer::new(alloc_id, offset))) 64 ( 0.00%) } . . pub fn create_fn_alloc( . &mut self, . fn_val: FnVal<'tcx, M::ExtraFnVal>, . ) -> Pointer { . let id = match fn_val { . FnVal::Instance(instance) => self.tcx.create_fn_alloc(instance), . FnVal::Other(extra) => { -- line 191 ---------------------------------------- -- line 196 ---------------------------------------- . id . } . }; . // Functions are global allocations, so make sure we get the right base pointer. . // We know this is not an `extern static` so this cannot fail. . self.global_base_pointer(Pointer::from(id)).unwrap() . } . 6,076 ( 0.00%) pub fn allocate( . &mut self, . size: Size, . align: Align, . kind: MemoryKind, . ) -> InterpResult<'static, Pointer> { 2,692 ( 0.00%) let alloc = Allocation::uninit(size, align, M::PANIC_ON_ALLOC_FAIL)?; 6,057 ( 0.00%) Ok(self.allocate_with(alloc, kind)) 4,730 ( 0.00%) } . . pub fn allocate_bytes( . &mut self, . bytes: &[u8], . align: Align, . kind: MemoryKind, . mutability: Mutability, . ) -> Pointer { -- line 220 ---------------------------------------- -- line 222 ---------------------------------------- . self.allocate_with(alloc, kind) . } . . pub fn allocate_with( . &mut self, . alloc: Allocation, . kind: MemoryKind, . ) -> Pointer { 1,346 ( 0.00%) let id = self.tcx.reserve_alloc_id(); . debug_assert_ne!( . Some(kind), . M::GLOBAL_KIND.map(MemoryKind::Machine), . "dynamically allocating global memory" . ); . let alloc = M::init_allocation_extra(self, id, Cow::Owned(alloc), Some(kind)); 15,696 ( 0.01%) self.alloc_map.insert(id, (kind, alloc.into_owned())); . M::tag_alloc_base_pointer(self, Pointer::from(id)) . } . . pub fn reallocate( . &mut self, . ptr: Pointer>, . old_size_and_align: Option<(Size, Align)>, . new_size: Size, -- line 245 ---------------------------------------- -- line 361 ---------------------------------------- . let align = M::enforce_alignment(&self.extra).then_some(align); . self.check_and_deref_ptr( . ptr, . size, . align, . CheckInAllocMsg::MemoryAccessTest, . |alloc_id, offset, ptr| { . let (size, align) = 15,584 ( 0.01%) self.get_size_and_align(alloc_id, AllocCheck::Dereferenceable)?; . Ok((size, align, (alloc_id, offset, ptr))) . }, . ) . } . . /// Check if the given pointer points to live memory of given `size` and `align` . /// (ignoring `M::enforce_alignment`). The caller can control the error message for the . /// out-of-bounds case. -- line 377 ---------------------------------------- -- line 378 ---------------------------------------- . #[inline(always)] . pub fn check_ptr_access_align( . &self, . ptr: Pointer>, . size: Size, . align: Align, . msg: CheckInAllocMsg, . ) -> InterpResult<'tcx> { 34 ( 0.00%) self.check_and_deref_ptr(ptr, size, Some(align), msg, |alloc_id, _, _| { 16 ( 0.00%) let check = match msg { . CheckInAllocMsg::DerefTest | CheckInAllocMsg::MemoryAccessTest => { . AllocCheck::Dereferenceable . } . CheckInAllocMsg::PointerArithmeticTest | CheckInAllocMsg::InboundsTest => { . AllocCheck::Live . } . }; 8 ( 0.00%) let (size, align) = self.get_size_and_align(alloc_id, check)?; . Ok((size, align, ())) . })?; . Ok(()) . } . . /// Low-level helper function to check if a ptr is in-bounds and potentially return a reference . /// to the allocation it points to. Supports both shared and mutable references, as the actual . /// checking is offloaded to a helper closure. `align` defines whether and which alignment check . /// is done. Returns `None` for size 0, and otherwise `Some` of what `alloc_size` returned. 56 ( 0.00%) fn check_and_deref_ptr( . &self, . ptr: Pointer>, . size: Size, . align: Option, . msg: CheckInAllocMsg, . alloc_size: impl FnOnce( . AllocId, . Size, . Pointer, . ) -> InterpResult<'tcx, (Size, Align, T)>, . ) -> InterpResult<'tcx, Option> { 8 ( 0.00%) fn check_offset_align(offset: u64, align: Align) -> InterpResult<'static> { 20 ( 0.00%) if offset % align.bytes() == 0 { . Ok(()) . } else { . // The biggest power of two through which `offset` is divisible. . let offset_pow2 = 1 << offset.trailing_zeros(); . throw_ub!(AlignmentCheckFailed { . has: Align::from_bytes(offset_pow2).unwrap(), . required: align, . }) . } 12 ( 0.00%) } . . // Extract from the pointer an `Option` and an offset, which is relative to the . // allocation or (if that is `None`) an absolute address. 19,490 ( 0.01%) let ptr_or_addr = if size.bytes() == 0 { . // Let's see what we can do, but don't throw errors if there's nothing there. . self.ptr_try_get_alloc(ptr) . } else { . // A "real" access, we insist on getting an `AllocId`. . Ok(self.ptr_get_alloc(ptr)?) . }; . Ok(match ptr_or_addr { . Err(addr) => { -- line 440 ---------------------------------------- -- line 460 ---------------------------------------- . alloc_size, . ptr_offset: self.machine_usize_to_isize(offset.bytes()), . ptr_size: size, . msg, . }) . } . // Test align. Check this last; if both bounds and alignment are violated . // we want the error to be about the bounds. 8 ( 0.00%) if let Some(align) = align { . if M::force_int_for_alignment_check(&self.extra) { . let addr = Scalar::from_pointer(ptr, &self.tcx) . .to_machine_usize(&self.tcx) . .expect("ptr-to-int cast for align check should never fail"); . check_offset_align(addr, align)?; . } else { . // Check allocation alignment and offset alignment. 8 ( 0.00%) if alloc_align.bytes() < align.bytes() { . throw_ub!(AlignmentCheckFailed { has: alloc_align, required: align }); . } 20 ( 0.00%) check_offset_align(offset.bytes(), align)?; . } . } . . // We can still be zero-sized in this branch, in which case we have to . // return `None`. 12 ( 0.00%) if size.bytes() == 0 { None } else { Some(ret_val) } . } . }) 60 ( 0.00%) } . . /// Test if the pointer might be null. . pub fn ptr_may_be_null(&self, ptr: Pointer>) -> bool { . match self.ptr_try_get_alloc(ptr) { . Ok((alloc_id, offset, _)) => { . let (size, _align) = self . .get_size_and_align(alloc_id, AllocCheck::MaybeDead) . .expect("alloc info with MaybeDead cannot fail"); -- line 496 ---------------------------------------- -- line 505 ---------------------------------------- . . /// Allocation accessors . impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { . /// Helper function to obtain a global (tcx) allocation. . /// This attempts to return a reference to an existing allocation if . /// one can be found in `tcx`. That, however, is only possible if `tcx` and . /// this machine use the same pointer tag, so it is indirected through . /// `M::tag_allocation`. 57,002 ( 0.03%) fn get_global_alloc( . &self, . id: AllocId, . is_write: bool, . ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> { 46,638 ( 0.02%) let (alloc, def_id) = match self.tcx.get_global_alloc(id) { 5,182 ( 0.00%) Some(GlobalAlloc::Memory(mem)) => { . // Memory of a constant or promoted or anonymous memory referenced by a static. . (mem, None) . } . Some(GlobalAlloc::Function(..)) => throw_ub!(DerefFunctionPointer(id)), . None => throw_ub!(PointerUseAfterFree(id)), . Some(GlobalAlloc::Static(def_id)) => { . assert!(self.tcx.is_static(def_id)); . assert!(!self.tcx.is_thread_local_static(def_id)); -- line 527 ---------------------------------------- -- line 537 ---------------------------------------- . // to another static), those inner references only exist in "resolved" form. . if self.tcx.is_foreign_item(def_id) { . throw_unsup!(ReadExternStatic(def_id)); . } . . (self.tcx.eval_static_initializer(def_id)?, Some(def_id)) . } . }; 41,456 ( 0.02%) M::before_access_global(&self.extra, id, alloc, def_id, is_write)?; . let alloc = Cow::Borrowed(alloc); . // We got tcx memory. Let the machine initialize its "extra" stuff. . let alloc = M::init_allocation_extra( . self, . id, // always use the ID we got as input, not the "hidden" one. . alloc, . M::GLOBAL_KIND.map(MemoryKind::Machine), . ); 20,728 ( 0.01%) Ok(alloc) 41,456 ( 0.02%) } . . /// Gives raw access to the `Allocation`, without bounds or alignment checks. . /// The caller is responsible for calling the access hooks! 25,910 ( 0.01%) fn get_raw( . &self, . id: AllocId, . ) -> InterpResult<'tcx, &Allocation> { . // The error type of the inner closure here is somewhat funny. We have two . // ways of "erroring": An actual error, or because we got a reference from . // `get_global_alloc` that we can actually use directly without inserting anything anywhere. . // So the error type is `InterpResult<'tcx, &Allocation>`. . let a = self.alloc_map.get_or(id, || { 20,728 ( 0.01%) let alloc = self.get_global_alloc(id, /*is_write*/ false).map_err(Err)?; 10,364 ( 0.01%) match alloc { . Cow::Borrowed(alloc) => { . // We got a ref, cheaply return that as an "error" so that the . // map does not get mutated. . Err(Ok(alloc)) . } . Cow::Owned(alloc) => { . // Need to put it into the map and return a ref to that . let kind = M::GLOBAL_KIND.expect( -- line 577 ---------------------------------------- -- line 578 ---------------------------------------- . "I got a global allocation that I have to copy but the machine does \ . not expect that to happen", . ); . Ok((MemoryKind::Machine(kind), alloc)) . } . } . }); . // Now unpack that funny error type 2,592 ( 0.00%) match a { . Ok(a) => Ok(&a.1), . Err(a) => a, . } 19,434 ( 0.01%) } . . /// "Safe" (bounds and align-checked) allocation access. 69,972 ( 0.04%) pub fn get<'a>( . &'a self, . ptr: Pointer>, . size: Size, . align: Align, . ) -> InterpResult<'tcx, Option>> { . let align = M::enforce_alignment(&self.extra).then_some(align); . let ptr_and_alloc = self.check_and_deref_ptr( . ptr, . size, . align, . CheckInAllocMsg::MemoryAccessTest, . |alloc_id, offset, ptr| { 23,324 ( 0.01%) let alloc = self.get_raw(alloc_id)?; . Ok((alloc.size(), alloc.align, (alloc_id, offset, ptr, alloc))) . }, . )?; 11,658 ( 0.01%) if let Some((alloc_id, offset, ptr, alloc)) = ptr_and_alloc { . let range = alloc_range(offset, size); . M::memory_read(&self.extra, &alloc.extra, ptr.provenance, range)?; 40,817 ( 0.02%) Ok(Some(AllocRef { alloc, range, tcx: self.tcx, alloc_id })) . } else { . // Even in this branch we have to be sure that we actually access the allocation, in . // order to ensure that `static FOO: Type = FOO;` causes a cycle error instead of . // magically pulling *any* ZST value from the ether. However, the `get_raw` above is . // always called when `ptr` has an `AllocId`. . Ok(None) . } 52,479 ( 0.03%) } . . /// Return the `extra` field of the given allocation. . pub fn get_alloc_extra<'a>(&'a self, id: AllocId) -> InterpResult<'tcx, &'a M::AllocExtra> { . Ok(&self.get_raw(id)?.extra) . } . . /// Gives raw mutable access to the `Allocation`, without bounds or alignment checks. . /// The caller is responsible for calling the access hooks! . /// . /// Also returns a ptr to `self.extra` so that the caller can use it in parallel with the . /// allocation. 25,992 ( 0.01%) fn get_raw_mut( . &mut self, . id: AllocId, . ) -> InterpResult<'tcx, (&mut Allocation, &mut M::MemoryExtra)> . { . // We have "NLL problem case #3" here, which cannot be worked around without loss of . // efficiency even for the common case where the key is in the map. . // . // (Cannot use `get_mut_or` since `get_global_alloc` needs `&self`.) 3,249 ( 0.00%) if self.alloc_map.get_mut(id).is_none() { . // Slow path. . // Allocation not found locally, go look global. . let alloc = self.get_global_alloc(id, /*is_write*/ true)?; . let kind = M::GLOBAL_KIND.expect( . "I got a global allocation that I have to copy but the machine does \ . not expect that to happen", . ); . self.alloc_map.insert(id, (MemoryKind::Machine(kind), alloc.into_owned())); . } . 3,249 ( 0.00%) let (_kind, alloc) = self.alloc_map.get_mut(id).unwrap(); 3,249 ( 0.00%) if alloc.mutability == Mutability::Not { . throw_ub!(WriteToReadOnly(id)) . } 12,986 ( 0.01%) Ok((alloc, &mut self.extra)) 16,245 ( 0.01%) } . . /// "Safe" (bounds and align-checked) allocation access. 31,224 ( 0.02%) pub fn get_mut<'a>( . &'a mut self, . ptr: Pointer>, . size: Size, . align: Align, . ) -> InterpResult<'tcx, Option>> { . let parts = self.get_ptr_access(ptr, size, align)?; 5,184 ( 0.00%) if let Some((alloc_id, offset, ptr)) = parts { . let tcx = self.tcx; . // FIXME: can we somehow avoid looking up the allocation twice here? . // We cannot call `get_raw_mut` inside `check_and_deref_ptr` as that would duplicate `&mut self`. 7,806 ( 0.00%) let (alloc, extra) = self.get_raw_mut(alloc_id)?; . let range = alloc_range(offset, size); . M::memory_written(extra, &mut alloc.extra, ptr.provenance, range)?; 15,612 ( 0.01%) Ok(Some(AllocRefMut { alloc, range, tcx, alloc_id })) . } else { . Ok(None) . } 23,418 ( 0.01%) } . . /// Return the `extra` field of the given allocation. . pub fn get_alloc_extra_mut<'a>( . &'a mut self, . id: AllocId, . ) -> InterpResult<'tcx, (&'a mut M::AllocExtra, &'a mut M::MemoryExtra)> { . let (alloc, memory_extra) = self.get_raw_mut(id)?; . Ok((&mut alloc.extra, memory_extra)) . } . . /// Obtain the size and alignment of an allocation, even if that allocation has . /// been deallocated. . /// . /// If `liveness` is `AllocCheck::MaybeDead`, this function always returns `Ok`. 42,900 ( 0.02%) pub fn get_size_and_align( . &self, . id: AllocId, . liveness: AllocCheck, . ) -> InterpResult<'static, (Size, Align)> { . // # Regular allocations . // Don't use `self.get_raw` here as that will . // a) cause cycles in case `id` refers to a static . // b) duplicate a global's allocation in miri 19,500 ( 0.01%) if let Some((_, alloc)) = self.alloc_map.get(id) { 3,896 ( 0.00%) return Ok((alloc.size(), alloc.align)); . } . . // # Function pointers . // (both global from `alloc_map` and local from `extra_fn_ptr_map`) 16 ( 0.00%) if self.get_fn_alloc(id).is_some() { . return if let AllocCheck::Dereferenceable = liveness { . // The caller requested no function pointers. . throw_ub!(DerefFunctionPointer(id)) . } else { . Ok((Size::ZERO, Align::ONE)) . }; . } . . // # Statics . // Can't do this in the match argument, we may get cycle errors since the lock would . // be held throughout the match. 44 ( 0.00%) match self.tcx.get_global_alloc(id) { . Some(GlobalAlloc::Static(did)) => { . assert!(!self.tcx.is_thread_local_static(did)); . // Use size and align of the type. . let ty = self.tcx.type_of(did); . let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap(); . Ok((layout.size, layout.align.abi)) . } 4 ( 0.00%) Some(GlobalAlloc::Memory(alloc)) => { . // Need to duplicate the logic here, because the global allocations have . // different associated types than the interpreter-local ones. 8 ( 0.00%) Ok((alloc.size(), alloc.align)) . } . Some(GlobalAlloc::Function(_)) => bug!("We already checked function pointers above"), . // The rest must be dead. . None => { . if let AllocCheck::MaybeDead = liveness { . // Deallocated pointers are allowed, we should be able to find . // them in the map. . Ok(*self -- line 740 ---------------------------------------- -- line 741 ---------------------------------------- . .dead_alloc_map . .get(&id) . .expect("deallocated pointers should all be recorded in `dead_alloc_map`")) . } else { . throw_ub!(PointerUseAfterFree(id)) . } . } . } 31,200 ( 0.02%) } . 16 ( 0.00%) fn get_fn_alloc(&self, id: AllocId) -> Option> { . if let Some(extra) = self.extra_fn_ptr_map.get(&id) { . Some(FnVal::Other(*extra)) . } else { 20 ( 0.00%) match self.tcx.get_global_alloc(id) { . Some(GlobalAlloc::Function(instance)) => Some(FnVal::Instance(instance)), 4 ( 0.00%) _ => None, . } . } 16 ( 0.00%) } . . pub fn get_fn( . &self, . ptr: Pointer>, . ) -> InterpResult<'tcx, FnVal<'tcx, M::ExtraFnVal>> { . trace!("get_fn({:?})", ptr); . let (alloc_id, offset, _ptr) = self.ptr_get_alloc(ptr)?; . if offset.bytes() != 0 { -- line 768 ---------------------------------------- -- line 903 ---------------------------------------- . writeln!(fmt)?; . } . Ok(()) . } . } . . /// Reading and writing. . impl<'tcx, 'a, Tag: Provenance, Extra> AllocRefMut<'a, 'tcx, Tag, Extra> { 23,427 ( 0.01%) pub fn write_scalar( . &mut self, . range: AllocRange, . val: ScalarMaybeUninit, . ) -> InterpResult<'tcx> { 13,015 ( 0.01%) Ok(self . .alloc 28,633 ( 0.01%) .write_scalar(&self.tcx, self.range.subrange(range), val) . .map_err(|e| e.to_interp_error(self.alloc_id))?) 15,618 ( 0.01%) } . . pub fn write_ptr_sized( . &mut self, . offset: Size, . val: ScalarMaybeUninit, . ) -> InterpResult<'tcx> { . self.write_scalar(alloc_range(offset, self.tcx.data_layout().pointer_size), val) . } . } . . impl<'tcx, 'a, Tag: Provenance, Extra> AllocRef<'a, 'tcx, Tag, Extra> { 16 ( 0.00%) pub fn read_scalar(&self, range: AllocRange) -> InterpResult<'tcx, ScalarMaybeUninit> { 57,040 ( 0.03%) Ok(self . .alloc 31,118 ( 0.02%) .read_scalar(&self.tcx, self.range.subrange(range)) . .map_err(|e| e.to_interp_error(self.alloc_id))?) 16 ( 0.00%) } . . pub fn read_ptr_sized(&self, offset: Size) -> InterpResult<'tcx, ScalarMaybeUninit> { . self.read_scalar(alloc_range(offset, self.tcx.data_layout().pointer_size)) . } . . pub fn check_bytes(&self, range: AllocRange, allow_uninit_and_ptr: bool) -> InterpResult<'tcx> { . Ok(self . .alloc -- line 945 ---------------------------------------- -- line 1016 ---------------------------------------- . &mut self, . src: Pointer>, . src_align: Align, . dest: Pointer>, . dest_align: Align, . size: Size, . nonoverlapping: bool, . ) -> InterpResult<'tcx> { 3,235 ( 0.00%) self.copy_repeatedly(src, src_align, dest, dest_align, size, 1, nonoverlapping) . } . 8,411 ( 0.00%) pub fn copy_repeatedly( . &mut self, . src: Pointer>, . src_align: Align, . dest: Pointer>, . dest_align: Align, . size: Size, . num_copies: u64, . nonoverlapping: bool, . ) -> InterpResult<'tcx> { 1,294 ( 0.00%) let tcx = self.tcx; . // We need to do our own bounds-checks. . let src_parts = self.get_ptr_access(src, size, src_align)?; . let dest_parts = self.get_ptr_access(dest, size * num_copies, dest_align)?; // `Size` multiplication . . // FIXME: we look up both allocations twice here, once ebfore for the `check_ptr_access` . // and once below to get the underlying `&[mut] Allocation`. . . // Source alloc preparations and access hooks. 1,294 ( 0.00%) let (src_alloc_id, src_offset, src) = match src_parts { . None => return Ok(()), // Zero-sized *source*, that means dst is also zero-sized and we have nothing to do. . Some(src_ptr) => src_ptr, . }; 2,588 ( 0.00%) let src_alloc = self.get_raw(src_alloc_id)?; . let src_range = alloc_range(src_offset, size); . M::memory_read(&self.extra, &src_alloc.extra, src.provenance, src_range)?; . // We need the `dest` ptr for the next operation, so we get it now. . // We already did the source checks and called the hooks so we are good to return early. 1,294 ( 0.00%) let (dest_alloc_id, dest_offset, dest) = match dest_parts { . None => return Ok(()), // Zero-sized *destiantion*. . Some(dest_ptr) => dest_ptr, . }; . . // This checks relocation edges on the src, which needs to happen before . // `prepare_relocation_copy`. . let src_bytes = src_alloc . .get_bytes_with_uninit_and_ptr(&tcx, src_range) . .map_err(|e| e.to_interp_error(src_alloc_id))? . .as_ptr(); // raw ptr, so we can also get a ptr to the destination allocation . // first copy the relocations to a temporary buffer, because . // `get_bytes_mut` will clear the relocations, which is correct, . // since we don't want to keep any relocations at the target. . let relocations = 7,764 ( 0.00%) src_alloc.prepare_relocation_copy(self, src_range, dest_offset, num_copies); . // Prepare a copy of the initialization mask. 2,588 ( 0.00%) let compressed = src_alloc.compress_uninit_range(src_range); . . // Destination alloc preparations and access hooks. 1,941 ( 0.00%) let (dest_alloc, extra) = self.get_raw_mut(dest_alloc_id)?; 1,941 ( 0.00%) let dest_range = alloc_range(dest_offset, size * num_copies); . M::memory_written(extra, &mut dest_alloc.extra, dest.provenance, dest_range)?; 2,588 ( 0.00%) let dest_bytes = dest_alloc . .get_bytes_mut_ptr(&tcx, dest_range) . .map_err(|e| e.to_interp_error(dest_alloc_id))? . .as_mut_ptr(); . 1,941 ( 0.00%) if compressed.no_bytes_init() { . // Fast path: If all bytes are `uninit` then there is nothing to copy. The target range . // is marked as uninitialized but we otherwise omit changing the byte representation which may . // be arbitrary for uninitialized bytes. . // This also avoids writing to the target bytes so that the backing allocation is never . // touched if the bytes stay uninitialized for the whole interpreter execution. On contemporary . // operating system this can avoid physically allocating the page. . dest_alloc.mark_init(dest_range, false); // `Size` multiplication . dest_alloc.mark_relocation_range(relocations); -- line 1091 ---------------------------------------- -- line 1093 ---------------------------------------- . } . . // SAFE: The above indexing would have panicked if there weren't at least `size` bytes . // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and . // `dest` could possibly overlap. . // The pointers above remain valid even if the `HashMap` table is moved around because they . // point into the `Vec` storing the bytes. . unsafe { 647 ( 0.00%) if src_alloc_id == dest_alloc_id { . if nonoverlapping { . // `Size` additions . if (src_offset <= dest_offset && src_offset + size > dest_offset) . || (dest_offset <= src_offset && dest_offset + size > src_offset) . { . throw_ub_format!("copy_nonoverlapping called on overlapping ranges") . } . } -- line 1109 ---------------------------------------- -- line 1114 ---------------------------------------- . dest_bytes.add((size * i).bytes_usize()), // `Size` multiplication . size.bytes_usize(), . ); . } . } else { . for i in 0..num_copies { . ptr::copy_nonoverlapping( . src_bytes, 1,941 ( 0.00%) dest_bytes.add((size * i).bytes_usize()), // `Size` multiplication . size.bytes_usize(), . ); . } . } . } . . // now fill in all the "init" data 3,235 ( 0.00%) dest_alloc.mark_compressed_init_range( . &compressed, . alloc_range(dest_offset, size), // just a single copy (i.e., not full `dest_range`) . num_copies, . ); . // copy the relocations to the destination 5,823 ( 0.00%) dest_alloc.mark_relocation_range(relocations); . . Ok(()) 5,823 ( 0.00%) } . } . . /// Machine pointer introspection. . impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { 6 ( 0.00%) pub fn scalar_to_ptr(&self, scalar: Scalar) -> Pointer> { . // We use `to_bits_or_ptr_internal` since we are just implementing the method people need to . // call to force getting out a pointer. 30 ( 0.00%) match scalar.to_bits_or_ptr_internal(self.pointer_size()) { . Err(ptr) => ptr.into(), . Ok(bits) => { . let addr = u64::try_from(bits).unwrap(); . let ptr = M::ptr_from_addr(&self, addr); . if addr == 0 { . assert!(ptr.provenance.is_none(), "null pointer can never have an AllocId"); . } . ptr . } . } 12 ( 0.00%) } . . /// Turning a "maybe pointer" into a proper pointer (and some information . /// about where it points), or an absolute address. . pub fn ptr_try_get_alloc( . &self, . ptr: Pointer>, . ) -> Result<(AllocId, Size, Pointer), u64> { . match ptr.into_pointer_or_addr() { -- line 1166 ---------------------------------------- 70,723 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs -------------------------------------------------------------------------------- Ir -- line 12 ---------------------------------------- . use rustc_data_structures::sync::Lrc; . use rustc_macros::HashStable_Generic; . use rustc_span::symbol::{kw, sym}; . use rustc_span::symbol::{Ident, Symbol}; . use rustc_span::{self, edition::Edition, Span, DUMMY_SP}; . use std::borrow::Cow; . use std::{fmt, mem}; . 1,434 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum CommentKind { . Line, . Block, . } . 14 ( 0.00%) #[derive(Clone, PartialEq, Encodable, Decodable, Hash, Debug, Copy)] . #[derive(HashStable_Generic)] . pub enum BinOpToken { . Plus, . Minus, . Star, . Slash, . Percent, . Caret, . And, . Or, . Shl, . Shr, . } . . /// A delimiter token. 4,301 ( 0.00%) #[derive(Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug, Copy)] . #[derive(HashStable_Generic)] . pub enum DelimToken { . /// A round parenthesis (i.e., `(` or `)`). . Paren, . /// A square bracket (i.e., `[` or `]`). . Bracket, . /// A curly brace (i.e., `{` or `}`). . Brace, . /// An empty delimiter. . NoDelim, . } . 109 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum LitKind { . Bool, // AST only, must never appear in a `Token` . Byte, . Char, . Integer, . Float, . Str, . StrRaw(u16), // raw string delimited by `n` hash symbols . ByteStr, . ByteStrRaw(u16), // raw byte string delimited by `n` hash symbols . Err, . } . . /// A literal token. 5,725 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Lit { . pub kind: LitKind, . pub symbol: Symbol, . pub suffix: Option, . } . . impl fmt::Display for Lit { 12,935 ( 0.01%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 23,283 ( 0.01%) let Lit { kind, symbol, suffix } = *self; . match kind { . Byte => write!(f, "b'{}'", symbol)?, 3,876 ( 0.00%) Char => write!(f, "'{}'", symbol)?, . Str => write!(f, "\"{}\"", symbol)?, . StrRaw(n) => write!( . f, . "r{delim}\"{string}\"{delim}", . delim = "#".repeat(n as usize), . string = symbol . )?, . ByteStr => write!(f, "b\"{}\"", symbol)?, . ByteStrRaw(n) => write!( . f, . "br{delim}\"{string}\"{delim}", . delim = "#".repeat(n as usize), . string = symbol . )?, 3,885 ( 0.00%) Integer | Float | Bool | Err => write!(f, "{}", symbol)?, . } . 5,174 ( 0.00%) if let Some(suffix) = suffix { . write!(f, "{}", suffix)?; . } . . Ok(()) 12,935 ( 0.01%) } . } . . impl LitKind { . /// An English article for the literal token kind. . pub fn article(self) -> &'static str { . match self { . Integer | Err => "an", . _ => "a", -- line 113 ---------------------------------------- -- line 130 ---------------------------------------- . crate fn may_have_suffix(self) -> bool { . matches!(self, Integer | Float | Err) . } . } . . impl Lit { . pub fn new(kind: LitKind, symbol: Symbol, suffix: Option) -> Lit { . Lit { kind, symbol, suffix } 18,121 ( 0.01%) } . } . . pub fn ident_can_begin_expr(name: Symbol, span: Span, is_raw: bool) -> bool { . let ident_token = Token::new(Ident(name, is_raw), span); . . !ident_token.is_reserved_ident() . || ident_token.is_path_segment_keyword() . || [ -- line 146 ---------------------------------------- -- line 164 ---------------------------------------- . kw::While, . kw::Yield, . kw::Static, . ] . .contains(&name) . } . . fn ident_can_begin_type(name: Symbol, span: Span, is_raw: bool) -> bool { 30 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 10 ( 0.00%) !ident_token.is_reserved_ident() . || ident_token.is_path_segment_keyword() . || [kw::Underscore, kw::For, kw::Impl, kw::Fn, kw::Unsafe, kw::Extern, kw::Typeof, kw::Dyn] . .contains(&name) . } . 660,447 ( 0.33%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum TokenKind { . /* Expression-operator symbols. */ . Eq, . Lt, . Le, . EqEq, . Ne, . Ge, . Gt, . AndAnd, . OrOr, . Not, . Tilde, 669 ( 0.00%) BinOp(BinOpToken), . BinOpEq(BinOpToken), . . /* Structural symbols */ . At, . Dot, . DotDot, . DotDotDot, . DotDotEq, -- line 202 ---------------------------------------- -- line 208 ---------------------------------------- . LArrow, . FatArrow, . Pound, . Dollar, . Question, . /// Used by proc macros for representing lifetimes, not generated by lexer right now. . SingleQuote, . /// An opening delimiter (e.g., `{`). 1,146 ( 0.00%) OpenDelim(DelimToken), . /// A closing delimiter (e.g., `}`). 19,857 ( 0.01%) CloseDelim(DelimToken), . . /* Literals */ 8,259 ( 0.00%) Literal(Lit), . . /// Identifier token. . /// Do not forget about `NtIdent` when you want to match on identifiers. . /// It's recommended to use `Token::(ident,uninterpolate,uninterpolated_span)` to . /// treat regular and interpolated identifiers in the same way. 554 ( 0.00%) Ident(Symbol, /* is_raw */ bool), . /// Lifetime identifier token. . /// Do not forget about `NtLifetime` when you want to match on lifetime identifiers. . /// It's recommended to use `Token::(lifetime,uninterpolate,uninterpolated_span)` to . /// treat regular and interpolated lifetime identifiers in the same way. 18 ( 0.00%) Lifetime(Symbol), . . Interpolated(Lrc), . . /// A doc comment token. . /// `Symbol` is the doc comment's data excluding its "quotes" (`///`, `/**`, etc) . /// similarly to symbols in string literal tokens. 201 ( 0.00%) DocComment(CommentKind, ast::AttrStyle, Symbol), . . Eof, . } . . // `TokenKind` is used a lot. Make sure it doesn't unintentionally get bigger. . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(TokenKind, 16); . 27,764 ( 0.01%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Token { 406 ( 0.00%) pub kind: TokenKind, . pub span: Span, . } . . impl TokenKind { . pub fn lit(kind: LitKind, symbol: Symbol, suffix: Option) -> TokenKind { . Literal(Lit::new(kind, symbol, suffix)) . } . . // An approximation to proc-macro-style single-character operators used by rustc parser. . // If the operator token can be broken into two tokens, the first of which is single-character, . // then this function performs that operation, otherwise it returns `None`. 79 ( 0.00%) pub fn break_two_token_op(&self) -> Option<(TokenKind, TokenKind)> { 316 ( 0.00%) Some(match *self { . Le => (Lt, Eq), . EqEq => (Eq, Eq), . Ne => (Not, Eq), . Ge => (Gt, Eq), . AndAnd => (BinOp(And), BinOp(And)), . OrOr => (BinOp(Or), BinOp(Or)), . BinOp(Shl) => (Lt, Lt), . BinOp(Shr) => (Gt, Gt), -- line 271 ---------------------------------------- -- line 280 ---------------------------------------- . BinOpEq(Shl) => (Lt, Le), . BinOpEq(Shr) => (Gt, Ge), . DotDot => (Dot, Dot), . DotDotDot => (Dot, DotDot), . ModSep => (Colon, Colon), . RArrow => (BinOp(Minus), Gt), . LArrow => (Lt, BinOp(Minus)), . FatArrow => (Eq, Gt), 79 ( 0.00%) _ => return None, . }) 79 ( 0.00%) } . . /// Returns tokens that are likely to be typed accidentally instead of the current token. . /// Enables better error recovery when the wrong token is found. . pub fn similar_tokens(&self) -> Option> { . match *self { . Comma => Some(vec![Dot, Lt, Semi]), . Semi => Some(vec![Colon, Comma]), . FatArrow => Some(vec![Eq, RArrow]), . _ => None, . } . } . . pub fn should_end_const_arg(&self) -> bool { 20 ( 0.00%) matches!(self, Gt | Ge | BinOp(Shr) | BinOpEq(Shr)) 5 ( 0.00%) } . } . . impl Token { 7,931 ( 0.00%) pub fn new(kind: TokenKind, span: Span) -> Self { 23,987 ( 0.01%) Token { kind, span } 7,931 ( 0.00%) } . . /// Some token that will be thrown away later. 58 ( 0.00%) pub fn dummy() -> Self { . Token::new(TokenKind::Question, DUMMY_SP) 58 ( 0.00%) } . . /// Recovers a `Token` from an `Ident`. This creates a raw identifier if necessary. . pub fn from_ast_ident(ident: Ident) -> Self { . Token::new(Ident(ident.name, ident.is_raw_guess()), ident.span) . } . . /// Return this token by value and leave a dummy token in its place. 5,724 ( 0.00%) pub fn take(&mut self) -> Self { . mem::replace(self, Token::dummy()) 5,724 ( 0.00%) } . . /// For interpolated tokens, returns a span of the fragment to which the interpolated . /// token refers. For all other tokens this is just a regular span. . /// It is particularly important to use this for identifiers and lifetimes . /// for which spans affect name resolution and edition checks. . /// Note that keywords are also identifiers, so they should use this . /// if they keep spans or perform edition checks. . pub fn uninterpolated_span(&self) -> Span { 36 ( 0.00%) match &self.kind { . Interpolated(nt) => nt.span(), 18 ( 0.00%) _ => self.span, . } 18 ( 0.00%) } . . pub fn is_op(&self) -> bool { 17,172 ( 0.01%) !matches!( 5,724 ( 0.00%) self.kind, . OpenDelim(..) . | CloseDelim(..) . | Literal(..) . | DocComment(..) . | Ident(..) . | Lifetime(..) . | Interpolated(..) . | Eof . ) 5,724 ( 0.00%) } . . pub fn is_like_plus(&self) -> bool { 365 ( 0.00%) matches!(self.kind, BinOp(Plus) | BinOpEq(Plus)) 73 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of an expression. . pub fn can_begin_expr(&self) -> bool { . match self.uninterpolate().kind { . Ident(name, is_raw) => . ident_can_begin_expr(name, self.span, is_raw), // value name or keyword . OpenDelim(..) | // tuple, array or block . Literal(..) | // literal -- line 365 ---------------------------------------- -- line 379 ---------------------------------------- . NtExpr(..) | . NtBlock(..) | . NtPath(..)), . _ => false, . } . } . . /// Returns `true` if the token can appear at the start of a type. 20 ( 0.00%) pub fn can_begin_type(&self) -> bool { 25 ( 0.00%) match self.uninterpolate().kind { 45 ( 0.00%) Ident(name, is_raw) => 5 ( 0.00%) ident_can_begin_type(name, self.span, is_raw), // type name or keyword . OpenDelim(Paren) | // tuple . OpenDelim(Bracket) | // array . Not | // never . BinOp(Star) | // raw pointer . BinOp(And) | // reference . AndAnd | // double reference . Question | // maybe bound in trait object . Lifetime(..) | // lifetime bound in trait object . Lt | BinOp(Shl) | // associated path . ModSep => true, // global path . Interpolated(ref nt) => matches!(**nt, NtTy(..) | NtPath(..)), . _ => false, . } 30 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a const param. . pub fn can_begin_const_arg(&self) -> bool { 25 ( 0.00%) match self.kind { . OpenDelim(Brace) => true, . Interpolated(ref nt) => matches!(**nt, NtExpr(..) | NtBlock(..) | NtLiteral(..)), 5 ( 0.00%) _ => self.can_begin_literal_maybe_minus(), . } . } . . /// Returns `true` if the token can appear at the start of a generic bound. . pub fn can_begin_bound(&self) -> bool { . self.is_path_start() . || self.is_lifetime() . || self.is_keyword(kw::For) -- line 419 ---------------------------------------- -- line 427 ---------------------------------------- . } . . /// Returns `true` if the token is any literal, a minus (which can prefix a literal, . /// for example a '-42', or one of the boolean idents). . /// . /// In other words, would this token be a valid start of `parse_literal_maybe_minus`? . /// . /// Keep this in sync with and `Lit::from_token`, excluding unary negation. 7 ( 0.00%) pub fn can_begin_literal_maybe_minus(&self) -> bool { 70 ( 0.00%) match self.uninterpolate().kind { . Literal(..) | BinOp(Minus) => true, 28 ( 0.00%) Ident(name, false) if name.is_bool_lit() => true, . Interpolated(ref nt) => match &**nt { . NtLiteral(_) => true, . NtExpr(e) => match &e.kind { . ast::ExprKind::Lit(_) => true, . ast::ExprKind::Unary(ast::UnOp::Neg, e) => { . matches!(&e.kind, ast::ExprKind::Lit(_)) . } . _ => false, . }, . _ => false, . }, . _ => false, . } 14 ( 0.00%) } . . // A convenience function for matching on identifiers during parsing. . // Turns interpolated identifier (`$i: ident`) or lifetime (`$l: lifetime`) token . // into the regular identifier or lifetime token it refers to, . // otherwise returns the original token. 3,335 ( 0.00%) pub fn uninterpolate(&self) -> Cow<'_, Token> { 38,152 ( 0.02%) match &self.kind { . Interpolated(nt) => match **nt { . NtIdent(ident, is_raw) => { . Cow::Owned(Token::new(Ident(ident.name, is_raw), ident.span)) . } . NtLifetime(ident) => Cow::Owned(Token::new(Lifetime(ident.name), ident.span)), . _ => Cow::Borrowed(self), . }, . _ => Cow::Borrowed(self), . } 3,335 ( 0.00%) } . . /// Returns an identifier if this token is an identifier. 10,237 ( 0.01%) pub fn ident(&self) -> Option<(Ident, /* is_raw */ bool)> { . let token = self.uninterpolate(); 23,977 ( 0.01%) match token.kind { 21,490 ( 0.01%) Ident(name, is_raw) => Some((Ident::new(name, token.span), is_raw)), . _ => None, . } 62,577 ( 0.03%) } . . /// Returns a lifetime identifier if this token is a lifetime. 20 ( 0.00%) pub fn lifetime(&self) -> Option { . let token = self.uninterpolate(); 68 ( 0.00%) match token.kind { 84 ( 0.00%) Lifetime(name) => Some(Ident::new(name, token.span)), . _ => None, . } 140 ( 0.00%) } . . /// Returns `true` if the token is an identifier. . pub fn is_ident(&self) -> bool { . self.ident().is_some() 45 ( 0.00%) } . . /// Returns `true` if the token is a lifetime. 14 ( 0.00%) pub fn is_lifetime(&self) -> bool { . self.lifetime().is_some() 28 ( 0.00%) } . . /// Returns `true` if the token is an identifier whose name is the given . /// string slice. 39 ( 0.00%) pub fn is_ident_named(&self, name: Symbol) -> bool { . self.ident().map_or(false, |(ident, _)| ident.name == name) 78 ( 0.00%) } . . /// Returns `true` if the token is an interpolated path. . fn is_path(&self) -> bool { 380 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtPath(..) = **nt { . return true; . } . } . false . } . . /// Would `maybe_whole_expr` in `parser.rs` return `Ok(..)`? -- line 515 ---------------------------------------- -- line 522 ---------------------------------------- . } . } . . false . } . . // Is the token an interpolated block (`$b:block`)? . pub fn is_whole_block(&self) -> bool { 4 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtBlock(..) = **nt { . return true; . } . } . false 2 ( 0.00%) } . . /// Returns `true` if the token is either the `mut` or `const` keyword. . pub fn is_mutability(&self) -> bool { . self.is_keyword(kw::Mut) || self.is_keyword(kw::Const) . } . 18 ( 0.00%) pub fn is_qpath_start(&self) -> bool { 208 ( 0.00%) self == &Lt || self == &BinOp(Shl) . } . 380 ( 0.00%) pub fn is_path_start(&self) -> bool { 562 ( 0.00%) self == &ModSep . || self.is_qpath_start() . || self.is_path() . || self.is_path_segment_keyword() 91 ( 0.00%) || self.is_ident() && !self.is_reserved_ident() 475 ( 0.00%) } . . /// Returns `true` if the token is a given keyword, `kw`. 1,372 ( 0.00%) pub fn is_keyword(&self, kw: Symbol) -> bool { . self.is_non_raw_ident_where(|id| id.name == kw) 2,744 ( 0.00%) } . 18 ( 0.00%) pub fn is_path_segment_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_path_segment_keyword) . } . . // Returns true for reserved identifiers used internally for elided lifetimes, . // unnamed method parameters, crate root module, error recovery etc. 10 ( 0.00%) pub fn is_special_ident(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_special) . } . . /// Returns `true` if the token is a keyword used in the language. 10 ( 0.00%) pub fn is_used_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_used_keyword) . } . . /// Returns `true` if the token is a keyword reserved for possible future use. 10 ( 0.00%) pub fn is_unused_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_unused_keyword) . } . . /// Returns `true` if the token is either a special identifier or a keyword. . pub fn is_reserved_ident(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_reserved) . } . . /// Returns `true` if the token is the identifier `true` or `false`. 18 ( 0.00%) pub fn is_bool_lit(&self) -> bool { 36 ( 0.00%) self.is_non_raw_ident_where(|id| id.name.is_bool_lit()) . } . . pub fn is_numeric_lit(&self) -> bool { . matches!( . self.kind, . Literal(Lit { kind: LitKind::Integer, .. }) | Literal(Lit { kind: LitKind::Float, .. }) . ) . } . . /// Returns `true` if the token is a non-raw identifier for which `pred` holds. 4 ( 0.00%) pub fn is_non_raw_ident_where(&self, pred: impl FnOnce(Ident) -> bool) -> bool { 54,828 ( 0.03%) match self.ident() { 90 ( 0.00%) Some((id, false)) => pred(id), . _ => false, . } 5 ( 0.00%) } . 20,790 ( 0.01%) pub fn glue(&self, joint: &Token) -> Option { 10,395 ( 0.01%) let kind = match self.kind { 35 ( 0.00%) Eq => match joint.kind { . Eq => EqEq, . Gt => FatArrow, . _ => return None, . }, 6 ( 0.00%) Lt => match joint.kind { . Eq => Le, . Lt => BinOp(Shl), . Le => BinOpEq(Shl), . BinOp(Minus) => LArrow, . _ => return None, . }, 14 ( 0.00%) Gt => match joint.kind { . Eq => Ge, . Gt => BinOp(Shr), . Ge => BinOpEq(Shr), . _ => return None, . }, . Not => match joint.kind { . Eq => Ne, . _ => return None, . }, 86 ( 0.00%) BinOp(op) => match joint.kind { . Eq => BinOpEq(op), 2 ( 0.00%) BinOp(And) if op == And => AndAnd, . BinOp(Or) if op == Or => OrOr, 10 ( 0.00%) Gt if op == Minus => RArrow, . _ => return None, . }, . Dot => match joint.kind { . Dot => DotDot, . DotDot => DotDotDot, . _ => return None, . }, . DotDot => match joint.kind { . Dot => DotDotDot, . Eq => DotDotEq, . _ => return None, . }, 38 ( 0.00%) Colon => match joint.kind { . Colon => ModSep, . _ => return None, . }, . SingleQuote => match joint.kind { . Ident(name, false) => Lifetime(Symbol::intern(&format!("'{}", name))), . _ => return None, . }, . . Le | EqEq | Ne | Ge | AndAnd | OrOr | Tilde | BinOpEq(..) | At | DotDotDot . | DotDotEq | Comma | Semi | ModSep | RArrow | LArrow | FatArrow | Pound | Dollar . | Question | OpenDelim(..) | CloseDelim(..) | Literal(..) | Ident(..) . | Lifetime(..) | Interpolated(..) | DocComment(..) | Eof => return None, . }; . 507 ( 0.00%) Some(Token::new(kind, self.span.to(joint.span))) 18,711 ( 0.01%) } . } . . impl PartialEq for Token { . fn eq(&self, rhs: &TokenKind) -> bool { 31,095 ( 0.02%) self.kind == *rhs . } . } . . #[derive(Clone, Encodable, Decodable)] . /// For interpolation during macro expansion. . pub enum Nonterminal { . NtItem(P), . NtBlock(P), -- line 675 ---------------------------------------- -- line 711 ---------------------------------------- . Path, . Vis, . TT, . } . . impl NonterminalKind { . /// The `edition` closure is used to get the edition for the given symbol. Doing . /// `span.edition()` is expensive, so we do it lazily. 4 ( 0.00%) pub fn from_symbol( . symbol: Symbol, . edition: impl FnOnce() -> Edition, . ) -> Option { 10 ( 0.00%) Some(match symbol { . sym::item => NonterminalKind::Item, . sym::block => NonterminalKind::Block, . sym::stmt => NonterminalKind::Stmt, . sym::pat => match edition() { . Edition::Edition2015 | Edition::Edition2018 => { . NonterminalKind::PatParam { inferred: true } . } . Edition::Edition2021 => NonterminalKind::PatWithOr, -- line 731 ---------------------------------------- -- line 737 ---------------------------------------- . sym::lifetime => NonterminalKind::Lifetime, . sym::literal => NonterminalKind::Literal, . sym::meta => NonterminalKind::Meta, . sym::path => NonterminalKind::Path, . sym::vis => NonterminalKind::Vis, . sym::tt => NonterminalKind::TT, . _ => return None, . }) 4 ( 0.00%) } . fn symbol(self) -> Symbol { . match self { . NonterminalKind::Item => sym::item, . NonterminalKind::Block => sym::block, . NonterminalKind::Stmt => sym::stmt, . NonterminalKind::PatParam { inferred: false } => sym::pat_param, . NonterminalKind::PatParam { inferred: true } | NonterminalKind::PatWithOr => sym::pat, . NonterminalKind::Expr => sym::expr, -- line 753 ---------------------------------------- 242,983 ( 0.12%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/unescape.rs -------------------------------------------------------------------------------- Ir -- line 73 ---------------------------------------- . EscapeError::UnskippedWhitespaceWarning | EscapeError::MultipleSkippedLinesWarning . ) . } . } . . /// Takes a contents of a literal (without quotes) and produces a . /// sequence of escaped characters or errors. . /// Values are returned through invoking of the provided callback. 18,178 ( 0.01%) pub fn unescape_literal(literal_text: &str, mode: Mode, callback: &mut F) . where . F: FnMut(Range, Result), . { . match mode { . Mode::Char | Mode::Byte => { 3,876 ( 0.00%) let mut chars = literal_text.chars(); 1,292 ( 0.00%) let result = unescape_char_or_byte(&mut chars, mode); . // The Chars iterator moved forward. 9,044 ( 0.00%) callback(0..(literal_text.len() - chars.as_str().len()), result); . } . Mode::Str | Mode::ByteStr => unescape_str_or_byte_str(literal_text, mode, callback), . // NOTE: Raw strings do not perform any explicit character escaping, here we . // only translate CRLF to LF and produce errors on bare CR. . Mode::RawStr | Mode::RawByteStr => { . unescape_raw_str_or_byte_str(literal_text, mode, callback) . } . } 10,376 ( 0.01%) } . . /// Takes a contents of a byte, byte string or raw byte string (without quotes) . /// and produces a sequence of bytes or errors. . /// Values are returned through invoking of the provided callback. . pub fn unescape_byte_literal(literal_text: &str, mode: Mode, callback: &mut F) . where . F: FnMut(Range, Result), . { -- line 107 ---------------------------------------- -- line 108 ---------------------------------------- . assert!(mode.is_bytes()); . unescape_literal(literal_text, mode, &mut |range, result| { . callback(range, result.map(byte_from_char)); . }) . } . . /// Takes a contents of a char literal (without quotes), and returns an . /// unescaped char or an error 7,752 ( 0.00%) pub fn unescape_char(literal_text: &str) -> Result { 5,168 ( 0.00%) let mut chars = literal_text.chars(); 2,584 ( 0.00%) unescape_char_or_byte(&mut chars, Mode::Char) . .map_err(|err| (literal_text.len() - chars.as_str().len(), err)) 7,752 ( 0.00%) } . . /// Takes a contents of a byte literal (without quotes), and returns an . /// unescaped byte or an error. . pub fn unescape_byte(literal_text: &str) -> Result { . let mut chars = literal_text.chars(); . unescape_char_or_byte(&mut chars, Mode::Byte) . .map(byte_from_char) . .map_err(|err| (literal_text.len() - chars.as_str().len(), err)) -- line 128 ---------------------------------------- -- line 136 ---------------------------------------- . Byte, . ByteStr, . RawStr, . RawByteStr, . } . . impl Mode { . pub fn in_single_quotes(self) -> bool { 10 ( 0.00%) match self { . Mode::Char | Mode::Byte => true, . Mode::Str | Mode::ByteStr | Mode::RawStr | Mode::RawByteStr => false, . } . } . 10 ( 0.00%) pub fn in_double_quotes(self) -> bool { . !self.in_single_quotes() 5 ( 0.00%) } . . pub fn is_bytes(self) -> bool { . match self { . Mode::Byte | Mode::ByteStr | Mode::RawByteStr => true, . Mode::Char | Mode::Str | Mode::RawStr => false, . } . } . } . 26,930 ( 0.01%) fn scan_escape(first_char: char, chars: &mut Chars<'_>, mode: Mode) -> Result { 13,465 ( 0.01%) if first_char != '\\' { . // Previous character was not a slash, and we don't expect it to be . // an escape-only character. . return match first_char { . '\t' | '\n' => Err(EscapeError::EscapeOnlyChar), . '\r' => Err(EscapeError::BareCarriageReturn), . '\'' if mode.in_single_quotes() => Err(EscapeError::EscapeOnlyChar), . '"' if mode.in_double_quotes() => Err(EscapeError::EscapeOnlyChar), . _ => { 109 ( 0.00%) if mode.is_bytes() && !first_char.is_ascii() { . // Byte literal can't be a non-ascii character. . return Err(EscapeError::NonAsciiCharInByte); . } . Ok(first_char) . } . }; . } . . // Previous character is '\\', try to unescape it. . 7,752 ( 0.00%) let second_char = chars.next().ok_or(EscapeError::LoneSlash)?; . . let res = match second_char { . '"' => '"', . 'n' => '\n', . 'r' => '\r', . 't' => '\t', . '\\' => '\\', . '\'' => '\'', -- line 191 ---------------------------------------- -- line 209 ---------------------------------------- . let value = value as u8; . . value as char . } . . 'u' => { . // We've parsed '\u', now we have to parse '{..}'. . 10,336 ( 0.01%) if chars.next() != Some('{') { . return Err(EscapeError::NoBraceInUnicodeEscape); . } . . // First character must be a hexadecimal digit. . let mut n_digits = 1; 20,672 ( 0.01%) let mut value: u32 = match chars.next().ok_or(EscapeError::UnclosedUnicodeEscape)? { . '_' => return Err(EscapeError::LeadingUnderscoreUnicodeEscape), . '}' => return Err(EscapeError::EmptyUnicodeEscape), 562 ( 0.00%) c => c.to_digit(16).ok_or(EscapeError::InvalidCharInUnicodeEscape)?, . }; . . // First character is valid, now parse the rest of the number . // and closing brace. . loop { 78,000 ( 0.04%) match chars.next() { . None => return Err(EscapeError::UnclosedUnicodeEscape), . Some('_') => continue, . Some('}') => { 5,168 ( 0.00%) if n_digits > 6 { . return Err(EscapeError::OverlongUnicodeEscape); . } . . // Incorrect syntax has higher priority for error reporting . // than unallowed value for a literal. . if mode.is_bytes() { . return Err(EscapeError::UnicodeEscapeInByte); . } . 7,752 ( 0.00%) break std::char::from_u32(value).ok_or_else(|| { . if value > 0x10FFFF { . EscapeError::OutOfRangeUnicodeEscape . } else { . EscapeError::LoneSurrogateUnicodeEscape . } . })?; . } . Some(c) => { . let digit = 2,770 ( 0.00%) c.to_digit(16).ok_or(EscapeError::InvalidCharInUnicodeEscape)?; 15,624 ( 0.01%) n_digits += 1; 15,624 ( 0.01%) if n_digits > 6 { . // Stop updating value since we're sure that it's is incorrect already. . continue; . } . let digit = digit as u32; 54,684 ( 0.03%) value = value * 16 + digit; . } . }; . } . } . _ => return Err(EscapeError::InvalidEscape), . }; . Ok(res) 32,316 ( 0.02%) } . 2,584 ( 0.00%) fn unescape_char_or_byte(chars: &mut Chars<'_>, mode: Mode) -> Result { . let first_char = chars.next().ok_or(EscapeError::ZeroChars)?; 12,920 ( 0.01%) let res = scan_escape(first_char, chars, mode)?; . if chars.next().is_some() { . return Err(EscapeError::MoreThanOneChar); . } . Ok(res) 12,920 ( 0.01%) } . . /// Takes a contents of a string literal (without quotes) and produces a . /// sequence of escaped characters or errors. . fn unescape_str_or_byte_str(src: &str, mode: Mode, callback: &mut F) . where . F: FnMut(Range, Result), . { 15 ( 0.00%) assert!(mode.in_double_quotes()); . let initial_len = src.len(); 5 ( 0.00%) let mut chars = src.chars(); . while let Some(first_char) = chars.next() { 545 ( 0.00%) let start = initial_len - chars.as_str().len() - first_char.len_utf8(); . 654 ( 0.00%) let unescaped_char = match first_char { . '\\' => { . let second_char = chars.clone().next(); . match second_char { . Some('\n') => { . // Rust language specification requires us to skip whitespaces . // if unescaped '\' character is followed by '\n'. . // For details see [Rust language reference] . // (https://doc.rust-lang.org/reference/tokens.html#string-literals). -- line 302 ---------------------------------------- -- line 305 ---------------------------------------- . } . _ => scan_escape(first_char, &mut chars, mode), . } . } . '\n' => Ok('\n'), . '\t' => Ok('\t'), . _ => scan_escape(first_char, &mut chars, mode), . }; 327 ( 0.00%) let end = initial_len - chars.as_str().len(); 1,417 ( 0.00%) callback(start..end, unescaped_char); . } . . fn skip_ascii_whitespace(chars: &mut Chars<'_>, start: usize, callback: &mut F) . where . F: FnMut(Range, Result), . { . let tail = chars.as_str(); . let first_non_space = tail -- line 322 ---------------------------------------- -- line 344 ---------------------------------------- . /// Takes a contents of a string literal (without quotes) and produces a . /// sequence of characters or errors. . /// NOTE: Raw strings do not perform any explicit character escaping, here we . /// only translate CRLF to LF and produce errors on bare CR. . fn unescape_raw_str_or_byte_str(literal_text: &str, mode: Mode, callback: &mut F) . where . F: FnMut(Range, Result), . { 10 ( 0.00%) assert!(mode.in_double_quotes()); . let initial_len = literal_text.len(); . . let mut chars = literal_text.chars(); . while let Some(curr) = chars.next() { . let start = initial_len - chars.as_str().len() - curr.len_utf8(); . . let result = match curr { . '\r' => Err(EscapeError::BareCarriageReturnInRawString), -- line 360 ---------------------------------------- 59,121 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs -------------------------------------------------------------------------------- Ir -- line 27 ---------------------------------------- . impl CacheEntry { . #[inline] . fn update( . &mut self, . new_file_and_idx: Option<(Lrc, usize)>, . pos: BytePos, . time_stamp: usize, . ) { 623 ( 0.00%) if let Some((file, file_idx)) = new_file_and_idx { 57 ( 0.00%) self.file = file; 84 ( 0.00%) self.file_index = file_idx; . } . 314 ( 0.00%) let line_index = self.file.lookup_line(pos).unwrap(); . let line_bounds = self.file.line_bounds(line_index); 722 ( 0.00%) self.line_number = line_index + 1; 957 ( 0.00%) self.line = line_bounds; . self.touch(time_stamp); . } . . #[inline] . fn touch(&mut self, time_stamp: usize) { 13,575 ( 0.01%) self.time_stamp = time_stamp; . } . } . . #[derive(Clone)] . pub struct CachingSourceMapView<'sm> { . source_map: &'sm SourceMap, . line_cache: [CacheEntry; 3], . time_stamp: usize, . } . . impl<'sm> CachingSourceMapView<'sm> { 102 ( 0.00%) pub fn new(source_map: &'sm SourceMap) -> CachingSourceMapView<'sm> { . let files = source_map.files(); 51 ( 0.00%) let first_file = files[0].clone(); . let entry = CacheEntry { . time_stamp: 0, . line_number: 0, . line: BytePos(0)..BytePos(0), . file: first_file, . file_index: 0, . }; . 255 ( 0.00%) CachingSourceMapView { . source_map, 357 ( 0.00%) line_cache: [entry.clone(), entry.clone(), entry], . time_stamp: 0, . } 204 ( 0.00%) } . . pub fn byte_pos_to_line_and_col( . &mut self, . pos: BytePos, . ) -> Option<(Lrc, usize, BytePos)> { . self.time_stamp += 1; . . // Check if the position is in one of the cached lines -- line 85 ---------------------------------------- -- line 106 ---------------------------------------- . }; . . let cache_entry = &mut self.line_cache[oldest]; . cache_entry.update(new_file_and_idx, pos, self.time_stamp); . . Some((cache_entry.file.clone(), cache_entry.line_number, pos - cache_entry.line.start)) . } . 48,741 ( 0.02%) pub fn span_data_to_lines_and_cols( . &mut self, . span_data: &SpanData, . ) -> Option<(Lrc, usize, BytePos, usize, BytePos)> { 27,852 ( 0.01%) self.time_stamp += 1; . . // Check if lo and hi are in the cached lines. 6,963 ( 0.00%) let lo_cache_idx = self.cache_entry_index(span_data.lo); 6,963 ( 0.00%) let hi_cache_idx = self.cache_entry_index(span_data.hi); . 13,228 ( 0.01%) if lo_cache_idx != -1 && hi_cache_idx != -1 { . // Cache hit for span lo and hi. Check if they belong to the same file. . let result = { 13,224 ( 0.01%) let lo = &self.line_cache[lo_cache_idx as usize]; . let hi = &self.line_cache[hi_cache_idx as usize]; . 39,672 ( 0.02%) if lo.file_index != hi.file_index { . return None; . } . . ( 13,224 ( 0.01%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 6,612 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . ) . }; . 6,612 ( 0.00%) self.line_cache[lo_cache_idx as usize].touch(self.time_stamp); 6,612 ( 0.00%) self.line_cache[hi_cache_idx as usize].touch(self.time_stamp); . 26,448 ( 0.01%) return Some(result); . } . . // No cache hit or cache hit for only one of span lo and hi. 698 ( 0.00%) let oldest = if lo_cache_idx != -1 || hi_cache_idx != -1 { . let avoid_idx = if lo_cache_idx != -1 { lo_cache_idx } else { hi_cache_idx }; . self.oldest_cache_entry_index_avoid(avoid_idx as usize) . } else { . self.oldest_cache_entry_index() . }; . . // If the entry doesn't point to the correct file, get the new file and index. . // Return early if the file containing beginning of span doesn't contain end of span. 2,808 ( 0.00%) let new_file_and_idx = if !file_contains(&self.line_cache[oldest].file, span_data.lo) { 185 ( 0.00%) let new_file_and_idx = self.file_for_position(span_data.lo)?; 222 ( 0.00%) if !file_contains(&new_file_and_idx.0, span_data.hi) { . return None; . } . 148 ( 0.00%) Some(new_file_and_idx) . } else { . let file = &self.line_cache[oldest].file; 942 ( 0.00%) if !file_contains(&file, span_data.hi) { . return None; . } . 942 ( 0.00%) None . }; . . // Update the cache entries. 1,755 ( 0.00%) let (lo_idx, hi_idx) = match (lo_cache_idx, hi_cache_idx) { . // Oldest cache entry is for span_data.lo line. . (-1, -1) => { . let lo = &mut self.line_cache[oldest]; . lo.update(new_file_and_idx, span_data.lo, self.time_stamp); . 639 ( 0.00%) if !lo.line.contains(&span_data.hi) { . let new_file_and_idx = Some((lo.file.clone(), lo.file_index)); . let next_oldest = self.oldest_cache_entry_index_avoid(oldest); . let hi = &mut self.line_cache[next_oldest]; . hi.update(new_file_and_idx, span_data.hi, self.time_stamp); . (oldest, next_oldest) . } else { . (oldest, oldest) . } . } . // Oldest cache entry is for span_data.lo line. . (-1, _) => { . let lo = &mut self.line_cache[oldest]; . lo.update(new_file_and_idx, span_data.lo, self.time_stamp); 4 ( 0.00%) let hi = &mut self.line_cache[hi_cache_idx as usize]; 6 ( 0.00%) hi.touch(self.time_stamp); . (oldest, hi_cache_idx as usize) . } . // Oldest cache entry is for span_data.hi line. . (_, -1) => { . let hi = &mut self.line_cache[oldest]; 136 ( 0.00%) hi.update(new_file_and_idx, span_data.hi, self.time_stamp); 272 ( 0.00%) let lo = &mut self.line_cache[lo_cache_idx as usize]; 544 ( 0.00%) lo.touch(self.time_stamp); . (lo_cache_idx as usize, oldest) . } . _ => { . panic!(); . } . }; . . let lo = &self.line_cache[lo_idx]; . let hi = &self.line_cache[hi_idx]; . . // Span lo and hi may equal line end when last line doesn't . // end in newline, hence the inclusive upper bounds below. 702 ( 0.00%) assert!(span_data.lo >= lo.line.start); 351 ( 0.00%) assert!(span_data.lo <= lo.line.end); 702 ( 0.00%) assert!(span_data.hi >= hi.line.start); 351 ( 0.00%) assert!(span_data.hi <= hi.line.end); 1,755 ( 0.00%) assert!(lo.file.contains(span_data.lo)); 1,053 ( 0.00%) assert!(lo.file.contains(span_data.hi)); 1,053 ( 0.00%) assert_eq!(lo.file_index, hi.file_index); . 1,053 ( 0.00%) Some(( 351 ( 0.00%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 351 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . )) 62,667 ( 0.03%) } . . fn cache_entry_index(&self, pos: BytePos) -> isize { . for (idx, cache_entry) in self.line_cache.iter().enumerate() { 80,822 ( 0.04%) if cache_entry.line.contains(&pos) { . return idx as isize; . } . } . . -1 . } . . fn oldest_cache_entry_index(&self) -> usize { . let mut oldest = 0; . . for idx in 1..self.line_cache.len() { 1,278 ( 0.00%) if self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp { . oldest = idx; . } . } . . oldest . } . . fn oldest_cache_entry_index_avoid(&self, avoid_idx: usize) -> usize { . let mut oldest = if avoid_idx != 0 { 0 } else { 1 }; . . for idx in 0..self.line_cache.len() { 884 ( 0.00%) if idx != avoid_idx 338 ( 0.00%) && self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp . { . oldest = idx; . } . } . . oldest . } . 185 ( 0.00%) fn file_for_position(&self, pos: BytePos) -> Option<(Lrc, usize)> { 37 ( 0.00%) if !self.source_map.files().is_empty() { 74 ( 0.00%) let file_idx = self.source_map.lookup_source_file_idx(pos); . let file = &self.source_map.files()[file_idx]; . 296 ( 0.00%) if file_contains(file, pos) { . return Some((file.clone(), file_idx)); . } . } . . None 185 ( 0.00%) } . } . . #[inline] . fn file_contains(file: &SourceFile, pos: BytePos) -> bool { . // `SourceMap::lookup_source_file_idx` and `SourceFile::contains` both consider the position . // one past the end of a file to belong to it. Normally, that's what we want. But for the . // purposes of converting a byte position to a line and column number, we can't come up with a . // line and column number if the file is empty, because an empty file doesn't contain any -- line 290 ---------------------------------------- 74,909 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp/ring.rs -------------------------------------------------------------------------------- Ir -- line 22 ---------------------------------------- . RingBuffer { data: VecDeque::new(), offset: 0 } . } . . pub fn is_empty(&self) -> bool { . self.data.is_empty() . } . . pub fn push(&mut self, value: T) -> usize { 33,648 ( 0.02%) let index = self.offset + self.data.len(); 106,112 ( 0.05%) self.data.push_back(value); . index . } . . pub fn clear(&mut self) { 2 ( 0.00%) self.data.clear(); . } . . pub fn index_of_first(&self) -> usize { . self.offset . } . . pub fn first(&self) -> Option<&T> { . self.data.front() . } . . pub fn first_mut(&mut self) -> Option<&mut T> { . self.data.front_mut() . } . 84,120 ( 0.04%) pub fn pop_first(&mut self) -> Option { . let first = self.data.pop_front()?; 67,296 ( 0.03%) self.offset += 1; 100,944 ( 0.05%) Some(first) 117,768 ( 0.06%) } . . pub fn last(&self) -> Option<&T> { . self.data.back() . } . . pub fn last_mut(&mut self) -> Option<&mut T> { . self.data.back_mut() . } -- line 63 ---------------------------------------- 84,120 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_hir_pretty/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 37 ---------------------------------------- . ImplItem(hir::ImplItemId), . ForeignItem(hir::ForeignItemId), . Body(hir::BodyId), . BodyParamPat(hir::BodyId, usize), . } . . pub trait PpAnn { . fn nested(&self, _state: &mut State<'_>, _nested: Nested) {} 6,472 ( 0.00%) fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {} . fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {} . } . . pub struct NoAnn; . impl PpAnn for NoAnn {} . pub const NO_ANN: &dyn PpAnn = &NoAnn; . . /// Identical to the `PpAnn` implementation for `hir::Crate`, -- line 53 ---------------------------------------- -- line 173 ---------------------------------------- . s: pp::Printer::new(), . comments: Some(Comments::new(sm, filename, input)), . attrs, . ann, . } . } . . fn attrs(&self, id: hir::HirId) -> &'a [ast::Attribute] { 9,708 ( 0.00%) (self.attrs)(id) . } . } . 22 ( 0.00%) pub fn to_string(ann: &dyn PpAnn, f: F) -> String . where . F: FnOnce(&mut State<'_>), . { 9,726 ( 0.00%) let mut printer = State { s: pp::Printer::new(), comments: None, attrs: &|_| &[], ann }; . f(&mut printer); 12 ( 0.00%) printer.s.eof() 16 ( 0.00%) } . . pub fn visibility_qualified>>(vis: &hir::Visibility<'_>, w: S) -> String { . to_string(NO_ANN, |s| { . s.print_visibility(vis); . s.word(w) . }) . } . -- line 200 ---------------------------------------- -- line 249 ---------------------------------------- . self.end(); // close the outer-box . } . } . . pub fn bclose(&mut self, span: rustc_span::Span) { . self.bclose_maybe_open(span, true) . } . 7,128 ( 0.00%) pub fn commasep_cmnt(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G) . where . F: FnMut(&mut State<'_>, &T), . G: FnMut(&T) -> rustc_span::Span, . { 1,944 ( 0.00%) self.rbox(0, b); . let len = elts.len(); . let mut i = 0; . for elt in elts { 9,699 ( 0.00%) self.maybe_print_comment(get_span(elt).hi()); . op(self, elt); . i += 1; 6,466 ( 0.00%) if i < len { . self.word(","); . self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi())); 10,340 ( 0.01%) self.space_if_not_bol(); . } . } 5,832 ( 0.00%) self.end(); . } . . pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) { 41,381 ( 0.02%) self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span) . } . . pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) { . self.print_inner_attributes(attrs); . for &item_id in _mod.item_ids { . self.ann.nested(self, Nested::Item(item_id)); . } . } -- line 287 ---------------------------------------- -- line 1128 ---------------------------------------- . fn cond_needs_par(expr: &hir::Expr<'_>) -> bool { . match expr.kind { . hir::ExprKind::Break(..) | hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) => true, . _ => contains_exterior_struct_lit(expr), . } . } . . fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) { 3 ( 0.00%) self.ibox(INDENT_UNIT); . self.word("["); . self.commasep_exprs(Inconsistent, exprs); . self.word("]"); . self.end() . } . . fn print_expr_anon_const(&mut self, anon_const: &hir::AnonConst) { . self.ibox(INDENT_UNIT); -- line 1144 ---------------------------------------- -- line 1195 ---------------------------------------- . self.word(",") . } . } . } . self.word("}"); . } . . fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) { 1,294 ( 0.00%) self.popen(); . self.commasep_exprs(Inconsistent, exprs); 1,294 ( 0.00%) if exprs.len() == 1 { . self.word(","); . } . self.pclose() . } . . fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) { . let prec = match func.kind { . hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN, -- line 1213 ---------------------------------------- -- line 1269 ---------------------------------------- . . fn print_expr_addr_of( . &mut self, . kind: hir::BorrowKind, . mutability: hir::Mutability, . expr: &hir::Expr<'_>, . ) { . self.word("&"); 1 ( 0.00%) match kind { . hir::BorrowKind::Ref => self.print_mutability(mutability, false), . hir::BorrowKind::Raw => { . self.word_nbsp("raw"); . self.print_mutability(mutability, true); . } . } . self.print_expr_maybe_paren(expr, parser::PREC_PREFIX) . } . . fn print_literal(&mut self, lit: &hir::Lit) { 15,522 ( 0.01%) self.maybe_print_comment(lit.span.lo()); 10,348 ( 0.01%) self.word(lit.node.to_lit_token().to_string()) . } . . fn print_inline_asm(&mut self, asm: &hir::InlineAsm<'_>) { . enum AsmArg<'a> { . Template(String), . Operand(&'a hir::InlineAsmOperand<'a>), . Options(ast::InlineAsmOptions), . } -- line 1297 ---------------------------------------- -- line 1394 ---------------------------------------- . s.word(opt); . }); . s.pclose(); . } . }); . self.pclose(); . } . 29,124 ( 0.01%) pub fn print_expr(&mut self, expr: &hir::Expr<'_>) { 19,416 ( 0.01%) self.maybe_print_comment(expr.span.lo()); 6,472 ( 0.00%) self.print_outer_attributes(self.attrs(expr.hir_id)); 9,708 ( 0.00%) self.ibox(INDENT_UNIT); 19,416 ( 0.01%) self.ann.pre(self, AnnNode::Expr(expr)); 16,180 ( 0.01%) match expr.kind { . hir::ExprKind::Box(ref expr) => { . self.word_space("box"); . self.print_expr_maybe_paren(expr, parser::PREC_PREFIX); . } . hir::ExprKind::Array(ref exprs) => { 2 ( 0.00%) self.print_expr_vec(exprs); . } . hir::ExprKind::ConstBlock(ref anon_const) => { . self.print_expr_anon_const(anon_const); . } . hir::ExprKind::Repeat(ref element, ref count) => { . self.print_expr_repeat(&element, count); . } . hir::ExprKind::Struct(ref qpath, fields, ref wth) => { . self.print_expr_struct(qpath, fields, wth); . } . hir::ExprKind::Tup(ref exprs) => { 1,294 ( 0.00%) self.print_expr_tup(exprs); . } . hir::ExprKind::Call(ref func, ref args) => { . self.print_expr_call(&func, args); . } . hir::ExprKind::MethodCall(ref segment, ref args, _) => { . self.print_expr_method_call(segment, args); . } . hir::ExprKind::Binary(op, ref lhs, ref rhs) => { . self.print_expr_binary(op, &lhs, &rhs); . } . hir::ExprKind::Unary(op, ref expr) => { . self.print_expr_unary(op, &expr); . } 4 ( 0.00%) hir::ExprKind::AddrOf(k, m, ref expr) => { 1 ( 0.00%) self.print_expr_addr_of(k, m, &expr); . } . hir::ExprKind::Lit(ref lit) => { . self.print_literal(&lit); . } . hir::ExprKind::Cast(ref expr, ref ty) => { . let prec = AssocOp::As.precedence() as i8; . self.print_expr_maybe_paren(&expr, prec); . self.space(); -- line 1448 ---------------------------------------- -- line 1586 ---------------------------------------- . self.print_expr_maybe_paren(&expr, parser::PREC_JUMP); . } . hir::ExprKind::Err => { . self.popen(); . self.word("/*ERROR*/"); . self.pclose(); . } . } 19,416 ( 0.01%) self.ann.post(self, AnnNode::Expr(expr)); 6,472 ( 0.00%) self.end() 25,888 ( 0.01%) } . . pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) { . self.print_pat(&loc.pat); . if let Some(ref ty) = loc.ty { . self.word_space(":"); . self.print_type(&ty); . } . } -- line 1604 ---------------------------------------- -- line 2232 ---------------------------------------- . self.word_space("="); . self.print_type(rhs_ty); . } . } . } . } . . pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) { 1 ( 0.00%) match mutbl { . hir::Mutability::Mut => self.word_nbsp("mut"), . hir::Mutability::Not => { . if print_const { . self.word_nbsp("const") . } . } . } . } -- line 2248 ---------------------------------------- 7,129 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/mod.rs -------------------------------------------------------------------------------- Ir -- line 90 ---------------------------------------- . &self.local_decls . } . } . . /// A streamlined trait that you can implement to create a pass; the . /// pass will be named after the type, and it will consist of a main . /// loop that goes over each available MIR and applies `run_pass`. . pub trait MirPass<'tcx> { 2,086 ( 0.00%) fn name(&self) -> Cow<'_, str> { . let name = std::any::type_name::(); 63 ( 0.00%) if let Some(tail) = name.rfind(':') { 263 ( 0.00%) Cow::from(&name[tail + 1..]) . } else { . Cow::from(name) . } 1,372 ( 0.00%) } . . /// Returns `true` if this pass is enabled with the current combination of compiler flags. . fn is_enabled(&self, _sess: &Session) -> bool { . true 480 ( 0.00%) } . . fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>); . . /// If this pass causes the MIR to enter a new phase, return that phase. . fn phase_change(&self) -> Option { . None 668 ( 0.00%) } . . fn is_mir_dump_enabled(&self) -> bool { . true 800 ( 0.00%) } . } . . /// The various "big phases" that MIR goes through. . /// . /// These phases all describe dialects of MIR. Since all MIR uses the same datastructures, the . /// dialects forbid certain variants or values in certain phases. . /// . /// Note: Each phase's validation checks all invariants of the *previous* phases' dialects. A phase . /// that changes the dialect documents what invariants must be upheld *after* that phase finishes. . /// . /// Warning: ordering of variants is significant. 410 ( 0.00%) #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)] . #[derive(HashStable)] . pub enum MirPhase { . Build = 0, . // FIXME(oli-obk): it's unclear whether we still need this phase (and its corresponding query). . // We used to have this for pre-miri MIR based const eval. . Const = 1, . /// This phase checks the MIR for promotable elements and takes them out of the main MIR body . /// by creating a new MIR body per promoted element. After this phase (and thus the termination -- line 141 ---------------------------------------- -- line 157 ---------------------------------------- . impl MirPhase { . /// Gets the index of the current MirPhase within the set of all `MirPhase`s. . pub fn phase_index(&self) -> usize { . *self as usize . } . } . . /// Where a specific `mir::Body` comes from. 70 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, Eq)] 63 ( 0.00%) #[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable)] . pub struct MirSource<'tcx> { . pub instance: InstanceDef<'tcx>, . . /// If `Some`, this is a promoted rvalue within the parent function. . pub promoted: Option, . } . . impl<'tcx> MirSource<'tcx> { 11 ( 0.00%) pub fn item(def_id: DefId) -> Self { 55 ( 0.00%) MirSource { . instance: InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)), . promoted: None, . } 11 ( 0.00%) } . . pub fn from_instance(instance: InstanceDef<'tcx>) -> Self { . MirSource { instance, promoted: None } . } . . pub fn with_opt_param(self) -> ty::WithOptConstParam { 23 ( 0.00%) self.instance.with_opt_param() 23 ( 0.00%) } . . #[inline] . pub fn def_id(&self) -> DefId { 1,180 ( 0.00%) self.instance.def_id() . } . } . . #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)] . pub struct GeneratorInfo<'tcx> { . /// The yield type of the function, if it is a generator. . pub yield_ty: Option>, . -- line 200 ---------------------------------------- -- line 205 ---------------------------------------- . pub generator_layout: Option>, . . /// If this is a generator then record the type of source expression that caused this generator . /// to be created. . pub generator_kind: GeneratorKind, . } . . /// The lowered representation of a single function. 1,296 ( 0.00%) #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)] . pub struct Body<'tcx> { . /// A list of basic blocks. References to basic block use a newtyped index type [`BasicBlock`] . /// that indexes into this vector. . basic_blocks: IndexVec>, . . /// Records how far through the "desugaring and optimization" process this particular . /// MIR has traversed. This is particularly useful when inlining, since in that context . /// we instantiate the promoted constants and add them to our promoted vector -- but those . /// promoted items have already been optimized, whereas ours have not. This field allows . /// us to see the difference and forego optimization on the inlined promoted items. 27 ( 0.00%) pub phase: MirPhase, . . pub source: MirSource<'tcx>, . . /// A list of source scopes; these are referenced by statements . /// and used for debuginfo. Indexed by a `SourceScope`. 28 ( 0.00%) pub source_scopes: IndexVec>, . 28 ( 0.00%) pub generator: Option>>, . . /// Declarations of locals. . /// . /// The first local is the return value pointer, followed by `arg_count` . /// locals for the function arguments, followed by any user-declared . /// variables and temporaries. . pub local_decls: LocalDecls<'tcx>, . -- line 240 ---------------------------------------- -- line 242 ---------------------------------------- . pub user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>, . . /// The number of arguments this function takes. . /// . /// Starting at local 1, `arg_count` locals will be provided by the caller . /// and can be assumed to be initialized. . /// . /// If this MIR was built for a constant, this will be 0. 14 ( 0.00%) pub arg_count: usize, . . /// Mark an argument local (which must be a tuple) as getting passed as . /// its individual components at the LLVM level. . /// . /// This is used for the "rust-call" ABI. 28 ( 0.00%) pub spread_arg: Option, . . /// Debug information pertaining to user variables, including captures. 14 ( 0.00%) pub var_debug_info: Vec>, . . /// A span representing this MIR, for error reporting. . pub span: Span, . . /// Constants that are required to evaluate successfully for this MIR to be well-formed. . /// We hold in this field all the constants we are not able to evaluate yet. . pub required_consts: Vec>, . -- line 267 ---------------------------------------- -- line 275 ---------------------------------------- . /// fn test() { . /// let _ = [0; std::mem::size_of::<*mut T>()]; . /// } . /// ``` . /// . /// **WARNING**: Do not change this flags after the MIR was originally created, even if an optimization . /// removed the last mention of all generic params. We do not want to rely on optimizations and . /// potentially allow things like `[u8; std::mem::size_of::() * 0]` due to this. 14 ( 0.00%) pub is_polymorphic: bool, . . predecessor_cache: PredecessorCache, . is_cyclic: GraphIsCyclicCache, . } . . impl<'tcx> Body<'tcx> { 252 ( 0.00%) pub fn new( . source: MirSource<'tcx>, . basic_blocks: IndexVec>, . source_scopes: IndexVec>, . local_decls: LocalDecls<'tcx>, . user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>, . arg_count: usize, . var_debug_info: Vec>, . span: Span, . generator_kind: Option, . ) -> Self { . // We need `arg_count` locals, and one for the return place. 21 ( 0.00%) assert!( 21 ( 0.00%) local_decls.len() > arg_count, . "expected at least {} locals, got {}", . arg_count + 1, . local_decls.len() . ); . 420 ( 0.00%) let mut body = Body { . phase: MirPhase::Build, . source, . basic_blocks, . source_scopes, . generator: generator_kind.map(|generator_kind| { . Box::new(GeneratorInfo { . yield_ty: None, . generator_drop: None, . generator_layout: None, . generator_kind, . }) . }), 84 ( 0.00%) local_decls, 84 ( 0.00%) user_type_annotations, . arg_count, . spread_arg: None, 84 ( 0.00%) var_debug_info, . span, . required_consts: Vec::new(), . is_polymorphic: false, . predecessor_cache: PredecessorCache::new(), . is_cyclic: GraphIsCyclicCache::new(), . }; 21 ( 0.00%) body.is_polymorphic = body.has_param_types_or_consts(); . body 189 ( 0.00%) } . . /// Returns a partially initialized MIR body containing only a list of basic blocks. . /// . /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It . /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different . /// crate. . pub fn new_cfg_only(basic_blocks: IndexVec>) -> Self { . let mut body = Body { -- line 343 ---------------------------------------- -- line 368 ---------------------------------------- . . #[inline] . pub fn basic_blocks_mut(&mut self) -> &mut IndexVec> { . // Because the user could mutate basic block terminators via this reference, we need to . // invalidate the caches. . // . // FIXME: Use a finer-grained API for this, so only transformations that alter terminators . // invalidate the caches. 90 ( 0.00%) self.predecessor_cache.invalidate(); . self.is_cyclic.invalidate(); . &mut self.basic_blocks . } . . #[inline] . pub fn basic_blocks_and_local_decls_mut( . &mut self, . ) -> (&mut IndexVec>, &mut LocalDecls<'tcx>) { -- line 384 ---------------------------------------- -- line 397 ---------------------------------------- . ) { . self.predecessor_cache.invalidate(); . self.is_cyclic.invalidate(); . (&mut self.basic_blocks, &mut self.local_decls, &mut self.var_debug_info) . } . . /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the . /// `START_BLOCK`. 182 ( 0.00%) pub fn is_cfg_cyclic(&self) -> bool { . self.is_cyclic.is_cyclic(self) 273 ( 0.00%) } . . #[inline] . pub fn local_kind(&self, local: Local) -> LocalKind { . let index = local.as_usize(); 6,507 ( 0.00%) if index == 0 { . debug_assert!( . self.local_decls[local].mutability == Mutability::Mut, . "return place should be mutable" . ); . . LocalKind::ReturnPointer 24,800 ( 0.01%) } else if index < self.arg_count + 1 { . LocalKind::Arg . } else if self.local_decls[local].is_user_variable() { . LocalKind::Var . } else { . LocalKind::Temp . } . } . . /// Returns an iterator over all user-declared mutable locals. . #[inline] . pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator + 'a { 33 ( 0.00%) (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| { . let local = Local::new(index); . let decl = &self.local_decls[local]; 25 ( 0.00%) if decl.is_user_variable() && decl.mutability == Mutability::Mut { . Some(local) . } else { . None . } . }) . } . . /// Returns an iterator over all user-declared mutable arguments and locals. . #[inline] . pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator + 'a { . (1..self.local_decls.len()).filter_map(move |index| { . let local = Local::new(index); . let decl = &self.local_decls[local]; 3,551 ( 0.00%) if (decl.is_user_variable() || index < self.arg_count + 1) . && decl.mutability == Mutability::Mut . { . Some(local) . } else { . None . } . }) . } . . /// Returns an iterator over all function arguments. . #[inline] . pub fn args_iter(&self) -> impl Iterator + ExactSizeIterator { 315 ( 0.00%) (1..self.arg_count + 1).map(Local::new) . } . . /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all . /// locals that are neither arguments nor the return place). . #[inline] . pub fn vars_and_temps_iter( . &self, . ) -> impl DoubleEndedIterator + ExactSizeIterator { -- line 469 ---------------------------------------- -- line 479 ---------------------------------------- . /// invalidating statement indices in `Location`s. . pub fn make_statement_nop(&mut self, location: Location) { . let block = &mut self.basic_blocks[location.block]; . debug_assert!(location.statement_index < block.statements.len()); . block.statements[location.statement_index].make_nop() . } . . /// Returns the source info associated with `location`. 6,712 ( 0.00%) pub fn source_info(&self, location: Location) -> &SourceInfo { . let block = &self[location.block]; . let stmts = &block.statements; 3,356 ( 0.00%) let idx = location.statement_index; 16,780 ( 0.01%) if idx < stmts.len() { 9,861 ( 0.00%) &stmts[idx].source_info . } else { 138 ( 0.00%) assert_eq!(idx, stmts.len()); 138 ( 0.00%) &block.terminator().source_info . } 6,712 ( 0.00%) } . . /// Returns the return type; it always return first element from `local_decls` array. . #[inline] . pub fn return_ty(&self) -> Ty<'tcx> { 65 ( 0.00%) self.local_decls[RETURN_PLACE].ty . } . . /// Gets the location of the terminator for the given block. . #[inline] . pub fn terminator_loc(&self, bb: BasicBlock) -> Location { 555 ( 0.00%) Location { block: bb, statement_index: self[bb].statements.len() } . } . . pub fn stmt_at(&self, location: Location) -> Either<&Statement<'tcx>, &Terminator<'tcx>> { . let Location { block, statement_index } = location; . let block_data = &self.basic_blocks[block]; . block_data . .statements . .get(statement_index) -- line 516 ---------------------------------------- -- line 520 ---------------------------------------- . . #[inline] . pub fn predecessors(&self) -> &Predecessors { . self.predecessor_cache.compute(&self.basic_blocks) . } . . #[inline] . pub fn dominators(&self) -> Dominators { 44 ( 0.00%) dominators(self) . } . . #[inline] . pub fn yield_ty(&self) -> Option> { . self.generator.as_ref().and_then(|generator| generator.yield_ty) . } . . #[inline] -- line 536 ---------------------------------------- -- line 571 ---------------------------------------- . . impl<'tcx> IndexMut for Body<'tcx> { . #[inline] . fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> { . &mut self.basic_blocks_mut()[index] . } . } . 930 ( 0.00%) #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)] . pub enum ClearCrossCrate { . Clear, . Set(T), . } . . impl ClearCrossCrate { . pub fn as_ref(&self) -> ClearCrossCrate<&T> { 13,436 ( 0.01%) match self { . ClearCrossCrate::Clear => ClearCrossCrate::Clear, . ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v), . } . } . . pub fn assert_crate_local(self) -> T { 3,380 ( 0.00%) match self { . ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"), . ClearCrossCrate::Set(v) => v, . } 10 ( 0.00%) } . } . . const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0; . const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1; . . impl<'tcx, E: TyEncoder<'tcx>, T: Encodable> Encodable for ClearCrossCrate { . #[inline] . fn encode(&self, e: &mut E) -> Result<(), E::Error> { -- line 606 ---------------------------------------- -- line 637 ---------------------------------------- . } . } . . /// Grouped information about the source code origin of a MIR entity. . /// Intended to be inspected by diagnostics and debuginfo. . /// Most passes can work with it as a whole, within a single function. . // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and . // `Hash`. Please ping @bjorn3 if removing them. 24,596 ( 0.01%) #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)] . pub struct SourceInfo { . /// The source span for the AST pertaining to this MIR entity. . pub span: Span, . . /// The source scope, keeping track of which bindings can be . /// seen by debuginfo, active lint levels, `unsafe {...}`, etc. . pub scope: SourceScope, . } -- line 653 ---------------------------------------- -- line 657 ---------------------------------------- . pub fn outermost(span: Span) -> Self { . SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE } . } . } . . /////////////////////////////////////////////////////////////////////////// . // Borrow kinds . 260 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)] . #[derive(Hash, HashStable)] . pub enum BorrowKind { . /// Data must be immutable and is aliasable. . Shared, . . /// The immediately borrowed place must be immutable, but projections from . /// it don't need to be. For example, a shallow borrow of `a.b` doesn't . /// conflict with a mutable borrow of `a.b.c`. -- line 673 ---------------------------------------- -- line 731 ---------------------------------------- . /// `true` if this borrow arose from method-call auto-ref . /// (i.e., `adjustment::Adjust::Borrow`). . allow_two_phase_borrow: bool, . }, . } . . impl BorrowKind { . pub fn allows_two_phase_borrow(&self) -> bool { 35 ( 0.00%) match *self { . BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false, . BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow, . } 7 ( 0.00%) } . . pub fn describe_mutability(&self) -> String { . match *self { . BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => { . "immutable".to_string() . } . BorrowKind::Mut { .. } => "mutable".to_string(), . } -- line 751 ---------------------------------------- -- line 777 ---------------------------------------- . /// Compiler-introduced temporary. . Temp, . /// Function argument. . Arg, . /// Location of function's return value. . ReturnPointer, . } . 192 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)] . pub struct VarBindingForm<'tcx> { . /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`? 48 ( 0.00%) pub binding_mode: ty::BindingMode, . /// If an explicit type was provided for this variable binding, . /// this holds the source Span of that type. . /// . /// NOTE: if you want to change this to a `HirId`, be wary that . /// doing so breaks incremental compilation (as of this writing), . /// while a `Span` does not cause our tests to fail. . pub opt_ty_info: Option, . /// Place of the RHS of the =, or the subject of the `match` where this -- line 796 ---------------------------------------- -- line 799 ---------------------------------------- . /// (a) the right-hand side isn't evaluated as a place expression. . /// (b) it gives a way to separate this case from the remaining cases . /// for diagnostics. . pub opt_match_place: Option<(Option>, Span)>, . /// The span of the pattern in which this variable was bound. . pub pat_span: Span, . } . 180 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable)] . pub enum BindingForm<'tcx> { . /// This is a binding for a non-`self` binding, or a `self` that has an explicit type. . Var(VarBindingForm<'tcx>), . /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit. 36 ( 0.00%) ImplicitSelf(ImplicitSelfKind), . /// Reference used in a guard expression to ensure immutability. . RefForGuard, . } . . /// Represents what type of implicit self a function has, if any. . #[derive(Clone, Copy, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)] . pub enum ImplicitSelfKind { . /// Represents a `fn x(self);`. -- line 820 ---------------------------------------- -- line 853 ---------------------------------------- . /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries . /// created during evaluation of expressions in a block tail . /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`. . /// . /// It is used to improve diagnostics when such temporaries are . /// involved in borrow_check errors, e.g., explanations of where the . /// temporaries come from, when their destructors are run, and/or how . /// one might revise the code to satisfy the borrow checker's rules. 407 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)] . pub struct BlockTailInfo { . /// If `true`, then the value resulting from evaluating this tail . /// expression is ignored by the block's expression context. . /// . /// Examples include `{ ...; tail };` and `let _ = { ...; tail };` . /// but not e.g., `let _x = { ...; tail };` . pub tail_result_is_ignored: bool, . -- line 869 ---------------------------------------- -- line 870 ---------------------------------------- . /// `Span` of the tail expression. . pub span: Span, . } . . /// A MIR local. . /// . /// This can be a binding declared by the user, a temporary inserted by the compiler, a function . /// argument, or the return place. 16,659 ( 0.01%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)] . pub struct LocalDecl<'tcx> { . /// Whether this is a mutable binding (i.e., `let x` or `let mut x`). . /// . /// Temporaries and the return place are always mutable. 4,396 ( 0.00%) pub mutability: Mutability, . . // FIXME(matthewjasper) Don't store in this in `Body` . pub local_info: Option>>, . . /// `true` if this is an internal local. . /// . /// These locals are not based on types in the source code and are only used . /// for a few desugarings at the moment. -- line 891 ---------------------------------------- -- line 894 ---------------------------------------- . /// across a suspension point against the type components of the generator . /// which type checking knows are live across a suspension point. We need to . /// flag drop flags to avoid triggering this check as they are introduced . /// after typeck. . /// . /// This should be sound because the drop flags are fully algebraic, and . /// therefore don't affect the auto-trait or outlives properties of the . /// generator. 3,014 ( 0.00%) pub internal: bool, . . /// If this local is a temporary and `is_block_tail` is `Some`, . /// then it is a temporary created for evaluation of some . /// subexpression of some block's tail expression (with no . /// intervening statement context). . // FIXME(matthewjasper) Don't store in this in `Body` . pub is_block_tail: Option, . . /// The type of this local. 3,014 ( 0.00%) pub ty: Ty<'tcx>, . . /// If the user manually ascribed a type to this variable, . /// e.g., via `let x: T`, then we carry that type here. The MIR . /// borrow checker needs this information since it can affect . /// region inference. . // FIXME(matthewjasper) Don't store in this in `Body` . pub user_ty: Option>, . -- line 920 ---------------------------------------- -- line 1005 ---------------------------------------- . static_assert_size!(LocalDecl<'_>, 56); . . /// Extra information about a some locals that's used for diagnostics and for . /// classifying variables into local variables, statics, etc, which is needed e.g. . /// for unsafety checking. . /// . /// Not used for non-StaticRef temporaries, the return place, or anonymous . /// function parameters. 1,432 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)] . pub enum LocalInfo<'tcx> { . /// A user-defined local variable or function parameter . /// . /// The `BindingForm` is solely used for local diagnostics when generating . /// warnings/errors when compiling the current crate, and therefore it need . /// not be visible across crates. . User(ClearCrossCrate>), . /// A temporary created that references the static with the given `DefId`. -- line 1021 ---------------------------------------- -- line 1064 ---------------------------------------- . ))) . ) . } . . /// Returns `true` if this variable is a named variable or function . /// parameter declared by the user. . #[inline] . pub fn is_user_variable(&self) -> bool { 10,832 ( 0.01%) matches!(self.local_info, Some(box LocalInfo::User(_))) . } . . /// Returns `true` if this is a reference to a variable bound in a `match` . /// expression that is used to access said variable for the guard of the . /// match arm. . pub fn is_ref_for_guard(&self) -> bool { . matches!( . self.local_info, . Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard))) . ) . } . . /// Returns `Some` if this is a reference to a static item that is used to . /// access that static. . pub fn is_ref_to_static(&self) -> bool { 893 ( 0.00%) matches!(self.local_info, Some(box LocalInfo::StaticRef { .. })) 259 ( 0.00%) } . . /// Returns `Some` if this is a reference to a thread-local static item that is used to . /// access that static. . pub fn is_ref_to_thread_local(&self) -> bool { 63 ( 0.00%) match self.local_info { . Some(box LocalInfo::StaticRef { is_thread_local, .. }) => is_thread_local, . _ => false, . } 15 ( 0.00%) } . . /// Returns `true` is the local is from a compiler desugaring, e.g., . /// `__next` from a `for` loop. . #[inline] . pub fn from_compiler_desugaring(&self) -> bool { . self.source_info.span.desugaring_kind().is_some() . } . -- line 1106 ---------------------------------------- -- line 1108 ---------------------------------------- . #[inline] . pub fn new(ty: Ty<'tcx>, span: Span) -> Self { . Self::with_source_info(ty, SourceInfo::outermost(span)) . } . . /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`. . #[inline] . pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self { 4,845 ( 0.00%) LocalDecl { . mutability: Mutability::Mut, . local_info: None, . internal: false, . is_block_tail: None, . ty, . user_ty: None, . source_info, . } -- line 1124 ---------------------------------------- -- line 1136 ---------------------------------------- . pub fn immutable(mut self) -> Self { . self.mutability = Mutability::Not; . self . } . . /// Converts `self` into same `LocalDecl` except tagged as internal temporary. . #[inline] . pub fn block_tail(mut self, info: BlockTailInfo) -> Self { 37 ( 0.00%) assert!(self.is_block_tail.is_none()); 111 ( 0.00%) self.is_block_tail = Some(info); 518 ( 0.00%) self . } . } . 408 ( 0.00%) #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)] . pub enum VarDebugInfoContents<'tcx> { . /// NOTE(eddyb) There's an unenforced invariant that this `Place` is . /// based on a `Local`, not a `Static`, and contains no indexing. . Place(Place<'tcx>), . Const(Constant<'tcx>), . } . . impl<'tcx> Debug for VarDebugInfoContents<'tcx> { -- line 1158 ---------------------------------------- -- line 1160 ---------------------------------------- . match self { . VarDebugInfoContents::Const(c) => write!(fmt, "{}", c), . VarDebugInfoContents::Place(p) => write!(fmt, "{:?}", p), . } . } . } . . /// Debug information pertaining to a user variable. 456 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)] . pub struct VarDebugInfo<'tcx> { . pub name: Symbol, . . /// Source info of the user variable, including the scope . /// within which the variable is visible (to debuginfo) . /// (see `LocalDecl`'s `source_info` field for more details). . pub source_info: SourceInfo, . -- line 1176 ---------------------------------------- -- line 1209 ---------------------------------------- . DEBUG_FORMAT = "bb{}", . const START_BLOCK = 0, . } . } . . impl BasicBlock { . pub fn start_location(self) -> Location { . Location { block: self, statement_index: 0 } 972 ( 0.00%) } . } . . /////////////////////////////////////////////////////////////////////////// . // BasicBlockData and Terminator . . /// See [`BasicBlock`] for documentation on what basic blocks are at a high level. 3,679 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)] . pub struct BasicBlockData<'tcx> { . /// List of statements in this block. 51 ( 0.00%) pub statements: Vec>, . . /// Terminator for this block. . /// . /// N.B., this should generally ONLY be `None` during construction. . /// Therefore, you should generally access it via the . /// `terminator()` or `terminator_mut()` methods. The only . /// exception is that certain passes, such as `simplify_cfg`, swap . /// out the terminator temporarily with `None` while they continue -- line 1235 ---------------------------------------- -- line 1239 ---------------------------------------- . /// If true, this block lies on an unwind path. This is used . /// during codegen where distinct kinds of basic blocks may be . /// generated (particularly for MSVC cleanup). Unwind blocks must . /// only branch to other unwind blocks. . pub is_cleanup: bool, . } . . /// Information about an assertion failure. 47 ( 0.00%) #[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq, PartialOrd)] . pub enum AssertKind { . BoundsCheck { len: O, index: O }, . Overflow(BinOp, O, O), . OverflowNeg(O), . DivisionByZero(O), . RemainderByZero(O), . ResumedAfterReturn(GeneratorKind), . ResumedAfterPanic(GeneratorKind), -- line 1255 ---------------------------------------- -- line 1287 ---------------------------------------- . pub type AssertMessage<'tcx> = AssertKind>; . . pub type Successors<'a> = . iter::Chain, slice::Iter<'a, BasicBlock>>; . pub type SuccessorsMut<'a> = . iter::Chain, slice::IterMut<'a, BasicBlock>>; . . impl<'tcx> BasicBlockData<'tcx> { 73 ( 0.00%) pub fn new(terminator: Option>) -> BasicBlockData<'tcx> { 1,168 ( 0.00%) BasicBlockData { statements: vec![], terminator, is_cleanup: false } 73 ( 0.00%) } . . /// Accessor for terminator. . /// . /// Terminator may not be None after construction of the basic block is complete. This accessor . /// provides a convenience way to reach the terminator. . #[inline] . pub fn terminator(&self) -> &Terminator<'tcx> { 1,294 ( 0.00%) self.terminator.as_ref().expect("invalid terminator state") . } . . #[inline] . pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> { 723 ( 0.00%) self.terminator.as_mut().expect("invalid terminator state") . } . . pub fn retain_statements(&mut self, mut f: F) . where . F: FnMut(&mut Statement<'_>) -> bool, . { . for s in &mut self.statements { . if !f(s) { . s.make_nop(); . } . } . } . 520 ( 0.00%) pub fn expand_statements(&mut self, mut f: F) . where . F: FnMut(&mut Statement<'tcx>) -> Option, . I: iter::TrustedLen>, . { . // Gather all the iterators we'll need to splice in, and their positions. . let mut splices: Vec<(usize, I)> = vec![]; . let mut extra_stmts = 0; . for (i, s) in self.statements.iter_mut().enumerate() { 18,424 ( 0.01%) if let Some(mut new_stmts) = f(s) { 14 ( 0.00%) if let Some(first) = new_stmts.next() { . // We can already store the first new statement. 3,936 ( 0.00%) *s = first; . . // Save the other statements for optimized splicing. . let remaining = new_stmts.size_hint().0; 1,312 ( 0.00%) if remaining > 0 { 4,550 ( 0.00%) splices.push((i + 1 + extra_stmts, new_stmts)); 1,300 ( 0.00%) extra_stmts += remaining; . } . } else { 4 ( 0.00%) s.make_nop(); . } 24 ( 0.00%) } . } . . // Splice in the new statements, from the end of the block. . // FIXME(eddyb) This could be more efficient with a "gap buffer" . // where a range of elements ("gap") is left uninitialized, with . // splicing adding new elements to the end of that gap and moving . // existing elements from before the gap to the end of the gap. . // For now, this is safe code, emulating a gap but initializing it. 155 ( 0.00%) let mut gap = self.statements.len()..self.statements.len() + extra_stmts; 156 ( 0.00%) self.statements.resize( . gap.end, 208 ( 0.00%) Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop }, . ); 18,200 ( 0.01%) for (splice_start, new_stmts) in splices.into_iter().rev() { 1,300 ( 0.00%) let splice_end = splice_start + new_stmts.size_hint().0; 4,555 ( 0.00%) while gap.end > splice_end { 3,900 ( 0.00%) gap.start -= 1; . gap.end -= 1; . self.statements.swap(gap.start, gap.end); . } 2,600 ( 0.00%) self.statements.splice(splice_start..splice_end, new_stmts); . gap.end = splice_start; . } 416 ( 0.00%) } . . pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> { . if index < self.statements.len() { &self.statements[index] } else { &self.terminator } . } . } . . impl AssertKind { . /// Getting a description does not require `O` to be printable, and does not -- line 1379 ---------------------------------------- -- line 1501 ---------------------------------------- . _ => write!(f, "{}", self.description()), . } . } . } . . /////////////////////////////////////////////////////////////////////////// . // Statements . 68,572 ( 0.03%) #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)] . pub struct Statement<'tcx> { . pub source_info: SourceInfo, . pub kind: StatementKind<'tcx>, . } . . // `Statement` 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!(Statement<'_>, 32); . . impl Statement<'_> { . /// Changes a statement to a nop. This is both faster than deleting instructions and avoids . /// invalidating statement indices in `Location`s. 26 ( 0.00%) pub fn make_nop(&mut self) { 26 ( 0.00%) self.kind = StatementKind::Nop 26 ( 0.00%) } . . /// Changes a statement to a nop and returns the original statement. . #[must_use = "If you don't need the statement, use `make_nop` instead"] 658 ( 0.00%) pub fn replace_nop(&mut self) -> Self { 658 ( 0.00%) Statement { 2,632 ( 0.00%) source_info: self.source_info, . kind: mem::replace(&mut self.kind, StatementKind::Nop), . } 658 ( 0.00%) } . } . 82,304 ( 0.04%) #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)] . pub enum StatementKind<'tcx> { . /// Write the RHS Rvalue to the LHS Place. 778 ( 0.00%) Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>), . . /// This represents all the reading that a pattern match may do . /// (e.g., inspecting constants and discriminant values), and the . /// kind of pattern it comes from. This is in order to adapt potential . /// error messages to these specific patterns. . /// . /// Note that this also is emitted for regular `let` bindings to ensure that locals that are . /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;` 8 ( 0.00%) FakeRead(Box<(FakeReadCause, Place<'tcx>)>), . . /// Write the discriminant for a variant to the enum Place. 32 ( 0.00%) SetDiscriminant { place: Box>, variant_index: VariantIdx }, . . /// Start a live range for the storage of the local. 336 ( 0.00%) StorageLive(Local), . . /// End the current live range for the storage of the local. 390 ( 0.00%) StorageDead(Local), . . /// Retag references in the given place, ensuring they got fresh tags. This is . /// part of the Stacked Borrows model. These statements are currently only interpreted . /// by miri and only generated when "-Z mir-emit-retag" is passed. . /// See . /// for more details. . Retag(RetagKind, Box>), . -- line 1565 ---------------------------------------- -- line 1732 ---------------------------------------- . pub count: Operand<'tcx>, . } . . /////////////////////////////////////////////////////////////////////////// . // Places . . /// A path to a value; something that can be evaluated without . /// changing or disturbing program state. 3,790 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, HashStable)] . pub struct Place<'tcx> { 65 ( 0.00%) pub local: Local, . . /// projection out of a place (access a field, deref a pointer, etc) . pub projection: &'tcx List>, . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . static_assert_size!(Place<'_>, 16); . 42,477 ( 0.02%) #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 75,856 ( 0.04%) #[derive(TyEncodable, TyDecodable, HashStable)] . pub enum ProjectionElem { . Deref, 20,751 ( 0.01%) Field(Field, T), 15 ( 0.00%) Index(V), . . /// These indices are generated by slice patterns. Easiest to explain . /// by example: . /// . /// ``` . /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false }, . /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false }, . /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true }, -- line 1764 ---------------------------------------- -- line 1788 ---------------------------------------- . from_end: bool, . }, . . /// "Downcast" to a variant of an ADT. Currently, we only introduce . /// this for ADTs with more than one variant. It may be better to . /// just introduce it always, or always for enums. . /// . /// The included Symbol is the name of the variant, used for printing MIR. 57 ( 0.00%) Downcast(Option, VariantIdx), . } . . impl ProjectionElem { . /// Returns `true` if the target of this projection may refer to a different region of memory . /// than the base. . fn is_indirect(&self) -> bool { 7 ( 0.00%) match self { . Self::Deref => true, . . Self::Field(_, _) . | Self::Index(_) . | Self::ConstantIndex { .. } . | Self::Subslice { .. } . | Self::Downcast(_, _) => false, . } -- line 1811 ---------------------------------------- -- line 1838 ---------------------------------------- . pub struct Field { . derive [HashStable] . DEBUG_FORMAT = "field[{}]" . } . } . . #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] . pub struct PlaceRef<'tcx> { 72 ( 0.00%) pub local: Local, 18 ( 0.00%) pub projection: &'tcx [PlaceElem<'tcx>], . } . . impl<'tcx> Place<'tcx> { . // FIXME change this to a const fn by also making List::empty a const fn. . pub fn return_place() -> Place<'tcx> { . Place { local: RETURN_PLACE, projection: List::empty() } 60 ( 0.00%) } . . /// Returns `true` if this `Place` contains a `Deref` projection. . /// . /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the . /// same region of memory as its base. . pub fn is_indirect(&self) -> bool { 62 ( 0.00%) self.projection.iter().any(|elem| elem.is_indirect()) 62 ( 0.00%) } . . /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or . /// a single deref of a local. . #[inline(always)] . pub fn local_or_deref_local(&self) -> Option { . self.as_ref().local_or_deref_local() . } . -- line 1870 ---------------------------------------- -- line 1872 ---------------------------------------- . /// projections, return `Some(_X)`. . #[inline(always)] . pub fn as_local(&self) -> Option { . self.as_ref().as_local() . } . . #[inline] . pub fn as_ref(&self) -> PlaceRef<'tcx> { 20,938 ( 0.01%) PlaceRef { local: self.local, projection: &self.projection } . } . . /// Iterate over the projections in evaluation order, i.e., the first element is the base with . /// its projection and then subsequently more projections are added. . /// As a concrete example, given the place a.b.c, this would yield: . /// - (a, .b) . /// - (a.b, .c) . /// -- line 1888 ---------------------------------------- -- line 1896 ---------------------------------------- . (base, proj) . }) . } . } . . impl From for Place<'_> { . fn from(local: Local) -> Self { . Place { local, projection: List::empty() } 15,813 ( 0.01%) } . } . . impl<'tcx> PlaceRef<'tcx> { . /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or . /// a single deref of a local. . pub fn local_or_deref_local(&self) -> Option { . match *self { . PlaceRef { local, projection: [] } -- line 1912 ---------------------------------------- -- line 1915 ---------------------------------------- . } . } . . /// If this place represents a local variable like `_X` with no . /// projections, return `Some(_X)`. . #[inline] . pub fn as_local(&self) -> Option { . match *self { 6,125 ( 0.00%) PlaceRef { local, projection: [] } => Some(local), . _ => None, . } . } . . #[inline] . pub fn last_projection(&self) -> Option<(PlaceRef<'tcx>, PlaceElem<'tcx>)> { 11,331 ( 0.01%) if let &[ref proj_base @ .., elem] = self.projection { . Some((PlaceRef { local: self.local, projection: proj_base }, elem)) . } else { . None . } . } . } . . impl Debug for Place<'_> { -- line 1938 ---------------------------------------- -- line 2024 ---------------------------------------- . trace!(?data); . match &data.local_data { . ClearCrossCrate::Set(data) => Some(data.lint_root), . ClearCrossCrate::Clear => None, . } . } . } . 504 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)] . pub struct SourceScopeData<'tcx> { 1 ( 0.00%) pub span: Span, . pub parent_scope: Option, . . /// Whether this scope is the root of a scope tree of another body, . /// inlined into this body by the MIR inliner. . /// `ty::Instance` is the callee, and the `Span` is the call site. . pub inlined: Option<(ty::Instance<'tcx>, Span)>, . . /// Nearest (transitive) parent scope (if any) which is inlined. . /// This is an optimization over walking up `parent_scope` . /// until a scope with `inlined: Some(...)` is found. 3 ( 0.00%) pub inlined_parent_scope: Option, . . /// Crate-local information for this source scope, that can't (and . /// needn't) be tracked across crates. . pub local_data: ClearCrossCrate, . } . 161 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)] . pub struct SourceScopeLocalData { . /// An `HirId` with lint levels equivalent to this scope's lint levels. . pub lint_root: hir::HirId, . /// The unsafe block that contains this node. . pub safety: Safety, . } . . /////////////////////////////////////////////////////////////////////////// . // Operands . . /// These are values that can appear inside an rvalue. They are intentionally . /// limited to prevent rvalues from being nested in one another. 79,381 ( 0.04%) #[derive(Clone, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)] . pub enum Operand<'tcx> { . /// Copy: The value must be available for use afterwards. . /// . /// This implies that the type of the place must be `Copy`; this is true . /// by construction during build, but also checked by the MIR type checker. 368 ( 0.00%) Copy(Place<'tcx>), . . /// Move: The value (including old borrows of it) will not be used again. . /// . /// Safe for values of all types (modulo future developments towards `?Move`). . /// Correct usage patterns are enforced by the borrow checker for safe code. . /// `Copy` may be converted to `Move` to enable "last-use" optimizations. 2,944 ( 0.00%) Move(Place<'tcx>), . . /// Synthesizes a constant value. 2,658 ( 0.00%) Constant(Box>), . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . static_assert_size!(Operand<'_>, 24); . . impl<'tcx> Debug for Operand<'tcx> { . fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { . use self::Operand::*; -- line 2089 ---------------------------------------- -- line 2109 ---------------------------------------- . Operand::Constant(Box::new(Constant { . span, . user_ty: None, . literal: ConstantKind::Ty(ty::Const::zero_sized(tcx, ty)), . })) . } . . pub fn is_move(&self) -> bool { 18 ( 0.00%) matches!(self, Operand::Move(..)) 9 ( 0.00%) } . . /// Convenience helper to make a literal-like constant from a given scalar value. . /// Since this is used to synthesize MIR, assumes `user_ty` is None. . pub fn const_from_scalar( . tcx: TyCtxt<'tcx>, . ty: Ty<'tcx>, . val: Scalar, . span: Span, -- line 2126 ---------------------------------------- -- line 2149 ---------------------------------------- . Operand::Copy(_) | Operand::Constant(_) => self.clone(), . Operand::Move(place) => Operand::Copy(place), . } . } . . /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a . /// constant. . pub fn place(&self) -> Option> { 188 ( 0.00%) match self { . Operand::Copy(place) | Operand::Move(place) => Some(*place), . Operand::Constant(_) => None, . } 47 ( 0.00%) } . . /// Returns the `Constant` that is the target of this `Operand`, or `None` if this `Operand` is a . /// place. . pub fn constant(&self) -> Option<&Constant<'tcx>> { . match self { . Operand::Constant(x) => Some(&**x), . Operand::Copy(_) | Operand::Move(_) => None, . } . } . } . . /////////////////////////////////////////////////////////////////////////// . /// Rvalues . 52,697 ( 0.03%) #[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)] . pub enum Rvalue<'tcx> { . /// x (either a move or copy, depending on type of x) . Use(Operand<'tcx>), . . /// [x; 32] . Repeat(Operand<'tcx>, &'tcx ty::Const<'tcx>), . . /// &x or &mut x 101 ( 0.00%) Ref(Region<'tcx>, BorrowKind, Place<'tcx>), . . /// Accessing a thread local static. This is inherently a runtime operation, even if llvm . /// treats it as an access to a static. This `Rvalue` yields a reference to the thread local . /// static. . ThreadLocalRef(DefId), . . /// Create a raw pointer to the given place . /// Can be generated by raw address of expressions (`&raw const x`), . /// or when casting a reference to a raw pointer. . AddressOf(Mutability, Place<'tcx>), . . /// length of a `[X]` or `[X;n]` value 5 ( 0.00%) Len(Place<'tcx>), . 18 ( 0.00%) Cast(CastKind, Operand<'tcx>, Ty<'tcx>), . 42 ( 0.00%) BinaryOp(BinOp, Box<(Operand<'tcx>, Operand<'tcx>)>), . CheckedBinaryOp(BinOp, Box<(Operand<'tcx>, Operand<'tcx>)>), . . NullaryOp(NullOp, Ty<'tcx>), . UnaryOp(UnOp, Operand<'tcx>), . . /// Read the discriminant of an ADT. . /// . /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot . /// be defined to return, say, a 0) if ADT is not an enum. 5 ( 0.00%) Discriminant(Place<'tcx>), . . /// Creates an aggregate value, like a tuple or struct. This is . /// only needed because we want to distinguish `dest = Foo { x: . /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case . /// that `Foo` has a destructor. These rvalues can be optimized . /// away after type-checking and before lowering. 2,636 ( 0.00%) Aggregate(Box>, Vec>), . . /// Transmutes a `*mut u8` into shallow-initialized `Box`. . /// . /// This is different a normal transmute because dataflow analysis will treat the box . /// as initialized but its content as uninitialized. . ShallowInitBox(Operand<'tcx>, Ty<'tcx>), . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . static_assert_size!(Rvalue<'_>, 40); . 32 ( 0.00%) #[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)] . pub enum CastKind { . Misc, . Pointer(PointerCast), . } . 4,726 ( 0.00%) #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)] . pub enum AggregateKind<'tcx> { . /// The type is of the element 3 ( 0.00%) Array(Ty<'tcx>), . Tuple, . . /// The second field is the variant index. It's equal to 0 for struct . /// and union expressions. The fourth field is . /// active field number and is present only for union expressions . /// -- e.g., for a union expression `SomeUnion { c: .. }`, the . /// active field index would identity the field `c` 32 ( 0.00%) Adt(DefId, VariantIdx, SubstsRef<'tcx>, Option, Option), . 12 ( 0.00%) Closure(DefId, SubstsRef<'tcx>), . Generator(DefId, SubstsRef<'tcx>, hir::Movability), . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . static_assert_size!(AggregateKind<'_>, 48); . 49 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, TyEncodable, TyDecodable, Hash, HashStable)] . pub enum BinOp { . /// The `+` operator (addition) . Add, . /// The `-` operator (subtraction) . Sub, . /// The `*` operator (multiplication) . Mul, . /// The `/` operator (division) -- line 2265 ---------------------------------------- -- line 2485 ---------------------------------------- . . /////////////////////////////////////////////////////////////////////////// . /// Constants . /// . /// Two constants are equal if they are the same constant. Note that . /// this does not necessarily mean that they are `==` in Rust. In . /// particular, one must be wary of `NaN`! . 10,565 ( 0.01%) #[derive(Clone, Copy, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)] . pub struct Constant<'tcx> { . pub span: Span, . . /// Optional user-given type: for something like . /// `collect::>`, this would be present and would . /// indicate that `Vec<_>` was explicitly specified. . /// . /// Needed for NLL to impose user-given type constraints. . pub user_ty: Option, . . pub literal: ConstantKind<'tcx>, . } . 31,475 ( 0.02%) #[derive(Clone, Copy, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable, Debug)] . #[derive(Lift)] . pub enum ConstantKind<'tcx> { . /// This constant came from the type system 14 ( 0.00%) Ty(&'tcx ty::Const<'tcx>), . /// This constant cannot go back into the type system, as it represents . /// something the type system cannot handle (e.g. pointers). . Val(interpret::ConstValue<'tcx>, Ty<'tcx>), . } . . impl<'tcx> Constant<'tcx> { 51,865 ( 0.03%) pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option { 51,865 ( 0.03%) match self.literal.const_for_ty()?.val.try_to_scalar() { . Some(Scalar::Ptr(ptr, _size)) => match tcx.global_alloc(ptr.provenance) { . GlobalAlloc::Static(def_id) => { . assert!(!tcx.is_thread_local_static(def_id)); . Some(def_id) . } . _ => None, . }, . _ => None, . } 82,984 ( 0.04%) } . #[inline] . pub fn ty(&self) -> Ty<'tcx> { . self.literal.ty() . } . } . . impl<'tcx> From<&'tcx ty::Const<'tcx>> for ConstantKind<'tcx> { . #[inline] -- line 2537 ---------------------------------------- -- line 2538 ---------------------------------------- . fn from(ct: &'tcx ty::Const<'tcx>) -> Self { . Self::Ty(ct) . } . } . . impl<'tcx> ConstantKind<'tcx> { . /// Returns `None` if the constant is not trivially safe for use in the type system. . pub fn const_for_ty(&self) -> Option<&'tcx ty::Const<'tcx>> { 46,656 ( 0.02%) match self { . ConstantKind::Ty(c) => Some(c), . ConstantKind::Val(..) => None, . } 12,955 ( 0.01%) } . . pub fn ty(&self) -> Ty<'tcx> { 46,954 ( 0.02%) match self { . ConstantKind::Ty(c) => c.ty, . ConstantKind::Val(_, ty) => ty, . } 23,477 ( 0.01%) } . . #[inline] . pub fn try_to_value(self) -> Option> { . match self { . ConstantKind::Ty(c) => c.val.try_to_value(), . ConstantKind::Val(val, _) => Some(val), . } . } -- line 2565 ---------------------------------------- -- line 2646 ---------------------------------------- . /// following two projected types: . /// . /// * base: `S`, projection: `(base.0).1` . /// * base: `(i32, &'static str)`, projection: `base.1` . /// . /// The first will lead to the constraint `w: &'1 str` (for some . /// inferred region `'1`). The second will lead to the constraint `w: . /// &'static str`. 76 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)] . pub struct UserTypeProjections { 57 ( 0.00%) pub contents: Vec<(UserTypeProjection, Span)>, . } . . impl<'tcx> UserTypeProjections { 9 ( 0.00%) pub fn none() -> Self { 9 ( 0.00%) UserTypeProjections { contents: vec![] } 9 ( 0.00%) } . . pub fn is_empty(&self) -> bool { . self.contents.is_empty() 9 ( 0.00%) } . . pub fn projections_and_spans( . &self, . ) -> impl Iterator + ExactSizeIterator { . self.contents.iter() . } . . pub fn projections(&self) -> impl Iterator + ExactSizeIterator { -- line 2674 ---------------------------------------- -- line 2680 ---------------------------------------- . self . } . . fn map_projections( . mut self, . mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection, . ) -> Self { . self.contents = self.contents.into_iter().map(|(proj, span)| (f(proj), span)).collect(); 44 ( 0.00%) self . } . . pub fn index(self) -> Self { . self.map_projections(|pat_ty_proj| pat_ty_proj.index()) . } . . pub fn subslice(self, from: u64, to: u64) -> Self { . self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to)) . } . 3 ( 0.00%) pub fn deref(self) -> Self { 4 ( 0.00%) self.map_projections(|pat_ty_proj| pat_ty_proj.deref()) 4 ( 0.00%) } . 32 ( 0.00%) pub fn leaf(self, field: Field) -> Self { 48 ( 0.00%) self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field)) 32 ( 0.00%) } . 10 ( 0.00%) pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self { 18 ( 0.00%) self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field)) 8 ( 0.00%) } . } . . /// Encodes the effect of a user-supplied type annotation on the . /// subcomponents of a pattern. The effect is determined by applying the . /// given list of proejctions to some underlying base type. Often, . /// the projection element list `projs` is empty, in which case this . /// directly encodes a type in `base`. But in the case of complex patterns with . /// subpatterns and bindings, we want to apply only a *part* of the type to a variable, -- line 2717 ---------------------------------------- -- line 2870 ---------------------------------------- . fn start_node(&self) -> Self::Node { . START_BLOCK . } . } . . impl<'tcx> graph::WithSuccessors for Body<'tcx> { . #[inline] . fn successors(&self, node: Self::Node) -> >::Iter { 151 ( 0.00%) self.basic_blocks[node].terminator().successors().cloned() . } . } . . impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> { . type Item = BasicBlock; . type Iter = iter::Cloned>; . } . -- line 2886 ---------------------------------------- -- line 2897 ---------------------------------------- . } . . /// `Location` represents the position of the start of the statement; or, if . /// `statement_index` equals the number of statements, then the start of the . /// terminator. . #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)] . pub struct Location { . /// The block that the location is within. 586 ( 0.00%) pub block: BasicBlock, . 288 ( 0.00%) pub statement_index: usize, . } . . impl fmt::Debug for Location { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(fmt, "{:?}[{}]", self.block, self.statement_index) . } . } . -- line 2915 ---------------------------------------- 156,726 ( 0.08%) -------------------------------------------------------------------------------- -- 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. 86,931 ( 0.04%) #[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")] 18 ( 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 { 154,756 ( 0.08%) 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> { 149,378 ( 0.08%) 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,256 ( 0.04%) 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 { 79,027 ( 0.04%) match self { 7,996 ( 0.00%) 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 { 247,785 ( 0.13%) match self { 263,340 ( 0.13%) 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, . { 124,742 ( 0.06%) match self { . Some(x) => x, 4 ( 0.00%) None => default, . } 167 ( 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")] 4 ( 0.00%) pub const fn unwrap_or_else(self, f: F) -> T . where . F: ~const FnOnce() -> T, . F: ~const Drop, . { 141,448 ( 0.07%) match self { 4,706 ( 0.00%) Some(x) => x, 5,260 ( 0.00%) None => f(), . } 14 ( 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, . { 172 ( 0.00%) match self { 322 ( 0.00%) Some(x) => x, . None => Default::default(), . } . } . . /// Returns the contained [`Some`] value, consuming the `self` value, . /// without checking that the value is not [`None`]. . /// . /// # Safety -- line 848 ---------------------------------------- -- 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")] 56 ( 0.00%) pub const fn map(self, f: F) -> Option . where . F: ~const FnOnce(T) -> U, . F: ~const Drop, . { 111,054 ( 0.06%) match self { 180,210 ( 0.09%) Some(x) => Some(f(x)), 1,013 ( 0.00%) None => None, . } 1,586 ( 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, . { 29,445 ( 0.01%) match self { 624 ( 0.00%) Some(t) => f(t), 9 ( 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, . { 419 ( 0.00%) match self { 168 ( 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, . { 21,060 ( 0.01%) match self { 32 ( 0.00%) Some(v) => Ok(v), 16 ( 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 1054 ---------------------------------------- . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn ok_or_else(self, err: F) -> Result . where . F: ~const FnOnce() -> E, . F: ~const Drop, . { 3,618 ( 0.00%) match self { 4,802 ( 0.00%) Some(v) => Ok(v), 1,630 ( 0.00%) None => Err(err()), . } . } . . /// 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`]. . /// -- line 1072 ---------------------------------------- -- 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 ( 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")] 29 ( 0.00%) pub const fn and_then(self, f: F) -> Option . where . F: ~const FnOnce(T) -> Option, . F: ~const Drop, . { 19,309 ( 0.01%) match self { 272 ( 0.00%) Some(x) => f(x), . None => None, . } 207 ( 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, . { 88 ( 0.00%) if let Some(x) = self { 9 ( 0.00%) if predicate(&x) { . return Some(x); . } . } . None . } . . /// Returns the option if it contains a value, otherwise returns `optb`. . /// -- line 1274 ---------------------------------------- -- 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, . { 119 ( 0.00%) match self { . Some(x) => Some(x), . None => optb, . } . } . . /// Returns the option if it contains a value, otherwise calls `f` and . /// returns the result. . /// -- line 1315 ---------------------------------------- -- 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, . { 27,488 ( 0.01%) match self { 156 ( 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, . { 309 ( 0.00%) if let None = *self { 721 ( 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, . { 14,370 ( 0.01%) 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. . 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 1515 ---------------------------------------- -- 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 { 48 ( 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 629 ( 0.00%) match self { 37,352 ( 0.02%) Some(&v) => Some(v), 32 ( 0.00%) None => None, . } 3 ( 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")] 444 ( 0.00%) pub const fn cloned(self) -> Option . where . T: ~const Clone, . { 6,861 ( 0.00%) match self { 57,303 ( 0.03%) Some(t) => Some(t.clone()), 219 ( 0.00%) None => None, . } 719 ( 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 { 82,628 ( 0.04%) match self { 878 ( 0.00%) Some(x) => Some(x.clone()), 13 ( 0.00%) None => None, . } 13,521 ( 0.01%) } . . #[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) { 10,087 ( 0.01%) 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) { 3 ( 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) 60 ( 0.00%) } . . #[inline] . fn branch(self) -> ControlFlow { 67,469 ( 0.03%) match self { 6,710 ( 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 { 7,944 ( 0.00%) None => None, . } . } . } . . #[unstable(feature = "try_trait_v2_residual", issue = "91285")] . impl ops::Residual for Option { . type TryType = Option; . } -- line 2274 ---------------------------------------- 317,716 ( 0.16%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs -------------------------------------------------------------------------------- Ir -- line 86 ---------------------------------------- . impl Qualif for HasMutInterior { . const ANALYSIS_NAME: &'static str = "flow_has_mut_interior"; . . fn in_qualifs(qualifs: &ConstQualifs) -> bool { . qualifs.has_mut_interior . } . . fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { 46,530 ( 0.02%) !ty.is_freeze(cx.tcx.at(DUMMY_SP), cx.param_env) . } . . fn in_adt_inherently<'tcx>( . cx: &ConstCx<'_, 'tcx>, . adt: &'tcx AdtDef, . _: SubstsRef<'tcx>, . ) -> bool { . // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently. -- line 102 ---------------------------------------- -- line 115 ---------------------------------------- . impl Qualif for NeedsDrop { . const ANALYSIS_NAME: &'static str = "flow_needs_drop"; . const IS_CLEARED_ON_MOVE: bool = true; . . fn in_qualifs(qualifs: &ConstQualifs) -> bool { . qualifs.needs_drop . } . 20,688 ( 0.01%) fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { 5,172 ( 0.00%) ty.needs_drop(cx.tcx, cx.param_env) 23,274 ( 0.01%) } . . fn in_adt_inherently<'tcx>( . cx: &ConstCx<'_, 'tcx>, . adt: &'tcx AdtDef, . _: SubstsRef<'tcx>, . ) -> bool { . adt.has_dtor(cx.tcx) . } -- line 133 ---------------------------------------- -- line 141 ---------------------------------------- . const ANALYSIS_NAME: &'static str = "flow_needs_nonconst_drop"; . const IS_CLEARED_ON_MOVE: bool = true; . const ALLOW_PROMOTED: bool = true; . . fn in_qualifs(qualifs: &ConstQualifs) -> bool { . qualifs.needs_non_const_drop . } . 18 ( 0.00%) fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { . // Avoid selecting for simple cases, such as builtin types. 8 ( 0.00%) if ty::util::is_trivially_const_drop(ty) { . return false; . } . . let Some(drop_trait) = cx.tcx.lang_items().drop_trait() else { . // there is no way to define a type that needs non-const drop . // without having the lang item present. . return false; . }; -- line 159 ---------------------------------------- -- line 196 ---------------------------------------- . let mut fcx = FulfillmentContext::new(); . for nested in impl_src.nested_obligations() { . fcx.register_predicate_obligation(&infcx, nested); . } . . // If we had any errors, then it's bad . !fcx.select_all_or_error(&infcx).is_empty() . }) 18 ( 0.00%) } . . fn in_adt_inherently<'tcx>( . cx: &ConstCx<'_, 'tcx>, . adt: &'tcx AdtDef, . _: SubstsRef<'tcx>, . ) -> bool { . adt.has_non_const_dtor(cx.tcx) . } -- line 212 ---------------------------------------- -- line 223 ---------------------------------------- . } . . fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { . // If *any* component of a composite data type does not implement `Structural{Partial,}Eq`, . // we know that at least some values of that type are not structural-match. I say "some" . // because that component may be part of an enum variant (e.g., . // `Option::::Some`), in which case some values of this type may be . // structural-match (`Option::None`). 6 ( 0.00%) traits::search_for_structural_match_violation(cx.body.span, cx.tcx, ty).is_some() . } . . fn in_adt_inherently<'tcx>( . cx: &ConstCx<'_, 'tcx>, . adt: &'tcx AdtDef, . substs: SubstsRef<'tcx>, . ) -> bool { . let ty = cx.tcx.mk_ty(ty::Adt(adt, substs)); . !ty.is_structural_eq_shallow(cx.tcx) . } . } . . // FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return. . . /// Returns `true` if this `Rvalue` contains qualif `Q`. 25,890 ( 0.01%) pub fn in_rvalue<'tcx, Q, F>( . cx: &ConstCx<'_, 'tcx>, . in_local: &mut F, . rvalue: &Rvalue<'tcx>, . ) -> bool . where . Q: Qualif, . F: FnMut(Local) -> bool, . { 12,945 ( 0.01%) match rvalue { . Rvalue::ThreadLocalRef(_) | Rvalue::NullaryOp(..) => { . Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)) . } . . Rvalue::Discriminant(place) | Rvalue::Len(place) => { . in_place::(cx, in_local, place.as_ref()) . } . -- line 264 ---------------------------------------- -- line 267 ---------------------------------------- . | Rvalue::UnaryOp(_, operand) . | Rvalue::Cast(_, operand, _) . | Rvalue::ShallowInitBox(operand, _) => in_operand::(cx, in_local, operand), . . Rvalue::BinaryOp(_, box (lhs, rhs)) | Rvalue::CheckedBinaryOp(_, box (lhs, rhs)) => { . in_operand::(cx, in_local, lhs) || in_operand::(cx, in_local, rhs) . } . 2 ( 0.00%) Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => { . // Special-case reborrows to be more like a copy of the reference. . if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() { . let base_ty = place_base.ty(cx.body, cx.tcx).ty; . if let ty::Ref(..) = base_ty.kind() { . return in_place::(cx, in_local, place_base); . } . } . 6 ( 0.00%) in_place::(cx, in_local, place.as_ref()) . } . . Rvalue::Aggregate(kind, operands) => { . // Return early if we know that the struct or enum being constructed is always . // qualified. 7,764 ( 0.00%) if let AggregateKind::Adt(adt_did, _, substs, ..) = **kind { . let def = cx.tcx.adt_def(adt_did); . if Q::in_adt_inherently(cx, def, substs) { . return true; . } . if def.is_union() && Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)) { . return true; . } . } . . // Otherwise, proceed structurally... 58,140 ( 0.03%) operands.iter().any(|o| in_operand::(cx, in_local, o)) . } . } 21,359 ( 0.01%) } . . /// Returns `true` if this `Place` contains qualif `Q`. 32,320 ( 0.02%) pub fn in_place<'tcx, Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool . where . Q: Qualif, . F: FnMut(Local) -> bool, . { 9 ( 0.00%) let mut place = place; . while let Some((place_base, elem)) = place.last_projection() { . match elem { . ProjectionElem::Index(index) if in_local(index) => return true, . . ProjectionElem::Deref . | ProjectionElem::Field(_, _) . | ProjectionElem::ConstantIndex { .. } . | ProjectionElem::Subslice { .. } -- line 320 ---------------------------------------- -- line 327 ---------------------------------------- . if !Q::in_any_value_of_ty(cx, proj_ty) { . return false; . } . . place = place_base; . } . . assert!(place.projection.is_empty()); 5 ( 0.00%) in_local(place.local) . } . . /// Returns `true` if this `Operand` contains qualif `Q`. 113,050 ( 0.06%) pub fn in_operand<'tcx, Q, F>( . cx: &ConstCx<'_, 'tcx>, . in_local: &mut F, . operand: &Operand<'tcx>, . ) -> bool . where . Q: Qualif, . F: FnMut(Local) -> bool, . { 25,840 ( 0.01%) let constant = match operand { . Operand::Copy(place) | Operand::Move(place) => { 19,380 ( 0.01%) return in_place::(cx, in_local, place.as_ref()); . } . . Operand::Constant(c) => c, . }; . . // Check the qualifs of the value of `const` items. 51,680 ( 0.03%) if let Some(ct) = constant.literal.const_for_ty() { 20,672 ( 0.01%) if let ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs: _, promoted }) = ct.val { . // Use qualifs of the type for the promoted. Promoteds in MIR body should be possible . // only for `NeedsNonConstDrop` with precise drop checking. This is the only const . // check performed after the promotion. Verify that with an assertion. . assert!(promoted.is_none() || Q::ALLOW_PROMOTED); . // Don't peek inside trait associated constants. . if promoted.is_none() && cx.tcx.trait_of_item(def.did).is_none() { . let qualifs = if let Some((did, param_did)) = def.as_const_arg() { . cx.tcx.at(constant.span).mir_const_qualif_const_arg((did, param_did)) -- line 366 ---------------------------------------- -- line 374 ---------------------------------------- . . // Just in case the type is more specific than . // the definition, e.g., impl associated const . // with type parameters, take it into account. . } . } . } . // Otherwise use the qualifs of the type. 28,424 ( 0.01%) Q::in_any_value_of_ty(cx, constant.literal.ty()) 96,254 ( 0.05%) } 1,947 ( 0.00%) -------------------------------------------------------------------------------- -- 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")] 2,614 ( 0.00%) pub fn from_str_radix(src: &str, radix: u32) -> Result { 1,307 ( 0.00%) from_str_radix(src, radix) 3,921 ( 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 { 4,440 ( 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 { 21,226 ( 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 { 70,229 ( 0.04%) 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 { 795,285 ( 0.40%) 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 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`. 68,074 ( 0.03%) 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`. 903 ( 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 24 ( 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 { 23,684 ( 0.01%) 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 { 41,574 ( 0.02%) 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 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 { 497,364 ( 0.25%) 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 { 254,047 ( 0.13%) 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 { 542,439 ( 0.27%) 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 1492 ---------------------------------------- . #[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)] . pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) { 217,341 ( 0.11%) let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// 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. -- line 1508 ---------------------------------------- -- line 1588 ---------------------------------------- . #[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)] . pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) { 21,381 ( 0.01%) let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// 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. -- line 1604 ---------------------------------------- -- 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) { 90,593 ( 0.05%) 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 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 { 42 ( 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 { 1,488 ( 0.00%) if self <= 1 { return 0; } . 1,425 ( 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. 4,275 ( 0.00%) let z = unsafe { intrinsics::ctlz_nonzero(p) }; 1,425 ( 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 { 1,362 ( 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 ---------------------------------------- 5,827 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs -------------------------------------------------------------------------------- Ir -- line 14 ---------------------------------------- . use rustc_target::abi::{HasDataLayout, Size, VariantIdx, Variants}; . . use super::{ . alloc_range, mir_assign_valid_types, AllocId, AllocRef, AllocRefMut, CheckInAllocMsg, . ConstAlloc, ImmTy, Immediate, InterpCx, InterpResult, LocalValue, Machine, MemoryKind, OpTy, . Operand, Pointer, PointerArithmetic, Provenance, Scalar, ScalarMaybeUninit, . }; . 11,753 ( 0.01%) #[derive(Copy, Clone, Hash, PartialEq, Eq, HashStable, Debug)] . /// Information required for the sound usage of a `MemPlace`. . pub enum MemPlaceMeta { . /// The unsized payload (e.g. length for slices or vtable pointer for trait objects). . Meta(Scalar), . /// `Sized` types or unsized `extern type` . None, . /// The address of this place may not be taken. This protects the `MemPlace` from coming from . /// a ZST Operand without a backing allocation and being converted to an integer address. This -- line 30 ---------------------------------------- -- line 33 ---------------------------------------- . Poison, . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(MemPlaceMeta, 24); . . impl MemPlaceMeta { . pub fn unwrap_meta(self) -> Scalar { 6 ( 0.00%) match self { . Self::Meta(s) => s, . Self::None | Self::Poison => { . bug!("expected wide pointer extra data (e.g. slice length or trait object vtable)") . } . } . } . fn has_meta(self) -> bool { 8,435 ( 0.00%) match self { . Self::Meta(_) => true, . Self::None | Self::Poison => false, . } . } . } . . #[derive(Copy, Clone, Hash, PartialEq, Eq, HashStable, Debug)] . pub struct MemPlace { -- line 57 ---------------------------------------- -- line 113 ---------------------------------------- . fn deref(&self) -> &MemPlace { . &self.mplace . } . } . . impl<'tcx, Tag: Provenance> From> for PlaceTy<'tcx, Tag> { . #[inline(always)] . fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self { 315 ( 0.00%) PlaceTy { place: Place::Ptr(mplace.mplace), layout: mplace.layout } . } . } . . impl MemPlace { . #[inline(always)] . pub fn from_ptr(ptr: Pointer>, align: Align) -> Self { . MemPlace { ptr, align, meta: MemPlaceMeta::None } . } -- line 129 ---------------------------------------- -- line 132 ---------------------------------------- . pub fn map_provenance(self, f: impl FnOnce(Option) -> Option) -> Self { . MemPlace { ptr: self.ptr.map_provenance(f), ..self } . } . . /// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space. . /// This is the inverse of `ref_to_mplace`. . #[inline(always)] . pub fn to_ref(self, cx: &impl HasDataLayout) -> Immediate { 30 ( 0.00%) match self.meta { 21 ( 0.00%) MemPlaceMeta::None => Immediate::from(Scalar::from_maybe_pointer(self.ptr, cx)), . MemPlaceMeta::Meta(meta) => { . Immediate::ScalarPair(Scalar::from_maybe_pointer(self.ptr, cx).into(), meta.into()) . } . MemPlaceMeta::Poison => bug!( . "MPlaceTy::dangling may never be used to produce a \ . place that will have the address of its pointee taken" . ), . } -- line 149 ---------------------------------------- -- line 177 ---------------------------------------- . #[inline] . pub fn offset( . &self, . offset: Size, . meta: MemPlaceMeta, . layout: TyAndLayout<'tcx>, . cx: &impl HasDataLayout, . ) -> InterpResult<'tcx, Self> { 60,173 ( 0.03%) Ok(MPlaceTy { mplace: self.mplace.offset(offset, meta, cx)?, layout }) . } . . #[inline] . pub fn from_aligned_ptr(ptr: Pointer>, layout: TyAndLayout<'tcx>) -> Self { 13 ( 0.00%) MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout } . } . . #[inline] 3 ( 0.00%) pub(super) fn len(&self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> { 12 ( 0.00%) if self.layout.is_unsized() { . // We need to consult `meta` metadata 6 ( 0.00%) match self.layout.ty.kind() { 1 ( 0.00%) ty::Slice(..) | ty::Str => self.mplace.meta.unwrap_meta().to_machine_usize(cx), . _ => bug!("len not supported on unsized type {:?}", self.layout.ty), . } . } else { . // Go through the layout. There are lots of types that support a length, . // e.g., SIMD types. (But not all repr(simd) types even have FieldsShape::Array!) 4 ( 0.00%) match self.layout.fields { 4 ( 0.00%) FieldsShape::Array { count, .. } => Ok(count), . _ => bug!("len not supported on sized type {:?}", self.layout.ty), . } . } 6 ( 0.00%) } . . #[inline] . pub(super) fn vtable(&self) -> Scalar { . match self.layout.ty.kind() { . ty::Dynamic(..) => self.mplace.meta.unwrap_meta(), . _ => bug!("vtable not supported on type {:?}", self.layout.ty), . } . } -- line 217 ---------------------------------------- -- line 218 ---------------------------------------- . } . . // These are defined here because they produce a place. . impl<'tcx, Tag: Provenance> OpTy<'tcx, Tag> { . #[inline(always)] . /// Note: do not call `as_ref` on the resulting place. This function should only be used to . /// read from the resulting mplace, not to get its address back. . pub fn try_as_mplace(&self) -> Result, ImmTy<'tcx, Tag>> { 27,236 ( 0.01%) match **self { 123,084 ( 0.06%) Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }), . Operand::Immediate(_) if self.layout.is_zst() => Ok(MPlaceTy::dangling(self.layout)), 18,256 ( 0.01%) Operand::Immediate(imm) => Err(ImmTy::from_immediate(imm, self.layout)), . } . } . . #[inline(always)] . /// Note: do not call `as_ref` on the resulting place. This function should only be used to . /// read from the resulting mplace, not to get its address back. . pub fn assert_mem_place(&self) -> MPlaceTy<'tcx, Tag> { . self.try_as_mplace().unwrap() -- line 237 ---------------------------------------- -- line 263 ---------------------------------------- . M: Machine<'mir, 'tcx, PointerTag = Tag>, . { . /// Take a value, which represents a (thin or wide) reference, and make it a place. . /// Alignment is just based on the type. This is the inverse of `MemPlace::to_ref()`. . /// . /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not . /// want to ever use the place for memory access! . /// Generally prefer `deref_operand`. 60 ( 0.00%) pub fn ref_to_mplace( . &self, . val: &ImmTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { . let pointee_type = 18 ( 0.00%) val.layout.ty.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty; 18 ( 0.00%) let layout = self.layout_of(pointee_type)?; 30 ( 0.00%) let (ptr, meta) = match **val { 8 ( 0.00%) Immediate::Scalar(ptr) => (ptr, MemPlaceMeta::None), 14 ( 0.00%) Immediate::ScalarPair(ptr, meta) => (ptr, MemPlaceMeta::Meta(meta.check_init()?)), . }; . . let mplace = MemPlace { . ptr: self.scalar_to_ptr(ptr.check_init()?), . // We could use the run-time alignment here. For now, we do not, because . // the point of tracking the alignment here is to make sure that the *static* . // alignment information emitted with the loads is correct. The run-time . // alignment can only be more restrictive. 6 ( 0.00%) align: layout.align.abi, . meta, . }; 102 ( 0.00%) Ok(MPlaceTy { mplace, layout }) 54 ( 0.00%) } . . /// Take an operand, representing a pointer, and dereference it to a place -- that . /// will always be a MemPlace. Lives in `place.rs` because it creates a place. 22 ( 0.00%) pub fn deref_operand( . &self, . src: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { 6 ( 0.00%) let val = self.read_immediate(src)?; . trace!("deref to {} on {:?}", val.layout.ty, *val); 4 ( 0.00%) let mplace = self.ref_to_mplace(&val)?; 10 ( 0.00%) self.check_mplace_access(mplace, CheckInAllocMsg::DerefTest)?; 22 ( 0.00%) Ok(mplace) 18 ( 0.00%) } . . #[inline] . pub(super) fn get_alloc( . &self, . place: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Option>> { . assert!(!place.layout.is_unsized()); 5,831 ( 0.00%) assert!(!place.meta.has_meta()); 5,831 ( 0.00%) let size = place.layout.size; 52,479 ( 0.03%) self.memory.get(place.ptr, size, place.align) . } . . #[inline] . pub(super) fn get_alloc_mut( . &mut self, . place: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Option>> { 2,602 ( 0.00%) assert!(!place.layout.is_unsized()); 2,602 ( 0.00%) assert!(!place.meta.has_meta()); 2,602 ( 0.00%) let size = place.layout.size; 15,612 ( 0.01%) self.memory.get_mut(place.ptr, size, place.align) . } . . /// Check if this mplace is dereferenceable and sufficiently aligned. . fn check_mplace_access( . &self, . mplace: MPlaceTy<'tcx, M::PointerTag>, . msg: CheckInAllocMsg, . ) -> InterpResult<'tcx> { . let (size, align) = self . .size_and_align_of_mplace(&mplace)? 2 ( 0.00%) .unwrap_or((mplace.layout.size, mplace.layout.align.abi)); 2 ( 0.00%) assert!(mplace.mplace.align <= align, "dynamic alignment less strict than static one?"); 2 ( 0.00%) let align = M::enforce_alignment(&self.memory.extra).then_some(align); 6 ( 0.00%) self.memory.check_ptr_access_align(mplace.ptr, size, align.unwrap_or(Align::ONE), msg)?; . Ok(()) . } . . /// Offset a pointer to project to a field of a struct/union. Unlike `place_field`, this is . /// always possible without allocating, so it can take `&self`. Also return the field's layout. . /// This supports both struct and array fields. . /// . /// This also works for arrays, but then the `usize` index type is restricting. . /// For indexing into arrays, use `mplace_index`. . #[inline(always)] . pub fn mplace_field( . &self, . base: &MPlaceTy<'tcx, M::PointerTag>, . field: usize, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { 38,846 ( 0.02%) let offset = base.layout.fields.offset(field); 27,900 ( 0.01%) let field_layout = base.layout.field(self, field); . . // Offset may need adjustment for unsized fields. 56,317 ( 0.03%) let (meta, offset) = if field_layout.is_unsized() { . // Re-use parent metadata to determine dynamic field layout. . // With custom DSTS, this *will* execute user-defined code, but the same . // happens at run-time so that's okay. . match self.size_and_align_of(&base.meta, &field_layout)? { . Some((_, align)) => (base.meta, offset.align_to(align)), . None => { . // For unsized types with an extern type tail we perform no adjustments. . // NOTE: keep this in sync with `PlaceRef::project_field` in the codegen backend. -- line 369 ---------------------------------------- -- line 374 ---------------------------------------- . } else { . // base.meta could be present; we might be accessing a sized field of an unsized . // struct. . (MemPlaceMeta::None, offset) . }; . . // We do not look at `base.layout.align` nor `field_layout.align`, unlike . // codegen -- mostly to see if we can get away with that 10,348 ( 0.01%) base.offset(offset, meta, field_layout, self) . } . . /// Index into an array. . #[inline(always)] . pub fn mplace_index( . &self, . base: &MPlaceTy<'tcx, M::PointerTag>, . index: u64, -- line 390 ---------------------------------------- -- line 409 ---------------------------------------- . "`mplace_index` called on non-array type {:?}", . base.layout.ty . ), . } . } . . // Iterates over all fields of an array. Much more efficient than doing the . // same by repeatedly calling `mplace_array`. 30 ( 0.00%) pub(super) fn mplace_array_fields<'a>( . &self, . base: &'a MPlaceTy<'tcx, Tag>, . ) -> InterpResult<'tcx, impl Iterator>> + 'a> . { 12 ( 0.00%) let len = base.len(self)?; // also asserts that we have a type where this makes sense 9 ( 0.00%) let stride = match base.layout.fields { 3 ( 0.00%) FieldsShape::Array { stride, .. } => stride, . _ => span_bug!(self.cur_span(), "mplace_array_fields: expected an array layout"), . }; 6 ( 0.00%) let layout = base.layout.field(self, 0); 3 ( 0.00%) let dl = &self.tcx.data_layout; . // `Size` multiplication 11,649 ( 0.01%) Ok((0..len).map(move |i| base.offset(stride * i, MemPlaceMeta::None, layout, dl))) 27 ( 0.00%) } . . fn mplace_subslice( . &self, . base: &MPlaceTy<'tcx, M::PointerTag>, . from: u64, . to: u64, . from_end: bool, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { -- line 439 ---------------------------------------- -- line 476 ---------------------------------------- . } . . pub(crate) fn mplace_downcast( . &self, . base: &MPlaceTy<'tcx, M::PointerTag>, . variant: VariantIdx, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { . // Downcasts only change the layout 2 ( 0.00%) assert!(!base.meta.has_meta()); 4 ( 0.00%) Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..*base }) . } . . /// Project into an mplace . pub(super) fn mplace_projection( . &self, . base: &MPlaceTy<'tcx, M::PointerTag>, . proj_elem: mir::PlaceElem<'tcx>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { -- line 493 ---------------------------------------- -- line 542 ---------------------------------------- . assert_eq!(layout.size, base.layout.size); . Ok((MPlaceTy { layout, ..*base }, len)) . } . . /// Gets the place of a field inside the place, and also the field's type. . /// Just a convenience function, but used quite a bit. . /// This is the only projection that might have a side-effect: We cannot project . /// into the field of a local `ScalarPair`, we have to first allocate it. 32,450 ( 0.02%) pub fn place_field( . &mut self, . base: &PlaceTy<'tcx, M::PointerTag>, . field: usize, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { . // FIXME: We could try to be smarter and avoid allocation for fields that span the . // entire place. 3,245 ( 0.00%) let mplace = self.force_allocation(base)?; 38,940 ( 0.02%) Ok(self.mplace_field(&mplace, field)?.into()) 25,960 ( 0.01%) } . . pub fn place_index( . &mut self, . base: &PlaceTy<'tcx, M::PointerTag>, . index: u64, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { . let mplace = self.force_allocation(base)?; . Ok(self.mplace_index(&mplace, index)?.into()) -- line 567 ---------------------------------------- -- line 568 ---------------------------------------- . } . . pub fn place_downcast( . &self, . base: &PlaceTy<'tcx, M::PointerTag>, . variant: VariantIdx, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { . // Downcast just changes the layout 24 ( 0.00%) Ok(match base.place { . Place::Ptr(mplace) => { . self.mplace_downcast(&MPlaceTy { mplace, layout: base.layout }, variant)?.into() . } . Place::Local { .. } => { 21 ( 0.00%) let layout = base.layout.for_variant(self, variant); 3 ( 0.00%) PlaceTy { layout, ..*base } . } . }) . } . . /// Projects into a place. . pub fn place_projection( . &mut self, . base: &PlaceTy<'tcx, M::PointerTag>, . &proj_elem: &mir::ProjectionElem>, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { . use rustc_middle::mir::ProjectionElem::*; 38,945 ( 0.02%) Ok(match proj_elem { 12,955 ( 0.01%) Field(field, _) => self.place_field(base, field.index())?, . Downcast(_, variant) => self.place_downcast(base, variant)?, 16 ( 0.00%) Deref => self.deref_operand(&self.place_to_op(base)?)?.into(), . // For the other variants, we have to force an allocation. . // This matches `operand_projection`. . Subslice { .. } | ConstantIndex { .. } | Index(_) => { . let mplace = self.force_allocation(base)?; . self.mplace_projection(&mplace, proj_elem)?.into() . } . }) . } -- line 605 ---------------------------------------- -- line 611 ---------------------------------------- . base: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, u64)> { . let mplace = self.force_allocation(base)?; . self.mplace_to_simd(&mplace) . } . . /// Computes a place. You should only use this if you intend to write into this . /// place; for reading, a more efficient alternative is `eval_place_for_read`. 21,264 ( 0.01%) pub fn eval_place( . &mut self, . place: mir::Place<'tcx>, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { 13,290 ( 0.01%) let mut place_ty = PlaceTy { . // This works even for dead/uninitialized locals; we check further when writing . place: Place::Local { frame: self.frame_idx(), local: place.local }, . layout: self.layout_of_local(self.frame(), place.local, None)?, . }; . 5,194 ( 0.00%) for elem in place.projection.iter() { 2,596 ( 0.00%) place_ty = self.place_projection(&place_ty, &elem)? . } . . trace!("{:?}", self.dump_place(place_ty.place)); . // Sanity-check the type we ended up with. . debug_assert!(mir_assign_valid_types( . *self.tcx, . self.param_env, . self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions( . place.ty(&self.frame().body.local_decls, *self.tcx).ty . )?)?, . place_ty.layout, . )); 47,826 ( 0.02%) Ok(place_ty) 21,264 ( 0.01%) } . . /// Write an immediate to a place . #[inline(always)] . pub fn write_immediate( . &mut self, . src: Immediate, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 43 ( 0.00%) self.write_immediate_no_validate(src, dest)?; . . if M::enforce_validity(self) { . // Data got changed, better make sure it matches the type! . self.validate_operand(&self.place_to_op(dest)?)?; . } . . Ok(()) . } -- line 661 ---------------------------------------- -- line 678 ---------------------------------------- . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { . self.write_scalar(Scalar::from_maybe_pointer(ptr.into(), self), dest) . } . . /// Write an immediate to a place. . /// If you use this you are responsible for validating that things got copied at the . /// right type. 2,600 ( 0.00%) fn write_immediate_no_validate( . &mut self, . src: Immediate, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { . if cfg!(debug_assertions) { . // This is a very common path, avoid some checks in release mode . assert!(!dest.layout.is_unsized(), "Cannot write unsized data"); . match src { -- line 694 ---------------------------------------- -- line 705 ---------------------------------------- . // FIXME: Can we check anything here? . } . } . } . trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty); . . // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`, . // but not factored as a separate function. 5,224 ( 0.00%) let mplace = match dest.place { 22 ( 0.00%) Place::Local { frame, local } => { 8 ( 0.00%) match M::access_local_mut(self, frame, local)? { . Ok(local) => { . // Local can be updated in-place. 98 ( 0.00%) *local = LocalValue::Live(Operand::Immediate(src)); . return Ok(()); . } . Err(mplace) => { . // The local is in memory, go on below. . mplace . } . } . } 15,606 ( 0.01%) Place::Ptr(mplace) => mplace, // already referring to memory . }; 23,410 ( 0.01%) let dest = MPlaceTy { mplace, layout: dest.layout }; . . // This is already in memory, write there. 28,592 ( 0.01%) self.write_immediate_to_mplace_no_validate(src, &dest) 5,200 ( 0.00%) } . . /// Write an immediate to memory. . /// If you use this you are responsible for validating that things got copied at the . /// right type. 26,020 ( 0.01%) fn write_immediate_to_mplace_no_validate( . &mut self, . value: Immediate, . dest: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { . // Note that it is really important that the type here is the right one, and matches the . // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here . // to handle padding properly, which is only correct if we never look at this data with the . // wrong type. . . // Invalid places are a thing: the return place of a diverging function 2,602 ( 0.00%) let tcx = *self.tcx; 5,204 ( 0.00%) let mut alloc = match self.get_alloc_mut(dest)? { 13,010 ( 0.01%) Some(a) => a, . None => return Ok(()), // zero-sized access . }; . . // FIXME: We should check that there are dest.layout.size many bytes available in . // memory. The code below is not sufficient, with enough padding it might not . // cover all the bytes! 5,204 ( 0.00%) match value { . Immediate::Scalar(scalar) => { 5,202 ( 0.00%) match dest.layout.abi { . Abi::Scalar(_) => {} // fine . _ => span_bug!( . self.cur_span(), . "write_immediate_to_mplace: invalid Scalar layout: {:#?}", . dest.layout . ), . } 23,409 ( 0.01%) alloc.write_scalar(alloc_range(Size::ZERO, dest.layout.size), scalar) . } . Immediate::ScalarPair(a_val, b_val) => { . // We checked `ptr_align` above, so all fields will have the alignment they need. . // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`, . // which `ptr.offset(b_offset)` cannot possibly fail to satisfy. 2 ( 0.00%) let (a, b) = match dest.layout.abi { 3 ( 0.00%) Abi::ScalarPair(a, b) => (a.value, b.value), . _ => span_bug!( . self.cur_span(), . "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}", . dest.layout . ), . }; . let (a_size, b_size) = (a.size(&tcx), b.size(&tcx)); . let b_offset = a_size.align_to(b.align(&tcx).abi); . . // It is tempting to verify `b_offset` against `layout.fields.offset(1)`, . // but that does not work: We could be a newtype around a pair, then the . // fields do not match the `ScalarPair` components. . 10 ( 0.00%) alloc.write_scalar(alloc_range(Size::ZERO, a_size), a_val)?; 8 ( 0.00%) alloc.write_scalar(alloc_range(b_offset, b_size), b_val) . } . } 20,816 ( 0.01%) } . . /// Copies the data from an operand to a place. This does not support transmuting! . /// Use `copy_op_transmute` if the layouts could disagree. . #[inline(always)] . pub fn copy_op( . &mut self, . src: &OpTy<'tcx, M::PointerTag>, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 16,885 ( 0.01%) self.copy_op_no_validate(src, dest)?; . . if M::enforce_validity(self) { . // Data got changed, better make sure it matches the type! . self.validate_operand(&self.place_to_op(dest)?)?; . } . . Ok(()) . } . . /// Copies the data from an operand to a place. This does not support transmuting! . /// Use `copy_op_transmute` if the layouts could disagree. . /// Also, if you use this you are responsible for validating that things get copied at the . /// right type. 25,944 ( 0.01%) fn copy_op_no_validate( . &mut self, . src: &OpTy<'tcx, M::PointerTag>, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { . // We do NOT compare the types for equality, because well-typed code can . // actually "transmute" `&mut T` to `&T` in an assignment without a cast. 58,422 ( 0.03%) if !mir_assign_valid_types(*self.tcx, self.param_env, src.layout, dest.layout) { . span_bug!( . self.cur_span(), . "type mismatch when copying!\nsrc: {:?},\ndest: {:?}", . src.layout.ty, . dest.layout.ty, . ); . } . . // Let us see if the layout is simple so we take a shortcut, avoid force_allocation. 16,231 ( 0.01%) let src = match self.try_read_immediate(src)? { . Ok(src_val) => { 2,600 ( 0.00%) assert!(!src.layout.is_unsized(), "cannot have unsized immediates"); . // Yay, we got a value that we can write directly. . // FIXME: Add a check to make sure that if `src` is indirect, . // it does not overlap with `dest`. 33,748 ( 0.02%) return self.write_immediate_no_validate(*src_val, dest); . } 5,176 ( 0.00%) Err(mplace) => mplace, . }; . // Slow path, this does not fit into an immediate. Just memcpy. . trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty); . . // This interprets `src.meta` with the `dest` local's layout, if an unsized local . // is being initialized! 8,411 ( 0.00%) let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?; . let size = size.unwrap_or_else(|| { 1,941 ( 0.00%) assert!( . !dest.layout.is_unsized(), . "Cannot copy into already initialized unsized place" . ); 647 ( 0.00%) dest.layout.size . }); 647 ( 0.00%) assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances"); . 647 ( 0.00%) self.memory 1,941 ( 0.00%) .copy(src.ptr, src.align, dest.ptr, dest.align, size, /*nonoverlapping*/ true) 25,944 ( 0.01%) } . . /// Copies the data from an operand to a place. The layouts may disagree, but they must . /// have the same size. 48 ( 0.00%) pub fn copy_op_transmute( . &mut self, . src: &OpTy<'tcx, M::PointerTag>, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 108 ( 0.00%) if mir_assign_valid_types(*self.tcx, self.param_env, src.layout, dest.layout) { . // Fast path: Just use normal `copy_op` . return self.copy_op(src, dest); . } . // We still require the sizes to match. . if src.layout.size != dest.layout.size { . // FIXME: This should be an assert instead of an error, but if we transmute within an . // array length computation, `typeck` may not have yet been run and errored out. In fact . // most likey we *are* running `typeck` right now. Investigate whether we can bail out -- line 878 ---------------------------------------- -- line 916 ---------------------------------------- . /// Ensures that a place is in memory, and returns where it is. . /// If the place currently refers to a local that doesn't yet have a matching allocation, . /// create such an allocation. . /// This is essentially `force_to_memplace`. . /// . /// This supports unsized types and returns the computed size to avoid some . /// redundant computation when copying; use `force_allocation` for a simpler, sized-only . /// version. 35,055 ( 0.02%) pub fn force_allocation_maybe_sized( . &mut self, . place: &PlaceTy<'tcx, M::PointerTag>, . meta: MemPlaceMeta, . ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option)> { 38,950 ( 0.02%) let (mplace, size) = match place.place { 3,270 ( 0.00%) Place::Local { frame, local } => { 6,528 ( 0.00%) match M::access_local_mut(self, frame, local)? { 5,922 ( 0.00%) Ok(&mut local_val) => { . // We need to make an allocation. . . // We need the layout of the local. We can NOT use the layout we got, . // that might e.g., be an inner field of a struct with `Scalar` layout, . // that has different alignment than the outer field. . let local_layout = 3,320 ( 0.00%) self.layout_of_local(&self.stack()[frame], local, None)?; . // We also need to support unsized types, and hence cannot use `allocate`. 2,622 ( 0.00%) let (size, align) = self . .size_and_align_of(&meta, &local_layout)? . .expect("Cannot allocate for non-dyn-sized type"); 4,596 ( 0.00%) let ptr = self.memory.allocate(size, align, MemoryKind::Stack)?; . let mplace = MemPlace { ptr: ptr.into(), align, meta }; 3,290 ( 0.00%) if let LocalValue::Live(Operand::Immediate(value)) = local_val { . // Preserve old value. . // We don't have to validate as we can assume the local . // was already valid for its type. . let mplace = MPlaceTy { mplace, layout: local_layout }; . self.write_immediate_to_mplace_no_validate(value, &mplace)?; . } . // Now we can call `access_mut` again, asserting it goes well, . // and actually overwrite things. 12,472 ( 0.01%) *M::access_local_mut(self, frame, local).unwrap().unwrap() = . LocalValue::Live(Operand::Indirect(mplace)); 4,606 ( 0.00%) (mplace, Some(size)) . } 25,872 ( 0.01%) Err(mplace) => (mplace, None), // this already was an indirect local . } . } 8,437 ( 0.00%) Place::Ptr(mplace) => (mplace, None), . }; . // Return with the original layout, so that the caller can go on 46,740 ( 0.02%) Ok((MPlaceTy { mplace, layout: place.layout }, size)) 31,160 ( 0.02%) } . . #[inline(always)] . pub fn force_allocation( . &mut self, . place: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { 29,223 ( 0.01%) Ok(self.force_allocation_maybe_sized(place, MemPlaceMeta::None)?.0) . } . 72 ( 0.00%) pub fn allocate( . &mut self, . layout: TyAndLayout<'tcx>, . kind: MemoryKind, . ) -> InterpResult<'static, MPlaceTy<'tcx, M::PointerTag>> { 96 ( 0.00%) let ptr = self.memory.allocate(layout.size, layout.align.abi, kind)?; 54 ( 0.00%) Ok(MPlaceTy::from_aligned_ptr(ptr.into(), layout)) 63 ( 0.00%) } . . /// Returns a wide MPlace of type `&'static [mut] str` to a new 1-aligned allocation. . pub fn allocate_str( . &mut self, . str: &str, . kind: MemoryKind, . mutbl: Mutability, . ) -> MPlaceTy<'tcx, M::PointerTag> { -- line 991 ---------------------------------------- -- line 998 ---------------------------------------- . self.tcx.lifetimes.re_static, . ty::TypeAndMut { ty: self.tcx.types.str_, mutbl }, . ); . let layout = self.layout_of(ty).unwrap(); . MPlaceTy { mplace, layout } . } . . /// Writes the discriminant of the given variant. 88 ( 0.00%) pub fn write_discriminant( . &mut self, . variant_index: VariantIdx, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { . // This must be an enum or generator. 32 ( 0.00%) match dest.layout.ty.kind() { 16 ( 0.00%) ty::Adt(adt, _) => assert!(adt.is_enum()), . ty::Generator(..) => {} . _ => span_bug!( . self.cur_span(), . "write_discriminant called on non-variant-type (neither enum nor generator)" . ), . } . // Layout computation excludes uninhabited variants from consideration . // therefore there's no way to represent those variants in the given layout. . // Essentially, uninhabited variants do not have a tag that corresponds to their . // discriminant, so we cannot do anything here. . // When evaluating we will always error before even getting here, but ConstProp 'executes' . // dead code, so we cannot ICE here. 56 ( 0.00%) if dest.layout.for_variant(self, variant_index).abi.is_uninhabited() { . throw_ub!(UninhabitedEnumVariantWritten) . } . 40 ( 0.00%) match dest.layout.variants { . Variants::Single { index } => { . assert_eq!(index, variant_index); . } . Variants::Multiple { . tag_encoding: TagEncoding::Direct, 24 ( 0.00%) tag: tag_layout, 8 ( 0.00%) tag_field, . .. . } => { . // No need to validate that the discriminant here because the . // `TyAndLayout::for_variant()` call earlier already checks the variant is valid. . . let discr_val = 32 ( 0.00%) dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val; . . // raw discriminants for enums are isize or bigger during . // their computation, but the in-memory tag is the smallest possible . // representation . let size = tag_layout.value.size(self); . let tag_val = size.truncate(discr_val); . 32 ( 0.00%) let tag_dest = self.place_field(dest, tag_field)?; . self.write_scalar(Scalar::from_uint(tag_val, size), &tag_dest)?; . } . Variants::Multiple { . tag_encoding: . TagEncoding::Niche { dataful_variant, ref niche_variants, niche_start }, . tag: tag_layout, . tag_field, . .. -- line 1060 ---------------------------------------- -- line 1082 ---------------------------------------- . // Write result. . let niche_dest = self.place_field(dest, tag_field)?; . self.write_immediate(*tag_val, &niche_dest)?; . } . } . } . . Ok(()) 64 ( 0.00%) } . 54 ( 0.00%) pub fn raw_const_to_mplace( . &self, . raw: ConstAlloc<'tcx>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { . // This must be an allocation in `tcx` 18 ( 0.00%) let _ = self.tcx.global_alloc(raw.alloc_id); . let ptr = self.global_base_pointer(Pointer::from(raw.alloc_id))?; 21 ( 0.00%) let layout = self.layout_of(raw.ty)?; 36 ( 0.00%) Ok(MPlaceTy::from_aligned_ptr(ptr.into(), layout)) 42 ( 0.00%) } . . /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type. . /// Also return some more information so drop doesn't have to run the same code twice. . pub(super) fn unpack_dyn_trait( . &self, . mplace: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> { . let vtable = self.scalar_to_ptr(mplace.vtable()); // also sanity checks the type -- line 1109 ---------------------------------------- 51,661 ( 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 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 { 26,055 ( 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 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 { 3,630 ( 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 { 12,576 ( 0.01%) *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 1237 ---------------------------------------- . /// `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,552,849 ( 0.79%) 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_typeck/src/check/coercion.rs -------------------------------------------------------------------------------- Ir -- line 73 ---------------------------------------- . /// See #47489 and #48598 . /// See docs on the "AllowTwoPhase" type for a more detailed discussion . allow_two_phase: AllowTwoPhase, . } . . impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> { . type Target = FnCtxt<'a, 'tcx>; . fn deref(&self) -> &Self::Target { 29,180 ( 0.01%) &self.fcx . } . } . . type CoerceResult<'tcx> = InferResult<'tcx, (Vec>, Ty<'tcx>)>; . . /// Coercing a mutable reference to an immutable works, while . /// coercing `&T` to `&mut T` should be forbidden. . fn coerce_mutbls<'tcx>( . from_mutbl: hir::Mutability, . to_mutbl: hir::Mutability, . ) -> RelateResult<'tcx, ()> { 9 ( 0.00%) match (from_mutbl, to_mutbl) { . (hir::Mutability::Mut, hir::Mutability::Mut | hir::Mutability::Not) . | (hir::Mutability::Not, hir::Mutability::Not) => Ok(()), . (hir::Mutability::Not, hir::Mutability::Mut) => Err(TypeError::Mutability), . } . } . . /// Do not require any adjustments, i.e. coerce `x -> x`. . fn identity(_: Ty<'_>) -> Vec> { -- line 101 ---------------------------------------- -- line 107 ---------------------------------------- . } . . /// This always returns `Ok(...)`. . fn success<'tcx>( . adj: Vec>, . target: Ty<'tcx>, . obligations: traits::PredicateObligations<'tcx>, . ) -> CoerceResult<'tcx> { 7,972 ( 0.00%) Ok(InferOk { value: (adj, target), obligations }) . } . . impl<'f, 'tcx> Coerce<'f, 'tcx> { . fn new( . fcx: &'f FnCtxt<'f, 'tcx>, . cause: ObligationCause<'tcx>, . allow_two_phase: AllowTwoPhase, . ) -> Self { 21,274 ( 0.01%) Coerce { fcx, cause, allow_two_phase, use_lub: false } . } . 58,344 ( 0.03%) fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> { . debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub); . self.commit_if_ok(|_| { 10,608 ( 0.01%) if self.use_lub { 8 ( 0.00%) self.at(&self.cause, self.fcx.param_env).lub(b, a) . } else { 10,600 ( 0.01%) self.at(&self.cause, self.fcx.param_env) . .sup(b, a) . .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations }) . } . }) 42,432 ( 0.02%) } . . /// Unify two types (using sub or lub) and produce a specific coercion. 10,612 ( 0.01%) fn unify_and(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F) -> CoerceResult<'tcx> . where . F: FnOnce(Ty<'tcx>) -> Vec>, . { 13,251 ( 0.01%) self.unify(&a, &b) 10,580 ( 0.01%) .and_then(|InferOk { value: ty, obligations }| success(f(ty), ty, obligations)) 7,959 ( 0.00%) } . 55,860 ( 0.03%) #[instrument(skip(self))] . fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { . // First, remove any resolved type variables (at the top level, at least): 2,660 ( 0.00%) let a = self.shallow_resolve(a); 2,660 ( 0.00%) let b = self.shallow_resolve(b); . debug!("Coerce.tys({:?} => {:?})", a, b); . . // Just ignore error types. 5,320 ( 0.00%) if a.references_error() || b.references_error() { . return success(vec![], self.fcx.tcx.ty_error(), vec![]); . } . . // Coercing from `!` to any type is allowed: 2,660 ( 0.00%) if a.is_never() { . return success(simple(Adjust::NeverToAny)(b), b, vec![]); . } . . // Coercing *from* an unresolved inference variable means that . // we have no information about the source type. This will always . // ultimately fall back to some form of subtyping. 2,660 ( 0.00%) if a.is_ty_var() { . return self.coerce_from_inference_variable(a, b, identity); . } . . // Consider coercing the subtype to a DST . // . // NOTE: this is wrapped in a `commit_if_ok` because it creates . // a "spurious" type variable, and we don't want to have that . // type variable in memory if the coercion fails. . let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b)); 10,638 ( 0.01%) match unsize { . Ok(_) => { . debug!("coerce: unsize successful"); 15 ( 0.00%) return unsize; . } . Err(TypeError::ObjectUnsafeCoercion(did)) => { . debug!("coerce: unsize not object safe"); . return Err(TypeError::ObjectUnsafeCoercion(did)); . } . Err(error) => { . debug!(?error, "coerce: unsize failed"); . } . } . . // Examine the supertype and consider auto-borrowing. 13,293 ( 0.01%) match *b.kind() { . ty::RawPtr(mt_b) => { . return self.coerce_unsafe_ptr(a, b, mt_b.mutbl); . } 2 ( 0.00%) ty::Ref(r_b, _, mutbl_b) => { 6 ( 0.00%) return self.coerce_borrowed_pointer(a, b, r_b, mutbl_b); . } . _ => {} . } . 18,598 ( 0.01%) match *a.kind() { . ty::FnDef(..) => { . // Function items are coercible to any closure . // type; function pointers are not (that would . // require double indirection). . // Additionally, we permit coercion of function . // items to drop the unsafe qualifier. 12 ( 0.00%) self.coerce_from_fn_item(a, b) . } . ty::FnPtr(a_f) => { . // We permit coercion of fn pointers to drop the . // unsafe qualifier. . self.coerce_from_fn_pointer(a, a_f, b) . } 9 ( 0.00%) ty::Closure(closure_def_id_a, substs_a) => { . // Non-capturing closures are coercible to . // function pointers or unsafe function pointers. . // It cannot convert closures that require unsafe. 24 ( 0.00%) self.coerce_closure_to_fn(a, closure_def_id_a, substs_a, b) . } . _ => { . // Otherwise, just use unification rules. 13,265 ( 0.01%) self.unify_and(a, b, identity) . } . } 5,320 ( 0.00%) } . . /// Coercing *from* an inference variable. In this case, we have no information . /// about the source type, so we can't really do a true coercion and we always . /// fall back to subtyping (`unify_and`). . fn coerce_from_inference_variable( . &self, . a: Ty<'tcx>, . b: Ty<'tcx>, -- line 237 ---------------------------------------- -- line 278 ---------------------------------------- . // to do something useful. . self.unify_and(a, b, make_adjustments) . } . } . . /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`. . /// To match `A` with `B`, autoderef will be performed, . /// calling `deref`/`deref_mut` where necessary. 10 ( 0.00%) fn coerce_borrowed_pointer( . &self, . a: Ty<'tcx>, . b: Ty<'tcx>, . r_b: ty::Region<'tcx>, . mutbl_b: hir::Mutability, . ) -> CoerceResult<'tcx> { . debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b); . . // If we have a parameter of type `&M T_a` and the value . // provided is `expr`, we will be adding an implicit borrow, . // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore, . // to type check, we will construct the type that `&M*expr` would . // yield. . 2 ( 0.00%) let (r_a, mt_a) = match *a.kind() { 3 ( 0.00%) ty::Ref(r_a, ty, mutbl) => { . let mt_a = ty::TypeAndMut { ty, mutbl }; . coerce_mutbls(mt_a.mutbl, mutbl_b)?; . (r_a, mt_a) . } . _ => return self.unify_and(a, b, identity), . }; . 2 ( 0.00%) let span = self.cause.span; . . let mut first_error = None; . let mut r_borrow_var = None; . let mut autoderef = self.autoderef(span, a); . let mut found = None; . 4 ( 0.00%) for (referent_ty, autoderefs) in autoderef.by_ref() { 4 ( 0.00%) if autoderefs == 0 { . // Don't let this pass, otherwise it would cause . // &T to autoref to &&T. . continue; . } . . // At this point, we have deref'd `a` to `referent_ty`. So . // imagine we are coercing from `&'a mut Vec` to `&'b mut [T]`. . // In the autoderef loop for `&'a mut Vec`, we would get -- line 326 ---------------------------------------- -- line 386 ---------------------------------------- . // this extra edge causes the region `'a` to be inferred to something . // too big, which then results in borrowck errors.) . // - We could track the innermost shared reference, but there is already . // code in regionck that has the job of creating links between . // the region of a borrow and the regions in the thing being . // borrowed (here, `'a` and `'x`), and it knows how to handle . // all the various cases. So instead we just make a region variable . // and let regionck figure it out. 2 ( 0.00%) let r = if !self.use_lub { . r_b // [2] above . } else if autoderefs == 1 { . r_a // [3] above . } else { . if r_borrow_var.is_none() { . // create var lazily, at most once . let coercion = Coercion(span); . let r = self.next_region_var(coercion); . r_borrow_var = Some(r); // [4] above . } . r_borrow_var.unwrap() . }; 1 ( 0.00%) let derefd_ty_a = self.tcx.mk_ref( . r, . TypeAndMut { . ty: referent_ty, . mutbl: mutbl_b, // [1] above . }, . ); 7 ( 0.00%) match self.unify(derefd_ty_a, b) { . Ok(ok) => { 4 ( 0.00%) found = Some(ok); . break; . } . Err(err) => { . if first_error.is_none() { . first_error = Some(err); . } . } . } . } . . // Extract type or return an error. We return the first error . // we got, which should be from relating the "base" type . // (e.g., in example above, the failure from relating `Vec` . // to the target type), since that should be the least . // confusing. 8 ( 0.00%) let InferOk { value: ty, mut obligations } = match found { . Some(d) => d, . None => { . let err = first_error.expect("coerce_borrowed_pointer had no error"); . debug!("coerce_borrowed_pointer: failed with err = {:?}", err); . return Err(err); . } . }; . 6 ( 0.00%) if ty == a && mt_a.mutbl == hir::Mutability::Not && autoderef.step_count() == 1 { . // As a special case, if we would produce `&'a *x`, that's . // a total no-op. We end up with the type `&'a T` just as . // we started with. In that case, just skip it . // altogether. This is just an optimization. . // . // Note that for `&mut`, we DO want to reborrow -- . // otherwise, this would be a move, which might be an . // error. For example `foo(self.x)` where `self` and . // `self.x` both have `&mut `type would be a move of . // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`, . // which is a borrow. 2 ( 0.00%) assert_eq!(mutbl_b, hir::Mutability::Not); // can only coerce &T -> &U 4 ( 0.00%) return success(vec![], ty, obligations); . } . . let InferOk { value: mut adjustments, obligations: o } = . self.adjust_steps_as_infer_ok(&autoderef); . obligations.extend(o); . obligations.extend(autoderef.into_obligations()); . . // Now apply the autoref. We have to extract the region out of -- line 462 ---------------------------------------- -- line 474 ---------------------------------------- . adjustments.push(Adjustment { . kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)), . target: ty, . }); . . debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}", ty, adjustments); . . success(adjustments, ty, obligations) 8 ( 0.00%) } . . // &[T; n] or &mut [T; n] -> &[T] . // or &mut [T; n] -> &mut [T] . // or &Concrete -> &Trait, etc. . #[instrument(skip(self), level = "debug")] . fn coerce_unsized(&self, mut source: Ty<'tcx>, mut target: Ty<'tcx>) -> CoerceResult<'tcx> { . source = self.shallow_resolve(source); . target = self.shallow_resolve(target); -- line 490 ---------------------------------------- -- line 506 ---------------------------------------- . // would need to be generic over the self-type (`impl CoerceUnsized for T`) . // or generic over the `CoerceUnsized` type parameter (`impl CoerceUnsized for . // SomeType`). . // . // However, these are exactly the kinds of impls which are forbidden by . // the compiler! Therefore, we can be sure that coercion will always fail . // when either the source or target type is a type variable. This allows us . // to skip performing any trait selection, and immediately bail out. 2,660 ( 0.00%) if source.is_ty_var() { . debug!("coerce_unsized: source is a TyVar, bailing out"); . return Err(TypeError::Mismatch); . } 2,690 ( 0.00%) if target.is_ty_var() { . debug!("coerce_unsized: target is a TyVar, bailing out"); . return Err(TypeError::Mismatch); . } . . let traits = 31,740 ( 0.02%) (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait()); 10,580 ( 0.01%) let (Some(unsize_did), Some(coerce_unsized_did)) = traits else { . debug!("missing Unsize or CoerceUnsized traits"); . return Err(TypeError::Mismatch); . }; . . // Note, we want to avoid unnecessary unsizing. We don't want to coerce to . // a DST unless we have to. This currently comes out in the wash since . // we can't unify [T] with U. But to properly support DST, we need to allow . // that, at which point we will need extra checks on the target here. . . // Handle reborrows before selecting `Source: CoerceUnsized`. 5,296 ( 0.00%) let reborrow = match (source.kind(), target.kind()) { 6 ( 0.00%) (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => { . coerce_mutbls(mutbl_a, mutbl_b)?; . 2 ( 0.00%) let coercion = Coercion(self.cause.span); 10 ( 0.00%) let r_borrow = self.next_region_var(coercion); . let mutbl = match mutbl_b { . hir::Mutability::Not => AutoBorrowMutability::Not, . hir::Mutability::Mut => AutoBorrowMutability::Mut { . // We don't allow two-phase borrows here, at least for initial . // implementation. If it happens that this coercion is a function argument, . // the reborrow in coerce_borrowed_ptr will pick it up. . allow_two_phase_borrow: AllowTwoPhase::No, . }, . }; . Some(( . Adjustment { kind: Adjust::Deref(None), target: ty_a }, . Adjustment { . kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)), 2 ( 0.00%) target: self . .tcx . .mk_ref(r_borrow, ty::TypeAndMut { mutbl: mutbl_b, ty: ty_a }), . }, . )) . } . (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => { . coerce_mutbls(mt_a, mt_b)?; . -- line 563 ---------------------------------------- -- line 574 ---------------------------------------- . let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target); . . // Setup either a subtyping or a LUB relationship between . // the `CoerceUnsized` target type and the expected type. . // We only have the latter, so we use an inference variable . // for the former and let type inference do the rest. . let origin = TypeVariableOrigin { . kind: TypeVariableOriginKind::MiscVariable, 2,645 ( 0.00%) span: self.cause.span, . }; 13,225 ( 0.01%) let coerce_target = self.next_ty_var(origin); 10,580 ( 0.01%) let mut coercion = self.unify_and(coerce_target, target, |target| { . let unsize = Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target }; 5,290 ( 0.00%) match reborrow { 13,215 ( 0.01%) None => vec![unsize], 28 ( 0.00%) Some((ref deref, ref autoref)) => vec![deref.clone(), autoref.clone(), unsize], . } . })?; . 2,645 ( 0.00%) let mut selcx = traits::SelectionContext::new(self); . . // Create an obligation for `Source: CoerceUnsized`. . let cause = ObligationCause::new( 5,290 ( 0.00%) self.cause.span, 5,290 ( 0.00%) self.body_id, . ObligationCauseCode::Coercion { source, target }, . ); . . // Use a FIFO queue for this custom fulfillment procedure. . // . // A Vec (or SmallVec) is not a natural choice for a queue. However, . // this code path is hot, and this queue usually has a max length of 1 . // and almost never more than 3. By using a SmallVec we avoid an . // allocation, at the (very small) cost of (occasionally) having to . // shift subsequent elements down when removing the front element. 37,030 ( 0.02%) let mut queue: SmallVec<[_; 4]> = smallvec![traits::predicate_for_trait_def( 5,290 ( 0.00%) self.tcx, 2,645 ( 0.00%) self.fcx.param_env, 13,225 ( 0.01%) cause, . coerce_unsized_did, . 0, . coerce_source, 13,225 ( 0.01%) &[coerce_target.into()] . )]; . . let mut has_unsized_tuple_coercion = false; . let mut has_trait_upcasting_coercion = false; . . // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid . // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where . // inference might unify those two inner type variables later. . let traits = [coerce_unsized_did, unsize_did]; 5,300 ( 0.00%) while !queue.is_empty() { . let obligation = queue.remove(0); . debug!("coerce_unsized resolve step: {:?}", obligation); 2,649 ( 0.00%) let bound_predicate = obligation.predicate.kind(); 13,245 ( 0.01%) let trait_pred = match bound_predicate.skip_binder() { 15,882 ( 0.01%) ty::PredicateKind::Trait(trait_pred) if traits.contains(&trait_pred.def_id()) => { 23,823 ( 0.01%) if unsize_did == trait_pred.def_id() { 12 ( 0.00%) let self_ty = trait_pred.self_ty(); 8 ( 0.00%) let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty(); 10 ( 0.00%) if let (ty::Dynamic(ref data_a, ..), ty::Dynamic(ref data_b, ..)) = . (self_ty.kind(), unsize_ty.kind()) . { . if data_a.principal_def_id() != data_b.principal_def_id() { . debug!("coerce_unsized: found trait upcasting coercion"); . has_trait_upcasting_coercion = true; . } . } 12 ( 0.00%) if let ty::Tuple(..) = unsize_ty.kind() { . debug!("coerce_unsized: found unsized tuple coercion"); . has_unsized_tuple_coercion = true; . } . } 5,294 ( 0.00%) bound_predicate.rebind(trait_pred) . } . _ => { 12 ( 0.00%) coercion.obligations.push(obligation); . continue; . } . }; 29,117 ( 0.01%) match selcx.select(&obligation.with(trait_pred)) { . // Uncertain or unimplemented. . Ok(None) => { . if trait_pred.def_id() == unsize_did { . let trait_pred = self.resolve_vars_if_possible(trait_pred); . let self_ty = trait_pred.skip_binder().self_ty(); . let unsize_ty = trait_pred.skip_binder().trait_ref.substs[1].expect_ty(); . debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred); . match (&self_ty.kind(), &unsize_ty.kind()) { -- line 663 ---------------------------------------- -- line 679 ---------------------------------------- . } . } else { . debug!("coerce_unsized: early return - ambiguous"); . return Err(TypeError::Mismatch); . } . } . Err(traits::Unimplemented) => { . debug!("coerce_unsized: early return - can't prove obligation"); 15,864 ( 0.01%) return Err(TypeError::Mismatch); . } . . // Object safety violations or miscellaneous. . Err(err) => { . self.report_selection_error(obligation.clone(), &obligation, &err, false); . // Treat this like an obligation and follow through . // with the unsizing - the lack of a coercion should . // be silent, as it causes a type mismatch later. . } . 57 ( 0.00%) Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()), . } 5,288 ( 0.00%) } . 2 ( 0.00%) if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion { . feature_err( . &self.tcx.sess.parse_sess, . sym::unsized_tuple_coercion, . self.cause.span, . "unsized tuple coercion is not stable enough for use and is subject to change", . ) . .emit(); . } . 2 ( 0.00%) if has_trait_upcasting_coercion && !self.tcx().features().trait_upcasting { . feature_err( . &self.tcx.sess.parse_sess, . sym::trait_upcasting, . self.cause.span, . "trait upcasting coercion is experimental", . ) . .emit(); . } . 11 ( 0.00%) Ok(coercion) . } . . fn coerce_from_safe_fn( . &self, . a: Ty<'tcx>, . fn_ty_a: ty::PolyFnSig<'tcx>, . b: Ty<'tcx>, . to_unsafe: F, -- line 730 ---------------------------------------- -- line 762 ---------------------------------------- . a, . fn_ty_a, . b, . simple(Adjust::Pointer(PointerCast::UnsafeFnPointer)), . identity, . ) . } . 20 ( 0.00%) fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { . //! Attempts to coerce from the type of a Rust function item . //! into a closure or a `proc`. . . let b = self.shallow_resolve(b); 10 ( 0.00%) let InferOk { value: b, mut obligations } = 2 ( 0.00%) self.normalize_associated_types_in_as_infer_ok(self.cause.span, b); . debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b); . 4 ( 0.00%) match b.kind() { . ty::FnPtr(b_sig) => { . let a_sig = a.fn_sig(self.tcx); . // Intrinsics are not coercible to function pointers . if a_sig.abi() == Abi::RustIntrinsic || a_sig.abi() == Abi::PlatformIntrinsic { . return Err(TypeError::IntrinsicCast); . } . . // Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396). -- line 787 ---------------------------------------- -- line 817 ---------------------------------------- . simple(Adjust::Pointer(PointerCast::ReifyFnPointer)), . )?; . . obligations.extend(o2); . Ok(InferOk { value, obligations }) . } . _ => self.unify_and(a, b, identity), . } 16 ( 0.00%) } . 42 ( 0.00%) fn coerce_closure_to_fn( . &self, . a: Ty<'tcx>, . closure_def_id_a: DefId, . substs_a: SubstsRef<'tcx>, . b: Ty<'tcx>, . ) -> CoerceResult<'tcx> { . //! Attempts to coerce from the type of a non-capturing closure . //! into a function pointer. . //! . . let b = self.shallow_resolve(b); . 6 ( 0.00%) match b.kind() { . // At this point we haven't done capture analysis, which means . // that the ClosureSubsts just contains an inference variable instead . // of tuple of captured types. . // . // All we care here is if any variable is being captured and not the exact paths, . // so we check `upvars_mentioned` for root variables being captured. . ty::FnPtr(fn_ty) . if self -- line 848 ---------------------------------------- -- line 864 ---------------------------------------- . self.unify_and( . pointer_ty, . b, . simple(Adjust::Pointer(PointerCast::ClosureFnPointer(unsafety))), . ) . } . _ => self.unify_and(a, b, identity), . } 24 ( 0.00%) } . . fn coerce_unsafe_ptr( . &self, . a: Ty<'tcx>, . b: Ty<'tcx>, . mutbl_b: hir::Mutability, . ) -> CoerceResult<'tcx> { . debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b); -- line 880 ---------------------------------------- -- line 906 ---------------------------------------- . } . } . . impl<'a, 'tcx> FnCtxt<'a, 'tcx> { . /// Attempt to coerce an expression to a type, and return the . /// adjusted type of the expression, if successful. . /// Adjustments are only recorded if the coercion succeeded. . /// The expressions *must not* have any pre-existing adjustments. 37,212 ( 0.02%) pub fn try_coerce( . &self, . expr: &hir::Expr<'_>, . expr_ty: Ty<'tcx>, . target: Ty<'tcx>, . allow_two_phase: AllowTwoPhase, . cause: Option>, . ) -> RelateResult<'tcx, Ty<'tcx>> { 7,974 ( 0.00%) let source = self.resolve_vars_with_obligations(expr_ty); . debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target); . . let cause = 2,658 ( 0.00%) cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable)); . let coerce = Coerce::new(self, cause, allow_two_phase); 31,886 ( 0.02%) let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?; . 10,624 ( 0.01%) let (adjustments, _) = self.register_infer_ok_obligations(ok); 26,560 ( 0.01%) self.apply_adjustments(expr, adjustments); 7,968 ( 0.00%) Ok(if expr_ty.references_error() { self.tcx.ty_error() } else { target }) 23,922 ( 0.01%) } . . /// Same as `try_coerce()`, but without side-effects. . /// . /// Returns false if the coercion creates any obligations that result in . /// errors. . pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool { . let source = self.resolve_vars_with_obligations(expr_ty); . debug!("coercion::can_with_predicates({:?} -> {:?})", source, target); -- line 941 ---------------------------------------- -- line 967 ---------------------------------------- . } . . /// Given some expressions, their known unified type and another expression, . /// tries to unify the types, potentially inserting coercions on any of the . /// provided expressions and returns their LUB (aka "common supertype"). . /// . /// This is really an internal helper. From outside the coercion . /// module, you should instantiate a `CoerceMany` instance. 8,489 ( 0.00%) fn try_find_coercion_lub( . &self, . cause: &ObligationCause<'tcx>, . exprs: &[E], . prev_ty: Ty<'tcx>, . new: &hir::Expr<'_>, . new_ty: Ty<'tcx>, . ) -> RelateResult<'tcx, Ty<'tcx>> . where . E: AsCoercionSite, . { 3,918 ( 0.00%) let prev_ty = self.resolve_vars_with_obligations(prev_ty); 1,959 ( 0.00%) let new_ty = self.resolve_vars_with_obligations(new_ty); . debug!( . "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)", . prev_ty, . new_ty, . exprs.len() . ); . . // The following check fixes #88097, where the compiler erroneously . // attempted to coerce a closure type to itself via a function pointer. 653 ( 0.00%) if prev_ty == new_ty { 648 ( 0.00%) return Ok(prev_ty); . } . . // Special-case that coercion alone cannot handle: . // Function items or non-capturing closures of differing IDs or InternalSubsts. 16 ( 0.00%) let (a_sig, b_sig) = { 16 ( 0.00%) let is_capturing_closure = |ty| { 8 ( 0.00%) if let &ty::Closure(closure_def_id, _substs) = ty { . self.tcx.upvars_mentioned(closure_def_id.expect_local()).is_some() . } else { . false . } 16 ( 0.00%) }; 24 ( 0.00%) if is_capturing_closure(prev_ty.kind()) || is_capturing_closure(new_ty.kind()) { . (None, None) . } else { 12 ( 0.00%) match (prev_ty.kind(), new_ty.kind()) { . (ty::FnDef(..), ty::FnDef(..)) => { . // Don't reify if the function types have a LUB, i.e., they . // are the same function and their parameters have a LUB. . match self . .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty)) . { . // We have a LUB of prev_ty and new_ty, just return it. . Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)), -- line 1022 ---------------------------------------- -- line 1048 ---------------------------------------- . substs_b.as_closure().sig(), . hir::Unsafety::Normal, . )), . ), . _ => (None, None), . } . } . }; 8 ( 0.00%) if let (Some(a_sig), Some(b_sig)) = (a_sig, b_sig) { . // Intrinsics are not coercible to function pointers. . if a_sig.abi() == Abi::RustIntrinsic . || a_sig.abi() == Abi::PlatformIntrinsic . || b_sig.abi() == Abi::RustIntrinsic . || b_sig.abi() == Abi::PlatformIntrinsic . { . return Err(TypeError::IntrinsicCast); . } -- line 1064 ---------------------------------------- -- line 1094 ---------------------------------------- . } . . // Configure a Coerce instance to compute the LUB. . // We don't allow two-phase borrows on any autorefs this creates since we . // probably aren't processing function arguments here and even if we were, . // they're going to get autorefed again anyway and we can apply 2-phase borrows . // at that time. . let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No); 2 ( 0.00%) coerce.use_lub = true; . . // First try to coerce the new expression to the type of the previous ones, . // but only if the new expression has no coercion already applied to it. . let mut first_error = None; 16 ( 0.00%) if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) { 2,676 ( 0.00%) let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty)); 4 ( 0.00%) match result { . Ok(ok) => { 16 ( 0.00%) let (adjustments, target) = self.register_infer_ok_obligations(ok); 16 ( 0.00%) self.apply_adjustments(new, adjustments); . debug!( . "coercion::try_find_coercion_lub: was able to coerce from previous type {:?} to new type {:?}", . prev_ty, new_ty, . ); 4 ( 0.00%) return Ok(target); . } . Err(e) => first_error = Some(e), . } . } . . // Then try to coerce the previous expressions to the type of the new one. . // This requires ensuring there are no coercions applied to *any* of the . // previous expressions, other than noop reborrows (ignoring lifetimes). -- line 1125 ---------------------------------------- -- line 1175 ---------------------------------------- . let (adjustments, target) = self.register_infer_ok_obligations(ok); . for expr in exprs { . let expr = expr.as_coercion_site(); . self.apply_adjustments(expr, adjustments.clone()); . } . Ok(target) . } . } 5,877 ( 0.00%) } . } . . /// CoerceMany encapsulates the pattern you should use when you have . /// many expressions that are all getting coerced to a common . /// type. This arises, for example, when you have a match (the result . /// of each arm is coerced to a common type). It also arises in less . /// obvious places, such as when you have many `break foo` expressions . /// that target the same loop, or the various `return` expressions in -- line 1191 ---------------------------------------- -- line 1253 ---------------------------------------- . /// expected to pass each element in the slice to `coerce(...)` in . /// order. This is used with arrays in particular to avoid . /// needlessly cloning the slice. . pub fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self { . Self::make(expected_ty, Expressions::UpFront(coercion_sites)) . } . . fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self { 37 ( 0.00%) CoerceMany { expected_ty, final_ty: None, expressions, pushed: 0 } . } . . /// Returns the "expected type" with which this coercion was . /// constructed. This represents the "downward propagated" type . /// that was given to us at the start of typing whatever construct . /// we are typing (e.g., the match expression). . /// . /// Typically, this is used as the expected type when -- line 1269 ---------------------------------------- -- line 1281 ---------------------------------------- . self.final_ty.unwrap_or(self.expected_ty) . } . . /// Indicates that the value generated by `expression`, which is . /// of type `expression_ty`, is one of the possibilities that we . /// could coerce from. This will record `expression`, and later . /// calls to `coerce` may come back and add adjustments and things . /// if necessary. 7,752 ( 0.00%) pub fn coerce<'a>( . &mut self, . fcx: &FnCtxt<'a, 'tcx>, . cause: &ObligationCause<'tcx>, . expression: &'tcx hir::Expr<'tcx>, . expression_ty: Ty<'tcx>, . ) { 214 ( 0.00%) self.coerce_inner(fcx, cause, Some(expression), expression_ty, None, false) 5,168 ( 0.00%) } . . /// Indicates that one of the inputs is a "forced unit". This . /// occurs in a case like `if foo { ... };`, where the missing else . /// generates a "forced unit". Another example is a `loop { break; . /// }`, where the `break` has no argument expression. We treat . /// these cases slightly differently for error-reporting . /// purposes. Note that these tend to correspond to cases where . /// the `()` expression is implicit in the source, and hence we do -- line 1305 ---------------------------------------- -- line 1323 ---------------------------------------- . Some(augment_error), . label_unit_as_expected, . ) . } . . /// The inner coercion "engine". If `expression` is `None`, this . /// is a forced-unit case, and hence `expression_ty` must be . /// `Nil`. 735 ( 0.00%) #[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")] . crate fn coerce_inner<'a>( . &mut self, . fcx: &FnCtxt<'a, 'tcx>, . cause: &ObligationCause<'tcx>, . expression: Option<&'tcx hir::Expr<'tcx>>, . mut expression_ty: Ty<'tcx>, . augment_error: Option<&mut dyn FnMut(&mut DiagnosticBuilder<'_>)>, . label_expression_as_expected: bool, . ) { . // Incorporate whatever type inference information we have . // until now; in principle we might also want to process . // pending obligations, but doing so should only improve . // compatibility (hopefully that is true) by helping us . // uncover never types better. 685 ( 0.00%) if expression_ty.is_ty_var() { . expression_ty = fcx.infcx.shallow_resolve(expression_ty); . } . . // If we see any error types, just propagate that error . // upwards. 2,724 ( 0.00%) if expression_ty.references_error() || self.merged_ty().references_error() { . self.final_ty = Some(fcx.tcx.ty_error()); . return; . } . . // Handle the actual type unification etc. 105 ( 0.00%) let result = if let Some(expression) = expression { 2,043 ( 0.00%) if self.pushed == 0 { . // Special-case the first expression we are coercing. . // To be honest, I'm not entirely sure why we do this. . // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why 252 ( 0.00%) fcx.try_coerce( . expression, . expression_ty, . self.expected_ty, . AllowTwoPhase::No, 112 ( 0.00%) Some(cause.clone()), . ) . } else { 1,306 ( 0.00%) match self.expressions { 6 ( 0.00%) Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub( . cause, . exprs, . self.merged_ty(), . expression, . expression_ty, . ), 3,905 ( 0.00%) Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub( . cause, 1,950 ( 0.00%) &coercion_sites[0..self.pushed], . self.merged_ty(), . expression, . expression_ty, . ), . } . } . } else { . // this is a hack for cases where we default to `()` because -- line 1389 ---------------------------------------- -- line 1403 ---------------------------------------- . fcx.at(cause, fcx.param_env) . .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty()) . .map(|infer_ok| { . fcx.register_infer_ok_obligations(infer_ok); . expression_ty . }) . }; . 1,370 ( 0.00%) match result { 681 ( 0.00%) Ok(v) => { 681 ( 0.00%) self.final_ty = Some(v); . if let Some(e) = expression { 1,362 ( 0.00%) match self.expressions { . Expressions::Dynamic(ref mut buffer) => buffer.push(e), 1,332 ( 0.00%) Expressions::UpFront(coercion_sites) => { . // if the user gave us an array to validate, check that we got . // the next expression in the list, as expected 2,644 ( 0.00%) assert_eq!( 1,998 ( 0.00%) coercion_sites[self.pushed].as_coercion_site().hir_id, . e.hir_id . ); . } . } 2,739 ( 0.00%) self.pushed += 1; . } . } . Err(coercion_error) => { . let (expected, found) = if label_expression_as_expected { . // In the case where this is a "forced unit", like . // `break`, we want to call the `()` "expected" . // since it is implied by the syntax. . // (Note: not all force-units work this way.)" -- line 1434 ---------------------------------------- -- line 1707 ---------------------------------------- . if let ty::Dynamic(..) = ty.kind() { . return true; . } . } . } . false . } . 24 ( 0.00%) pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> { 84 ( 0.00%) if let Some(final_ty) = self.final_ty { . final_ty . } else { . // If we only had inputs that were of type `!` (or no . // inputs at all), then the final type is `!`. . assert_eq!(self.pushed, 0); . fcx.tcx.types.never . } 30 ( 0.00%) } . } . . /// Something that can be converted into an expression to which we can . /// apply a coercion. . pub trait AsCoercionSite { . fn as_coercion_site(&self) -> &hir::Expr<'_>; . } . -- line 1732 ---------------------------------------- -- line 1736 ---------------------------------------- . } . } . . impl<'a, T> AsCoercionSite for &'a T . where . T: AsCoercionSite, . { . fn as_coercion_site(&self) -> &hir::Expr<'_> { 13 ( 0.00%) (**self).as_coercion_site() . } . } . . impl AsCoercionSite for ! { . fn as_coercion_site(&self) -> &hir::Expr<'_> { . unreachable!() . } . } . . impl AsCoercionSite for hir::Arm<'_> { . fn as_coercion_site(&self) -> &hir::Expr<'_> { 14 ( 0.00%) &self.body . } . } 103,333 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/middle/region.rs -------------------------------------------------------------------------------- Ir -- line 77 ---------------------------------------- . // . // FIXME(pnkfelix): this currently derives `PartialOrd` and `Ord` to . // placate the same deriving in `ty::FreeRegion`, but we may want to . // actually attach a more meaningful ordering to scopes than the one . // generated via deriving here. . #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Copy, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub struct Scope { 3,413 ( 0.00%) pub id: hir::ItemLocalId, 64,032 ( 0.03%) pub data: ScopeData, . } . . impl fmt::Debug for Scope { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . match self.data { . ScopeData::Node => write!(fmt, "Node({:?})", self.id), . ScopeData::CallSite => write!(fmt, "CallSite({:?})", self.id), . ScopeData::Arguments => write!(fmt, "Arguments({:?})", self.id), -- line 94 ---------------------------------------- -- line 99 ---------------------------------------- . "Remainder {{ block: {:?}, first_statement_index: {}}}", . self.id, . fsi.as_u32(), . ), . } . } . } . 299,087 ( 0.15%) #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub enum ScopeData { . Node, . . /// Scope of the call-site for a function or closure . /// (outlives the arguments as well as the body). . CallSite, . -- line 115 ---------------------------------------- -- line 159 ---------------------------------------- . /// . /// N.B., likely to be replaced as API is refined; e.g., pnkfelix . /// anticipates `fn entry_node_id` and `fn each_exit_node_id`. . pub fn item_local_id(&self) -> hir::ItemLocalId { . self.id . } . . pub fn hir_id(&self, scope_tree: &ScopeTree) -> Option { 703 ( 0.00%) scope_tree . .root_body . .map(|hir_id| hir::HirId { owner: hir_id.owner, local_id: self.item_local_id() }) . } . . /// Returns the span of this `Scope`. Note that in general the . /// returned span may not correspond to the span of any `NodeId` in . /// the AST. 4,921 ( 0.00%) pub fn span(&self, tcx: TyCtxt<'_>, scope_tree: &ScopeTree) -> Span { 1,406 ( 0.00%) let hir_id = match self.hir_id(scope_tree) { . Some(hir_id) => hir_id, . None => return DUMMY_SP, . }; 2,812 ( 0.00%) let span = tcx.hir().span(hir_id); 2,812 ( 0.00%) if let ScopeData::Remainder(first_statement_index) = self.data { 18 ( 0.00%) if let Node::Block(ref blk) = tcx.hir().get(hir_id) { . // Want span for scope starting after the . // indexed statement and ending at end of . // `blk`; reuse span of `blk` and shift `lo` . // forward to end of indexed statement. . // . // (This is the special case alluded to in the . // doc-comment for this method) . 24 ( 0.00%) let stmt_span = blk.stmts[first_statement_index.index()].span; . . // To avoid issues with macro-generated spans, the span . // of the statement must be nested in that of the block. 6 ( 0.00%) if span.lo() <= stmt_span.lo() && stmt_span.lo() <= span.hi() { 12 ( 0.00%) return span.with_lo(stmt_span.lo()); . } . } . } . span 6,327 ( 0.00%) } . } . . pub type ScopeDepth = u32; . . /// The region scope tree encodes information about region relationships. . #[derive(Default, Debug)] . pub struct ScopeTree { . /// If not empty, this body is the root of this region hierarchy. -- line 209 ---------------------------------------- -- line 321 ---------------------------------------- . /// The `Span` of the yield. . pub span: Span, . /// The number of expressions and patterns appearing before the `yield` in the body, plus one. . pub expr_and_pat_count: usize, . pub source: hir::YieldSource, . } . . impl ScopeTree { 20,844 ( 0.01%) pub fn record_scope_parent(&mut self, child: Scope, parent: Option<(Scope, ScopeDepth)>) { . debug!("{:?}.parent = {:?}", child, parent); . 6,948 ( 0.00%) if let Some(p) = parent { . let prev = self.parent_map.insert(child, p); 3,449 ( 0.00%) assert!(prev.is_none()); . } . . // Record the destruction scopes for later so we can query them. 6,948 ( 0.00%) if let ScopeData::Destruction = child.data { . self.destruction_scopes.insert(child.item_local_id(), child); . } 13,740 ( 0.01%) } . 6,718 ( 0.00%) pub fn opt_destruction_scope(&self, n: hir::ItemLocalId) -> Option { . self.destruction_scopes.get(&n).cloned() 6,718 ( 0.00%) } . . pub fn record_var_scope(&mut self, var: hir::ItemLocalId, lifetime: Scope) { . debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime); 20 ( 0.00%) assert!(var != lifetime.item_local_id()); . self.var_map.insert(var, lifetime); . } . . pub fn record_rvalue_scope(&mut self, var: hir::ItemLocalId, lifetime: Option) { . debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime); 4 ( 0.00%) if let Some(lifetime) = lifetime { . assert!(var != lifetime.item_local_id()); . } . self.rvalue_scopes.insert(var, lifetime); . } . . /// Returns the narrowest scope that encloses `id`, if any. . pub fn opt_encl_scope(&self, id: Scope) -> Option { . self.parent_map.get(&id).cloned().map(|(p, _)| p) . } . . /// Returns the lifetime of the local variable `var_id` 42 ( 0.00%) pub fn var_scope(&self, var_id: hir::ItemLocalId) -> Scope { . self.var_map . .get(&var_id) . .cloned() . .unwrap_or_else(|| bug!("no enclosing scope for id {:?}", var_id)) 42 ( 0.00%) } . . /// Returns the scope when the temp created by `expr_id` will be cleaned up. 46,809 ( 0.02%) pub fn temporary_scope(&self, expr_id: hir::ItemLocalId) -> Option { . // Check for a designated rvalue scope. 6 ( 0.00%) if let Some(&s) = self.rvalue_scopes.get(&expr_id) { . debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s); . return s; . } . . // Otherwise, locate the innermost terminating scope . // if there's one. Static items, for instance, won't . // have an enclosing scope, hence no scope will be . // returned. 6,685 ( 0.00%) let mut id = Scope { id: expr_id, data: ScopeData::Node }; . 169,904 ( 0.09%) while let Some(&(p, _)) = self.parent_map.get(&id) { 57,075 ( 0.03%) match p.data { . ScopeData::Destruction => { . debug!("temporary_scope({:?}) = {:?} [enclosing]", expr_id, id); . return Some(id); . } 18,542 ( 0.01%) _ => id = p, . } . } . . debug!("temporary_scope({:?}) = None", expr_id); . None 53,496 ( 0.03%) } . . /// Returns `true` if `subscope` is equal to or is lexically nested inside `superscope`, and . /// `false` otherwise. . /// . /// Used by clippy. . pub fn is_subscope_of(&self, subscope: Scope, superscope: Scope) -> bool { . let mut s = subscope; . debug!("is_subscope_of({:?}, {:?})", subscope, superscope); -- line 408 ---------------------------------------- 113,045 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/layout.rs -------------------------------------------------------------------------------- Ir -- line 23 ---------------------------------------- . use std::iter; . use std::num::NonZeroUsize; . use std::ops::Bound; . . use rand::{seq::SliceRandom, SeedableRng}; . use rand_xoshiro::Xoshiro128StarStar; . . pub fn provide(providers: &mut ty::query::Providers) { 6 ( 0.00%) *providers = . ty::query::Providers { layout_of, fn_abi_of_fn_ptr, fn_abi_of_instance, ..*providers }; . } . . pub trait IntegerExt { . fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>, signed: bool) -> Ty<'tcx>; . fn from_attr(cx: &C, ity: attr::IntType) -> Integer; . fn from_int_ty(cx: &C, ity: ty::IntTy) -> Integer; . fn from_uint_ty(cx: &C, uty: ty::UintTy) -> Integer; -- line 39 ---------------------------------------- -- line 44 ---------------------------------------- . min: i128, . max: i128, . ) -> (Integer, bool); . } . . impl IntegerExt for Integer { . #[inline] . fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>, signed: bool) -> Ty<'tcx> { 40 ( 0.00%) match (*self, signed) { . (I8, false) => tcx.types.u8, . (I16, false) => tcx.types.u16, . (I32, false) => tcx.types.u32, . (I64, false) => tcx.types.u64, . (I128, false) => tcx.types.u128, . (I8, true) => tcx.types.i8, . (I16, true) => tcx.types.i16, . (I32, true) => tcx.types.i32, . (I64, true) => tcx.types.i64, . (I128, true) => tcx.types.i128, . } . } . . /// Gets the Integer type from an attr::IntType. 16 ( 0.00%) fn from_attr(cx: &C, ity: attr::IntType) -> Integer { . let dl = cx.data_layout(); . 40 ( 0.00%) match ity { . attr::SignedInt(ast::IntTy::I8) | attr::UnsignedInt(ast::UintTy::U8) => I8, . attr::SignedInt(ast::IntTy::I16) | attr::UnsignedInt(ast::UintTy::U16) => I16, . attr::SignedInt(ast::IntTy::I32) | attr::UnsignedInt(ast::UintTy::U32) => I32, . attr::SignedInt(ast::IntTy::I64) | attr::UnsignedInt(ast::UintTy::U64) => I64, . attr::SignedInt(ast::IntTy::I128) | attr::UnsignedInt(ast::UintTy::U128) => I128, . attr::SignedInt(ast::IntTy::Isize) | attr::UnsignedInt(ast::UintTy::Usize) => { 6 ( 0.00%) dl.ptr_sized_integer() . } . } 16 ( 0.00%) } . . fn from_int_ty(cx: &C, ity: ty::IntTy) -> Integer { . match ity { . ty::IntTy::I8 => I8, . ty::IntTy::I16 => I16, . ty::IntTy::I32 => I32, . ty::IntTy::I64 => I64, . ty::IntTy::I128 => I128, 16 ( 0.00%) ty::IntTy::Isize => cx.data_layout().ptr_sized_integer(), . } . } . fn from_uint_ty(cx: &C, ity: ty::UintTy) -> Integer { 40 ( 0.00%) match ity { . ty::UintTy::U8 => I8, . ty::UintTy::U16 => I16, . ty::UintTy::U32 => I32, . ty::UintTy::U64 => I64, . ty::UintTy::U128 => I128, 3 ( 0.00%) ty::UintTy::Usize => cx.data_layout().ptr_sized_integer(), . } . } . . /// Finds the appropriate Integer type and signedness for the given . /// signed discriminant range and `#[repr]` attribute. . /// N.B.: `u128` values above `i128::MAX` will be treated as signed, but . /// that shouldn't affect anything, other than maybe debuginfo. 12 ( 0.00%) fn repr_discr<'tcx>( . tcx: TyCtxt<'tcx>, . ty: Ty<'tcx>, . repr: &ReprOptions, . min: i128, . max: i128, . ) -> (Integer, bool) { . // Theoretically, negative values could be larger in unsigned representation . // than the unsigned representation of the signed minimum. However, if there . // are any negative values, the only valid unsigned representation is u128 . // which can fit all i128 values, so the result remains unaffected. . let unsigned_fit = Integer::fit_unsigned(cmp::max(min as u128, max as u128)); . let signed_fit = cmp::max(Integer::fit_signed(min), Integer::fit_signed(max)); . 21 ( 0.00%) if let Some(ity) = repr.int { . let discr = Integer::from_attr(&tcx, ity); 3 ( 0.00%) let fit = if ity.is_signed() { signed_fit } else { unsigned_fit }; 1 ( 0.00%) if discr < fit { . bug!( . "Integer::repr_discr: `#[repr]` hint too small for \ . discriminant range of enum `{}", . ty . ) . } . return (discr, ity.is_signed()); . } . 6 ( 0.00%) let at_least = if repr.c() { . // This is usually I32, however it can be different on some platforms, . // notably hexagon and arm-none/thumb-none . tcx.data_layout().c_enum_min_size . } else { . // repr(Rust) enums try to be as small as possible . I8 . }; . . // If there are no negative values, we can use the unsigned fit. 27 ( 0.00%) if min >= 0 { . (cmp::max(unsigned_fit, at_least), false) . } else { . (cmp::max(signed_fit, at_least), true) . } 22 ( 0.00%) } . } . . pub trait PrimitiveExt { . fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx>; . fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx>; . } . . impl PrimitiveExt for Primitive { . #[inline] . fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 48 ( 0.00%) match *self { . Int(i, signed) => i.to_ty(tcx, signed), . F32 => tcx.types.f32, . F64 => tcx.types.f64, . Pointer => tcx.mk_mut_ptr(tcx.mk_unit()), . } . } . . /// Return an *integer* type matching this primitive. -- line 168 ---------------------------------------- -- line 215 ---------------------------------------- . "unable to determine layout for `{}` because `{}` cannot be normalized", . t, . e.get_type_for_failure() . ), . } . } . } . 800 ( 0.00%) #[instrument(skip(tcx, query), level = "debug")] . fn layout_of<'tcx>( . tcx: TyCtxt<'tcx>, . query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>, . ) -> Result, LayoutError<'tcx>> { . ty::tls::with_related_context(tcx, move |icx| { 50 ( 0.00%) let (param_env, ty) = query.into_parts(); . debug!(?ty); . 200 ( 0.00%) if !tcx.recursion_limit().value_within_limit(icx.layout_depth) { . tcx.sess.fatal(&format!("overflow representing the type `{}`", ty)); . } . . // Update the ImplicitCtxt to increase the layout_depth 450 ( 0.00%) let icx = ty::tls::ImplicitCtxt { layout_depth: icx.layout_depth + 1, ..icx.clone() }; . . ty::tls::enter_context(&icx, |_| { 150 ( 0.00%) let param_env = param_env.with_reveal_all_normalized(tcx); . let unnormalized_ty = ty; . . // FIXME: We might want to have two different versions of `layout_of`: . // One that can be called after typecheck has completed and can use . // `normalize_erasing_regions` here and another one that can be called . // before typecheck has completed and uses `try_normalize_erasing_regions`. . let ty = match tcx.try_normalize_erasing_regions(param_env, ty) { . Ok(t) => t, . Err(normalization_error) => { . return Err(LayoutError::NormalizationFailure(ty, normalization_error)); . } . }; . 50 ( 0.00%) if ty != unnormalized_ty { . // Ensure this layout is also cached for the normalized type. . return tcx.layout_of(param_env.and(ty)); . } . 200 ( 0.00%) let cx = LayoutCx { tcx, param_env }; . 150 ( 0.00%) let layout = cx.layout_of_uncached(ty)?; . let layout = TyAndLayout { ty, layout }; . . cx.record_layout_for_printing(layout); . . // Type-level uninhabitedness should always imply ABI uninhabitedness. 50 ( 0.00%) if tcx.conservative_is_privately_uninhabited(param_env.and(ty)) { . assert!(layout.abi.is_uninhabited()); . } . 150 ( 0.00%) Ok(layout) . }) . }) . } . . pub struct LayoutCx<'tcx, C> { . pub tcx: C, . pub param_env: ty::ParamEnv<'tcx>, . } -- line 279 ---------------------------------------- -- line 291 ---------------------------------------- . // Invert a bijective mapping, i.e. `invert(map)[y] = x` if `map[x] = y`. . // This is used to go between `memory_index` (source field order to memory order) . // and `inverse_memory_index` (memory order to source field order). . // See also `FieldsShape::Arbitrary::memory_index` for more details. . // FIXME(eddyb) build a better abstraction for permutations, if possible. . fn invert_mapping(map: &[u32]) -> Vec { . let mut inverse = vec![0; map.len()]; . for i in 0..map.len() { 104 ( 0.00%) inverse[map[i] as usize] = i as u32; . } . inverse . } . . impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> { 63 ( 0.00%) fn scalar_pair(&self, a: Scalar, b: Scalar) -> Layout { . let dl = self.data_layout(); 49 ( 0.00%) let b_align = b.value.align(dl); 56 ( 0.00%) let align = a.value.align(dl).max(b_align).max(dl.aggregate_align); . let b_offset = a.value.size(dl).align_to(b_align.abi); . let size = (b_offset + b.value.size(dl)).align_to(align.abi); . . // HACK(nox): We iter on `b` and then `a` because `max_by_key` . // returns the last maximum. 84 ( 0.00%) let largest_niche = Niche::from_scalar(dl, b_offset, b) . .into_iter() 70 ( 0.00%) .chain(Niche::from_scalar(dl, Size::ZERO, a)) . .max_by_key(|niche| niche.available(dl)); . 133 ( 0.00%) Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, . fields: FieldsShape::Arbitrary { 14 ( 0.00%) offsets: vec![Size::ZERO, b_offset], 14 ( 0.00%) memory_index: vec![0, 1], . }, 91 ( 0.00%) abi: Abi::ScalarPair(a, b), 70 ( 0.00%) largest_niche, . align, . size, . } 56 ( 0.00%) } . 372 ( 0.00%) fn univariant_uninterned( . &self, . ty: Ty<'tcx>, . fields: &[TyAndLayout<'_>], . repr: &ReprOptions, . kind: StructKind, . ) -> Result> { . let dl = self.data_layout(); 124 ( 0.00%) let pack = repr.pack; 31 ( 0.00%) if pack.is_some() && repr.align.is_some() { . self.tcx.sess.delay_span_bug(DUMMY_SP, "struct cannot be packed and aligned"); . return Err(LayoutError::Unknown(ty)); . } . 124 ( 0.00%) let mut align = if pack.is_some() { dl.i8_align } else { dl.aggregate_align }; . . let mut inverse_memory_index: Vec = (0..fields.len() as u32).collect(); . . let optimize = !repr.inhibit_struct_field_reordering_opt(); 31 ( 0.00%) if optimize { . let end = 196 ( 0.00%) if let StructKind::MaybeUnsized = kind { fields.len() - 1 } else { fields.len() }; . let optimizing = &mut inverse_memory_index[..end]; 28 ( 0.00%) let field_align = |f: &TyAndLayout<'_>| { 80 ( 0.00%) if let Some(pack) = pack { f.align.abi.min(pack) } else { f.align.abi } . }; . . // If `-Z randomize-layout` was enabled for the type definition we can shuffle . // the field ordering to try and catch some code making assumptions about layouts . // we don't guarantee . if repr.can_randomize_type_layout() { . // `ReprOptions.layout_seed` is a deterministic seed that we can use to . // randomize field ordering with . let mut rng = Xoshiro128StarStar::seed_from_u64(repr.field_shuffle_seed); . . // Shuffle the ordering of the fields . optimizing.shuffle(&mut rng); . . // Otherwise we just leave things alone and actually optimize the type's fields . } else { 56 ( 0.00%) match kind { . StructKind::AlwaysSized | StructKind::MaybeUnsized => { 110 ( 0.00%) optimizing.sort_by_key(|&x| { . // Place ZSTs first to avoid "interesting offsets", . // especially with only one or two non-ZST fields. 70 ( 0.00%) let f = &fields[x as usize]; 14 ( 0.00%) (!f.is_zst(), cmp::Reverse(field_align(f))) . }); . } . . StructKind::Prefixed(..) => { . // Sort in ascending alignment so that the layout stays optimal . // regardless of the prefix 30 ( 0.00%) optimizing.sort_by_key(|&x| field_align(&fields[x as usize])); . } . } . . // FIXME(Kixiron): We can always shuffle fields within a given alignment class . // regardless of the status of `-Z randomize-layout` . } . } . -- line 393 ---------------------------------------- -- line 399 ---------------------------------------- . // produce `memory_index` (see `invert_mapping`). . . let mut sized = true; . let mut offsets = vec![Size::ZERO; fields.len()]; . let mut offset = Size::ZERO; . let mut largest_niche = None; . let mut largest_niche_available = 0; . 93 ( 0.00%) if let StructKind::Prefixed(prefix_size, prefix_align) = kind { . let prefix_align = 63 ( 0.00%) if let Some(pack) = pack { prefix_align.min(pack) } else { prefix_align }; . align = align.max(AbiAndPrefAlign::new(prefix_align)); . offset = prefix_size.align_to(prefix_align); . } . 26 ( 0.00%) for &i in &inverse_memory_index { 310 ( 0.00%) let field = fields[i as usize]; 52 ( 0.00%) if !sized { . self.tcx.sess.delay_span_bug( . DUMMY_SP, . &format!( . "univariant: field #{} of `{}` comes after unsized field", . offsets.len(), . ty . ), . ); . } . 130 ( 0.00%) if field.is_unsized() { . sized = false; . } . . // Invariant: offset < dl.obj_size_bound() <= 1<<61 52 ( 0.00%) let field_align = if let Some(pack) = pack { . field.align.min(AbiAndPrefAlign::new(pack)) . } else { 78 ( 0.00%) field.align . }; . offset = offset.align_to(field_align.abi); . align = align.max(field_align); . . debug!("univariant offset: {:?} field: {:#?}", offset, field); 52 ( 0.00%) offsets[i as usize] = offset; . 26 ( 0.00%) if !repr.hide_niche() { 195 ( 0.00%) if let Some(mut niche) = field.largest_niche { . let available = niche.available(dl); 36 ( 0.00%) if available > largest_niche_available { . largest_niche_available = available; . niche.offset += offset; 112 ( 0.00%) largest_niche = Some(niche); . } . } . } . 26 ( 0.00%) offset = offset.checked_add(field.size, dl).ok_or(LayoutError::SizeOverflow(ty))?; . } . 76 ( 0.00%) if let Some(repr_align) = repr.align { . align = align.max(AbiAndPrefAlign::new(repr_align)); . } . . debug!("univariant min_size: {:?}", offset); . let min_size = offset; . . // As stated above, inverse_memory_index holds field indices by increasing offset. . // This makes it an already-sorted view of the offsets vec. . // To invert it, consider: . // If field 5 has offset 0, offsets[0] is 5, and memory_index[5] should be 0. . // Field 5 would be the first element, so memory_index is i: . // Note: if we didn't optimize, it's already right. . . let memory_index = 83 ( 0.00%) if optimize { invert_mapping(&inverse_memory_index) } else { inverse_memory_index }; . . let size = min_size.align_to(align.abi); 62 ( 0.00%) let mut abi = Abi::Aggregate { sized }; . . // Unpack newtype ABIs and find scalar pairs. 124 ( 0.00%) if sized && size.bytes() > 0 { . // All other fields must be ZSTs. . let mut non_zst_fields = fields.iter().enumerate().filter(|&(_, f)| !f.is_zst()); . 6 ( 0.00%) match (non_zst_fields.next(), non_zst_fields.next(), non_zst_fields.next()) { . // We have exactly one non-ZST field. . (Some((i, field)), None, None) => { . // Field fills the struct and it has a scalar or scalar pair ABI. 50 ( 0.00%) if offsets[i].bytes() == 0 && align.abi == field.align.abi && size == field.size . { 24 ( 0.00%) match field.abi { . // For plain scalars, or vectors of them, we can't unpack . // newtypes for `#[repr(C)]`, as that affects C ABIs. 4 ( 0.00%) Abi::Scalar(_) | Abi::Vector { .. } if optimize => { . abi = field.abi; . } . // But scalar pairs are Rust-specific and get . // treated as aggregates by C ABIs anyway. . Abi::ScalarPair(..) => { . abi = field.abi; . } . _ => {} -- line 499 ---------------------------------------- -- line 503 ---------------------------------------- . . // Two non-ZST fields, and they're both scalars. . ( . Some((i, &TyAndLayout { layout: &Layout { abi: Abi::Scalar(a), .. }, .. })), . Some((j, &TyAndLayout { layout: &Layout { abi: Abi::Scalar(b), .. }, .. })), . None, . ) => { . // Order by the memory placement, not source order. 9 ( 0.00%) let ((i, a), (j, b)) = 7 ( 0.00%) if offsets[i] < offsets[j] { ((i, a), (j, b)) } else { ((j, b), (i, a)) }; 11 ( 0.00%) let pair = self.scalar_pair(a, b); 2 ( 0.00%) let pair_offsets = match pair.fields { 2 ( 0.00%) FieldsShape::Arbitrary { ref offsets, ref memory_index } => { 1 ( 0.00%) assert_eq!(memory_index, &[0, 1]); . offsets . } . _ => bug!(), . }; 9 ( 0.00%) if offsets[i] == pair_offsets[0] 1 ( 0.00%) && offsets[j] == pair_offsets[1] . && align == pair.align . && size == pair.size . { . // We can use `ScalarPair` only when it matches our . // already computed layout (including `#[repr(C)]`). 14 ( 0.00%) abi = pair.abi; . } 1 ( 0.00%) } . . _ => {} . } . } . 26 ( 0.00%) if fields.iter().any(|f| f.abi.is_uninhabited()) { . abi = Abi::Uninhabited; . } . 992 ( 0.00%) Ok(Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, 310 ( 0.00%) fields: FieldsShape::Arbitrary { offsets, memory_index }, . abi, 341 ( 0.00%) largest_niche, . align, . size, . }) 310 ( 0.00%) } . 500 ( 0.00%) fn layout_of_uncached(&self, ty: Ty<'tcx>) -> Result<&'tcx Layout, LayoutError<'tcx>> { 100 ( 0.00%) let tcx = self.tcx; 50 ( 0.00%) let param_env = self.param_env; . let dl = self.data_layout(); 62 ( 0.00%) let scalar_unit = |value: Primitive| { . let size = value.size(dl); 48 ( 0.00%) assert!(size.bits() <= 128); 53 ( 0.00%) Scalar { value, valid_range: WrappingRange { start: 0, end: size.unsigned_int_max() } } 12 ( 0.00%) }; . let scalar = |value: Primitive| tcx.intern_layout(Layout::scalar(self, scalar_unit(value))); . . let univariant = |fields: &[TyAndLayout<'_>], repr: &ReprOptions, kind| { 333 ( 0.00%) Ok(tcx.intern_layout(self.univariant_uninterned(ty, fields, repr, kind)?)) . }; . debug_assert!(!ty.has_infer_types_or_consts()); . 372 ( 0.00%) Ok(match *ty.kind() { . // Basic scalars. . ty::Bool => tcx.intern_layout(Layout::scalar( . self, 12 ( 0.00%) Scalar { value: Int(I8, false), valid_range: WrappingRange { start: 0, end: 1 } }, . )), . ty::Char => tcx.intern_layout(Layout::scalar( . self, 12 ( 0.00%) Scalar { . value: Int(I32, false), . valid_range: WrappingRange { start: 0, end: 0x10FFFF }, . }, . )), 15 ( 0.00%) ty::Int(ity) => scalar(Int(Integer::from_int_ty(dl, ity), true)), 20 ( 0.00%) ty::Uint(ity) => scalar(Int(Integer::from_uint_ty(dl, ity), false)), . ty::Float(fty) => scalar(match fty { . ty::FloatTy::F32 => F32, . ty::FloatTy::F64 => F64, . }), . ty::FnPtr(_) => { . let mut ptr = scalar_unit(Pointer); . ptr.valid_range = ptr.valid_range.with_start(1); . tcx.intern_layout(Layout::scalar(self, ptr)) -- line 588 ---------------------------------------- -- line 594 ---------------------------------------- . fields: FieldsShape::Primitive, . abi: Abi::Uninhabited, . largest_niche: None, . align: dl.i8_align, . size: Size::ZERO, . }), . . // Potentially-wide pointers. 12 ( 0.00%) ty::Ref(_, pointee, _) | ty::RawPtr(ty::TypeAndMut { ty: pointee, .. }) => { . let mut data_ptr = scalar_unit(Pointer); . if !ty.is_unsafe_ptr() { . data_ptr.valid_range = data_ptr.valid_range.with_start(1); . } . . let pointee = tcx.normalize_erasing_regions(param_env, pointee); 88 ( 0.00%) if pointee.is_sized(tcx.at(DUMMY_SP), param_env) { 136 ( 0.00%) return Ok(tcx.intern_layout(Layout::scalar(self, data_ptr))); . } . 12 ( 0.00%) let unsized_part = tcx.struct_tail_erasing_lifetimes(pointee, param_env); 12 ( 0.00%) let metadata = match unsized_part.kind() { . ty::Foreign(..) => { . return Ok(tcx.intern_layout(Layout::scalar(self, data_ptr))); . } 24 ( 0.00%) ty::Slice(_) | ty::Str => scalar_unit(Int(dl.ptr_sized_integer(), false)), . ty::Dynamic(..) => { . let mut vtable = scalar_unit(Pointer); . vtable.valid_range = vtable.valid_range.with_start(1); . vtable . } . _ => return Err(LayoutError::Unknown(unsized_part)), . }; . . // Effectively a (ptr, meta) tuple. 63 ( 0.00%) tcx.intern_layout(self.scalar_pair(data_ptr, metadata)) . } . . // Arrays and slices. 3 ( 0.00%) ty::Array(element, mut count) => { 1 ( 0.00%) if count.has_projections() { . count = tcx.normalize_erasing_regions(param_env, count); . if count.has_projections() { . return Err(LayoutError::Unknown(ty)); . } . } . 4 ( 0.00%) let count = count.try_eval_usize(tcx, param_env).ok_or(LayoutError::Unknown(ty))?; 5 ( 0.00%) let element = self.layout_of(element)?; . let size = 5 ( 0.00%) element.size.checked_mul(count, dl).ok_or(LayoutError::SizeOverflow(ty))?; . . let abi = 8 ( 0.00%) if count != 0 && tcx.conservative_is_privately_uninhabited(param_env.and(ty)) { . Abi::Uninhabited . } else { . Abi::Aggregate { sized: true } . }; . 11 ( 0.00%) let largest_niche = if count != 0 { element.largest_niche } else { None }; . 22 ( 0.00%) tcx.intern_layout(Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, 1 ( 0.00%) fields: FieldsShape::Array { stride: element.size, count }, . abi, . largest_niche, 1 ( 0.00%) align: element.align, . size, . }) . } 2 ( 0.00%) ty::Slice(element) => { 3 ( 0.00%) let element = self.layout_of(element)?; 11 ( 0.00%) tcx.intern_layout(Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, 1 ( 0.00%) fields: FieldsShape::Array { stride: element.size, count: 0 }, . abi: Abi::Aggregate { sized: false }, . largest_niche: None, 1 ( 0.00%) align: element.align, . size: Size::ZERO, . }) . } . ty::Str => tcx.intern_layout(Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, . fields: FieldsShape::Array { stride: Size::from_bytes(1), count: 0 }, . abi: Abi::Aggregate { sized: false }, . largest_niche: None, . align: dl.i8_align, . size: Size::ZERO, . }), . . // Odd unit types. 20 ( 0.00%) ty::FnDef(..) => univariant(&[], &ReprOptions::default(), StructKind::AlwaysSized)?, . ty::Dynamic(..) | ty::Foreign(..) => { . let mut unit = self.univariant_uninterned( . ty, . &[], . &ReprOptions::default(), . StructKind::AlwaysSized, . )?; . match unit.abi { -- line 692 ---------------------------------------- -- line 694 ---------------------------------------- . _ => bug!(), . } . tcx.intern_layout(unit) . } . . ty::Generator(def_id, substs, _) => self.generator_layout(ty, def_id, substs)?, . . ty::Closure(_, ref substs) => { 3 ( 0.00%) let tys = substs.as_closure().upvar_tys(); 3 ( 0.00%) univariant( 9 ( 0.00%) &tys.map(|ty| self.layout_of(ty)).collect::, _>>()?, 6 ( 0.00%) &ReprOptions::default(), . StructKind::AlwaysSized, . )? . } . 3 ( 0.00%) ty::Tuple(tys) => { . let kind = 9 ( 0.00%) if tys.len() == 0 { StructKind::AlwaysSized } else { StructKind::MaybeUnsized }; . 3 ( 0.00%) univariant( 6 ( 0.00%) &tys.iter() . .map(|k| self.layout_of(k.expect_ty())) . .collect::, _>>()?, 6 ( 0.00%) &ReprOptions::default(), . kind, . )? . } . . // SIMD vector types. 20 ( 0.00%) ty::Adt(def, substs) if def.repr.simd() => { . if !def.is_struct() { . // Should have yielded E0517 by now. . tcx.sess.delay_span_bug( . DUMMY_SP, . "#[repr(simd)] was applied to an ADT that is not a struct", . ); . return Err(LayoutError::Unknown(ty)); . } -- line 732 ---------------------------------------- -- line 833 ---------------------------------------- . abi: Abi::Vector { element: e_abi, count: e_len }, . largest_niche: e_ly.largest_niche, . size, . align, . }) . } . . // ADTs. 20 ( 0.00%) ty::Adt(def, substs) => { . // Cache the field layouts. 20 ( 0.00%) let variants = def . .variants . .iter() . .map(|v| { . v.fields . .iter() 108 ( 0.00%) .map(|field| self.layout_of(field.ty(tcx, substs))) . .collect::, _>>() . }) . .collect::, _>>()?; . 10 ( 0.00%) if def.is_union() { . if def.repr.pack.is_some() && def.repr.align.is_some() { . self.tcx.sess.delay_span_bug( . tcx.def_span(def.did), . "union cannot be packed and aligned", . ); . return Err(LayoutError::Unknown(ty)); . } . -- line 862 ---------------------------------------- -- line 921 ---------------------------------------- . } . . // A variant is absent if it's uninhabited and only has ZST fields. . // Present uninhabited variants only require space for their fields, . // but *not* an encoding of the discriminant (e.g., a tag value). . // See issue #49298 for more details on the need to leave space . // for non-ZST uninhabited data (mostly partial initialization). . let absent = |fields: &[TyAndLayout<'_>]| { 19 ( 0.00%) let uninhabited = fields.iter().any(|f| f.abi.is_uninhabited()); . let is_zst = fields.iter().all(|f| f.is_zst()); 6 ( 0.00%) uninhabited && is_zst 6 ( 0.00%) }; . let (present_first, present_second) = { . let mut present_variants = variants . .iter_enumerated() 56 ( 0.00%) .filter_map(|(i, v)| if absent(v) { None } else { Some(i) }); . (present_variants.next(), present_variants.next()) . }; 20 ( 0.00%) let present_first = match present_first { . Some(present_first) => present_first, . // Uninhabited because it has no variants, or only absent ones. . None if def.is_enum() => { . return Ok(tcx.layout_of(param_env.and(tcx.types.never))?.layout); . } . // If it's a struct, still compute a layout so that we can still compute the . // field offsets. . None => VariantIdx::new(0), . }; . 10 ( 0.00%) let is_struct = !def.is_enum() || . // Only one variant is present. 4 ( 0.00%) (present_second.is_none() && . // Representation optimizations are allowed. . !def.repr.inhibit_enum_layout_opt()); . if is_struct { . // Struct, or univariant enum equivalent to a struct. . // (Typechecking will reject discriminant-sizing attrs.) . . let v = present_first; 6 ( 0.00%) let kind = if def.is_enum() || variants[v].is_empty() { . StructKind::AlwaysSized . } else { 15 ( 0.00%) let param_env = tcx.param_env(def.did); 5 ( 0.00%) let last_field = def.variants[v].fields.last().unwrap(); . let always_sized = 30 ( 0.00%) tcx.type_of(last_field.did).is_sized(tcx.at(DUMMY_SP), param_env); 10 ( 0.00%) if !always_sized { . StructKind::MaybeUnsized . } else { . StructKind::AlwaysSized . } . }; . 78 ( 0.00%) let mut st = self.univariant_uninterned(ty, &variants[v], &def.repr, kind)?; 30 ( 0.00%) st.variants = Variants::Single { index: v }; 42 ( 0.00%) let (start, end) = self.tcx.layout_scalar_valid_range(def.did); 24 ( 0.00%) match st.abi { . Abi::Scalar(ref mut scalar) | Abi::ScalarPair(ref mut scalar, _) => { . // the asserts ensure that we are not using the . // `#[rustc_layout_scalar_valid_range(n)]` . // attribute to widen the range of anything as that would probably . // result in UB somewhere . // FIXME(eddyb) the asserts are probably not needed, . // as larger validity ranges would result in missed . // optimizations, *not* wrongly assuming the inner . // value is valid. e.g. unions enlarge validity ranges, . // because the values may be uninitialized. 15 ( 0.00%) if let Bound::Included(start) = start { . // FIXME(eddyb) this might be incorrect - it doesn't . // account for wrap-around (end < start) ranges. 4 ( 0.00%) assert!(scalar.valid_range.start <= start); 2 ( 0.00%) scalar.valid_range.start = start; . } 10 ( 0.00%) if let Bound::Included(end) = end { . // FIXME(eddyb) this might be incorrect - it doesn't . // account for wrap-around (end < start) ranges. . assert!(scalar.valid_range.end >= end); . scalar.valid_range.end = end; . } . . // Update `largest_niche` if we have introduced a larger niche. 15 ( 0.00%) let niche = if def.repr.hide_niche() { . None . } else { 50 ( 0.00%) Niche::from_scalar(dl, Size::ZERO, *scalar) . }; 35 ( 0.00%) if let Some(niche) = niche { 10 ( 0.00%) match st.largest_niche { 28 ( 0.00%) Some(largest_niche) => { . // Replace the existing niche even if they're equal, . // because this one is at a lower offset. 20 ( 0.00%) if largest_niche.available(dl) <= niche.available(dl) { 28 ( 0.00%) st.largest_niche = Some(niche); . } . } 7 ( 0.00%) None => st.largest_niche = Some(niche), . } . } . } . _ => assert!( 3 ( 0.00%) start == Bound::Unbounded && end == Bound::Unbounded, . "nonscalar layout for layout_scalar_valid_range type {:?}: {:#?}", . def, . st, . ), . } . 54 ( 0.00%) return Ok(tcx.intern_layout(st)); . } . . // At this point, we have handled all unions and . // structs. (We have also handled univariant enums . // that allow representation optimization.) . assert!(def.is_enum()); . . // The current code for niche-filling relies on variant indices . // instead of actual discriminants, so dataful enums with . // explicit discriminants (RFC #2363) would misbehave. . let no_explicit_discriminants = def . .variants . .iter_enumerated() . .all(|(i, v)| v.discr == ty::VariantDiscr::Relative(i.as_u32())); . 8 ( 0.00%) let mut niche_filling_layout = None; . . // Niche-filling enum optimization. 8 ( 0.00%) if !def.repr.inhibit_enum_layout_opt() && no_explicit_discriminants { . let mut dataful_variant = None; . let mut niche_variants = VariantIdx::MAX..=VariantIdx::new(0); . . // Find one non-ZST variant. 59 ( 0.00%) 'variants: for (v, fields) in variants.iter_enumerated() { 18 ( 0.00%) if absent(fields) { . continue 'variants; . } 12 ( 0.00%) for f in fields { . if !f.is_zst() { . if dataful_variant.is_none() { . dataful_variant = Some(v); . continue 'variants; . } else { . dataful_variant = None; . break 'variants; . } . } . } 4 ( 0.00%) niche_variants = *niche_variants.start().min(&v)..=v; . } . 3 ( 0.00%) if niche_variants.start() > niche_variants.end() { . dataful_variant = None; . } . . if let Some(i) = dataful_variant { 5 ( 0.00%) let count = (niche_variants.end().as_u32() . - niche_variants.start().as_u32() . + 1) as u128; . . // Find the field with the largest niche 1 ( 0.00%) let niche_candidate = variants[i] . .iter() . .enumerate() 2 ( 0.00%) .filter_map(|(j, field)| Some((j, field.largest_niche?))) . .max_by_key(|(_, niche)| niche.available(dl)); . 2 ( 0.00%) if let Some((field_index, niche, (niche_start, niche_scalar))) = 13 ( 0.00%) niche_candidate.and_then(|(field_index, niche)| { . Some((field_index, niche, niche.reserve(self, count)?)) . }) . { . let mut align = dl.aggregate_align; . let st = variants . .iter_enumerated() . .map(|(j, v)| { . let mut st = self.univariant_uninterned( -- line 1095 ---------------------------------------- -- line 1151 ---------------------------------------- . largest_niche, . size, . align, . }); . } . } . } . 20 ( 0.00%) let (mut min, mut max) = (i128::MAX, i128::MIN); 9 ( 0.00%) let discr_type = def.repr.discr_type(); 12 ( 0.00%) let bits = Integer::from_attr(self, discr_type).size().bits(); 53 ( 0.00%) for (i, discr) in def.discriminants(tcx) { 5 ( 0.00%) if variants[i].iter().any(|f| f.abi.is_uninhabited()) { . continue; . } . let mut x = discr.val as i128; 9 ( 0.00%) if discr_type.is_signed() { . // sign extend the raw representation to be an i128 171 ( 0.00%) x = (x << (128 - bits)) >> (128 - bits); . } 36 ( 0.00%) if x < min { 16 ( 0.00%) min = x; . } 36 ( 0.00%) if x > max { 27 ( 0.00%) max = x; . } . } . // We might have no inhabited variants, so pretend there's at least one. 4 ( 0.00%) if (min, max) == (i128::MAX, i128::MIN) { . min = 0; . max = 0; . } 20 ( 0.00%) assert!(min <= max, "discriminant range is {}...{}", min, max); 36 ( 0.00%) let (min_ity, signed) = Integer::repr_discr(tcx, ty, &def.repr, min, max); . 8 ( 0.00%) let mut align = dl.aggregate_align; 4 ( 0.00%) let mut size = Size::ZERO; . . // We're interested in the smallest alignment, so start large. 8 ( 0.00%) let mut start_align = Align::from_bytes(256).unwrap(); 20 ( 0.00%) assert_eq!(Integer::for_align(dl, start_align), None); . . // repr(C) on an enum tells us to make a (tag, union) layout, . // so we need to grow the prefix alignment to be at least . // the alignment of the union. (This value is used both for . // determining the alignment of the overall enum, and the . // determining the alignment of the payload after the tag.) 52 ( 0.00%) let mut prefix_align = min_ity.align(dl).abi; 4 ( 0.00%) if def.repr.c() { . for fields in &variants { . for field in fields { . prefix_align = prefix_align.max(field.align.abi); . } . } . } . . // Create the set of structs that represent each variant. 8 ( 0.00%) let mut layout_variants = variants . .iter_enumerated() . .map(|(i, field_layouts)| { 171 ( 0.00%) let mut st = self.univariant_uninterned( 9 ( 0.00%) ty, . &field_layouts, 18 ( 0.00%) &def.repr, 36 ( 0.00%) StructKind::Prefixed(min_ity.size(), prefix_align), . )?; 27 ( 0.00%) st.variants = Variants::Single { index: i }; . // Find the first field we can't move later . // to make room for a larger discriminant. . for field in 127 ( 0.00%) st.fields.index_by_increasing_offset().map(|j| field_layouts[j]) . { . if !field.is_zst() || field.align.abi.bytes() != 1 { 10 ( 0.00%) start_align = start_align.min(field.align.abi); . break; . } . } 36 ( 0.00%) size = cmp::max(size, st.size); 27 ( 0.00%) align = align.max(st.align); 54 ( 0.00%) Ok(st) . }) . .collect::, _>>()?; . . // Align the maximum variant size to the largest alignment. 20 ( 0.00%) size = size.align_to(align.abi); . 16 ( 0.00%) if size.bytes() >= dl.obj_size_bound() { . return Err(LayoutError::SizeOverflow(ty)); . } . 16 ( 0.00%) let typeck_ity = Integer::from_attr(dl, def.repr.discr_type()); 12 ( 0.00%) if typeck_ity < min_ity { . // It is a bug if Layout decided on a greater discriminant size than typeck for . // some reason at this point (based on values discriminant can take on). Mostly . // because this discriminant will be loaded, and then stored into variable of . // type calculated by typeck. Consider such case (a bug): typeck decided on . // byte-sized discriminant, but layout thinks we need a 16-bit to store all . // discriminant values. That would be a bug, because then, in codegen, in order . // to store this 16-bit discriminant into 8-bit sized temporary some of the . // space necessary to represent would have to be discarded (or layout is wrong -- line 1250 ---------------------------------------- -- line 1263 ---------------------------------------- . // as the alignment of the first field of each variant. . // We increase the size of the discriminant to avoid LLVM copying . // padding when it doesn't need to. This normally causes unaligned . // load/stores and excessive memcpy/memset operations. By using a . // bigger integer size, LLVM can be sure about its contents and . // won't be so conservative. . . // Use the initial field alignment 12 ( 0.00%) let mut ity = if def.repr.c() || def.repr.int.is_some() { . min_ity . } else { 9 ( 0.00%) Integer::for_align(dl, start_align).unwrap_or(min_ity) . }; . . // If the alignment is not larger than the chosen discriminant size, . // don't use the alignment as the final size. 3 ( 0.00%) if ity <= min_ity { . ity = min_ity; . } else { . // Patch up the variants' first few fields. 6 ( 0.00%) let old_ity_size = min_ity.size(); . let new_ity_size = ity.size(); . for variant in &mut layout_variants { 12 ( 0.00%) match variant.fields { . FieldsShape::Arbitrary { ref mut offsets, .. } => { . for i in offsets { 15 ( 0.00%) if *i <= old_ity_size { . assert_eq!(*i, old_ity_size); . *i = new_ity_size; . } . } . // We might be making the struct larger. 6 ( 0.00%) if variant.size <= old_ity_size { 2 ( 0.00%) variant.size = new_ity_size; . } . } . _ => bug!(), . } . } . } . 4 ( 0.00%) let tag_mask = ity.size().unsigned_int_max(); . let tag = Scalar { . value: Int(ity, signed), . valid_range: WrappingRange { 20 ( 0.00%) start: (min as u128 & tag_mask), 16 ( 0.00%) end: (max as u128 & tag_mask), . }, . }; . let mut abi = Abi::Aggregate { sized: true }; 24 ( 0.00%) if tag.value.size(dl) == size { . abi = Abi::Scalar(tag); . } else { . // Try to use a ScalarPair for all tagged enums. . let mut common_prim = None; . for (field_layouts, layout_variant) in iter::zip(&variants, &layout_variants) { 12 ( 0.00%) let offsets = match layout_variant.fields { . FieldsShape::Arbitrary { ref offsets, .. } => offsets, . _ => bug!(), . }; . let mut fields = . iter::zip(field_layouts, offsets).filter(|p| !p.0.is_zst()); 60 ( 0.00%) let (field, offset) = match (fields.next(), fields.next()) { . (None, None) => continue, . (Some(pair), None) => pair, . _ => { . common_prim = None; . break; . } . }; 15 ( 0.00%) let prim = match field.abi { 10 ( 0.00%) Abi::Scalar(scalar) => scalar.value, . _ => { . common_prim = None; . break; . } . }; 10 ( 0.00%) if let Some(pair) = common_prim { . // This is pretty conservative. We could go fancier . // by conflating things like i32 and u32, or even . // realising that (u8, u8) could just cohabit with . // u16 or even u32. 18 ( 0.00%) if pair != (prim, offset) { . common_prim = None; . break; . } . } else { . common_prim = Some((prim, offset)); . } . } 6 ( 0.00%) if let Some((prim, offset)) = common_prim { 51 ( 0.00%) let pair = self.scalar_pair(tag, scalar_unit(prim)); 6 ( 0.00%) let pair_offsets = match pair.fields { 6 ( 0.00%) FieldsShape::Arbitrary { ref offsets, ref memory_index } => { 3 ( 0.00%) assert_eq!(memory_index, &[0, 1]); . offsets . } . _ => bug!(), . }; 18 ( 0.00%) if pair_offsets[0] == Size::ZERO 6 ( 0.00%) && pair_offsets[1] == *offset 3 ( 0.00%) && align == pair.align 3 ( 0.00%) && size == pair.size . { . // We can use `ScalarPair` only when it matches our . // already computed layout (including `#[repr(C)]`). 81 ( 0.00%) abi = pair.abi; . } 3 ( 0.00%) } . } . . if layout_variants.iter().all(|v| v.abi.is_uninhabited()) { . abi = Abi::Uninhabited; . } . 64 ( 0.00%) let largest_niche = Niche::from_scalar(dl, Size::ZERO, tag); . . let tagged_layout = Layout { . variants: Variants::Multiple { . tag, . tag_encoding: TagEncoding::Direct, . tag_field: 0, . variants: layout_variants, . }, . fields: FieldsShape::Arbitrary { 20 ( 0.00%) offsets: vec![Size::ZERO], 16 ( 0.00%) memory_index: vec![0], . }, . largest_niche, . abi, 8 ( 0.00%) align, 4 ( 0.00%) size, . }; . 12 ( 0.00%) let best_layout = match (tagged_layout, niche_filling_layout) { . (tagged_layout, Some(niche_filling_layout)) => { . // Pick the smaller layout; otherwise, . // pick the layout with the larger niche; otherwise, . // pick tagged as it has simpler codegen. . cmp::min_by_key(tagged_layout, niche_filling_layout, |layout| { . let niche_size = layout.largest_niche.map_or(0, |n| n.available(dl)); . (layout.size, cmp::Reverse(niche_size)) . }) . } 244 ( 0.00%) (tagged_layout, None) => tagged_layout, . }; . 36 ( 0.00%) tcx.intern_layout(best_layout) 20 ( 0.00%) } . . // Types with no meaningful known layout. . ty::Projection(_) | ty::Opaque(..) => { . // NOTE(eddyb) `layout_of` query should've normalized these away, . // if that was possible, so there's no reason to try again here. . return Err(LayoutError::Unknown(ty)); . } . -- line 1419 ---------------------------------------- -- line 1420 ---------------------------------------- . ty::Placeholder(..) | ty::GeneratorWitness(..) | ty::Infer(_) => { . bug!("Layout::compute: unexpected type `{}`", ty) . } . . ty::Bound(..) | ty::Param(_) | ty::Error(_) => { . return Err(LayoutError::Unknown(ty)); . } . }) 400 ( 0.00%) } . } . . /// Overlap eligibility and variant assignment for each GeneratorSavedLocal. . #[derive(Clone, Debug, PartialEq)] . enum SavedLocalEligibility { . Unassigned, . Assigned(VariantIdx), . // FIXME: Use newtype_index so we aren't wasting bytes -- line 1436 ---------------------------------------- -- line 1755 ---------------------------------------- . } . . /// This is invoked by the `layout_of` query to record the final . /// layout of each type. . #[inline(always)] . fn record_layout_for_printing(&self, layout: TyAndLayout<'tcx>) { . // If we are running with `-Zprint-type-sizes`, maybe record layouts . // for dumping later. 250 ( 0.00%) if self.tcx.sess.opts.debugging_opts.print_type_sizes { . self.record_layout_for_printing_outlined(layout) . } . } . . fn record_layout_for_printing_outlined(&self, layout: TyAndLayout<'tcx>) { . // Ignore layouts that are done with non-empty environments or . // non-monomorphic layouts, as the user only wants to see the stuff . // resulting from the final codegen session. -- line 1771 ---------------------------------------- -- line 2041 ---------------------------------------- . . pub trait HasParamEnv<'tcx> { . fn param_env(&self) -> ty::ParamEnv<'tcx>; . } . . impl<'tcx> HasDataLayout for TyCtxt<'tcx> { . #[inline] . fn data_layout(&self) -> &TargetDataLayout { 37,074 ( 0.02%) &self.data_layout . } . } . . impl<'tcx> HasTargetSpec for TyCtxt<'tcx> { . fn target_spec(&self) -> &Target { . &self.sess.target . } . } -- line 2057 ---------------------------------------- -- line 2080 ---------------------------------------- . #[inline] . fn tcx(&self) -> TyCtxt<'tcx> { . **self . } . } . . impl<'tcx, C> HasParamEnv<'tcx> for LayoutCx<'tcx, C> { . fn param_env(&self) -> ty::ParamEnv<'tcx> { 26 ( 0.00%) self.param_env . } . } . . impl<'tcx, T: HasDataLayout> HasDataLayout for LayoutCx<'tcx, T> { . fn data_layout(&self) -> &TargetDataLayout { . self.tcx.data_layout() . } . } -- line 2096 ---------------------------------------- -- line 2098 ---------------------------------------- . impl<'tcx, T: HasTargetSpec> HasTargetSpec for LayoutCx<'tcx, T> { . fn target_spec(&self) -> &Target { . self.tcx.target_spec() . } . } . . impl<'tcx, T: HasTyCtxt<'tcx>> HasTyCtxt<'tcx> for LayoutCx<'tcx, T> { . fn tcx(&self) -> TyCtxt<'tcx> { 26 ( 0.00%) self.tcx.tcx() . } . } . . pub trait MaybeResult { . type Error; . . fn from(x: Result) -> Self; . fn to_result(self) -> Result; -- line 2114 ---------------------------------------- -- line 2124 ---------------------------------------- . Ok(self) . } . } . . impl MaybeResult for Result { . type Error = E; . . fn from(x: Result) -> Self { 2,675 ( 0.00%) x . } . fn to_result(self) -> Result { . self . } . } . . pub type TyAndLayout<'tcx> = rustc_target::abi::TyAndLayout<'tcx, Ty<'tcx>>; . -- line 2140 ---------------------------------------- -- line 2167 ---------------------------------------- . ) -> >>::Error; . } . . /// Blanket extension trait for contexts that can compute layouts of types. . pub trait LayoutOf<'tcx>: LayoutOfHelpers<'tcx> { . /// Computes the layout of a type. Note that this implicitly . /// executes in "reveal all" mode, and will normalize the input type. . #[inline] 6,538 ( 0.00%) fn layout_of(&self, ty: Ty<'tcx>) -> Self::LayoutOfResult { . self.spanned_layout_of(ty, DUMMY_SP) 6,536 ( 0.00%) } . . /// Computes the layout of a type, at `span`. Note that this implicitly . /// executes in "reveal all" mode, and will normalize the input type. . // FIXME(eddyb) avoid passing information like this, and instead add more . // `TyCtxt::at`-like APIs to be able to do e.g. `cx.at(span).layout_of(ty)`. . #[inline] . fn spanned_layout_of(&self, ty: Ty<'tcx>, span: Span) -> Self::LayoutOfResult { . let span = if !span.is_dummy() { span } else { self.layout_tcx_at_span() }; -- line 2185 ---------------------------------------- -- line 2221 ---------------------------------------- . where . C: HasTyCtxt<'tcx> + HasParamEnv<'tcx>, . { . fn ty_and_layout_for_variant( . this: TyAndLayout<'tcx>, . cx: &C, . variant_index: VariantIdx, . ) -> TyAndLayout<'tcx> { 26 ( 0.00%) let layout = match this.variants { . Variants::Single { index } . // If all variants but one are uninhabited, the variant layout is the enum layout. . if index == variant_index && . // Don't confuse variants of uninhabited enums with the enum itself. . // For more details see https://github.com/rust-lang/rust/issues/69763. . this.fields != FieldsShape::Primitive => . { . this.layout -- line 2237 ---------------------------------------- -- line 2263 ---------------------------------------- . align: tcx.data_layout.i8_align, . size: Size::ZERO, . }) . } . . Variants::Multiple { ref variants, .. } => &variants[variant_index], . }; . 104 ( 0.00%) assert_eq!(layout.variants, Variants::Single { index: variant_index }); . . TyAndLayout { ty: this.ty, layout } . } . 164,925 ( 0.08%) fn ty_and_layout_field(this: TyAndLayout<'tcx>, cx: &C, i: usize) -> TyAndLayout<'tcx> { . enum TyMaybeWithLayout<'tcx> { . Ty(Ty<'tcx>), . TyAndLayout(TyAndLayout<'tcx>), . } . 132,108 ( 0.07%) fn field_ty_or_layout<'tcx>( . this: TyAndLayout<'tcx>, . cx: &(impl HasTyCtxt<'tcx> + HasParamEnv<'tcx>), . i: usize, . ) -> TyMaybeWithLayout<'tcx> { . let tcx = cx.tcx(); . let tag_layout = |tag: Scalar| -> TyAndLayout<'tcx> { 128 ( 0.00%) let layout = Layout::scalar(cx, tag); 104 ( 0.00%) TyAndLayout { layout: tcx.intern_layout(layout), ty: tag.value.to_ty(tcx) } . }; . 33,030 ( 0.02%) match *this.ty.kind() { . ty::Bool . | ty::Char . | ty::Int(_) . | ty::Uint(_) . | ty::Float(_) . | ty::FnPtr(_) . | ty::Never . | ty::FnDef(..) -- line 2301 ---------------------------------------- -- line 2354 ---------------------------------------- . } . . // Arrays and slices. . ty::Array(element, _) | ty::Slice(element) => TyMaybeWithLayout::Ty(element), . ty::Str => TyMaybeWithLayout::Ty(tcx.types.u8), . . // Tuples, generators and closures. . ty::Closure(_, ref substs) => field_ty_or_layout( 2 ( 0.00%) TyAndLayout { ty: substs.as_closure().tupled_upvars_ty(), ..this }, . cx, . i, . ), . . ty::Generator(def_id, ref substs, _) => match this.variants { . Variants::Single { index } => TyMaybeWithLayout::Ty( . substs . .as_generator() -- line 2370 ---------------------------------------- -- line 2377 ---------------------------------------- . Variants::Multiple { tag, tag_field, .. } => { . if i == tag_field { . return TyMaybeWithLayout::TyAndLayout(tag_layout(tag)); . } . TyMaybeWithLayout::Ty(substs.as_generator().prefix_tys().nth(i).unwrap()) . } . }, . 41,384 ( 0.02%) ty::Tuple(tys) => TyMaybeWithLayout::Ty(tys[i].expect_ty()), . . // ADTs. 5 ( 0.00%) ty::Adt(def, substs) => { 26 ( 0.00%) match this.variants { 5 ( 0.00%) Variants::Single { index } => { 20 ( 0.00%) TyMaybeWithLayout::Ty(def.variants[index].fields[i].ty(tcx, substs)) . } . . // Discriminant field for enums (where applicable). . Variants::Multiple { tag, .. } => { 16 ( 0.00%) assert_eq!(i, 0); . return TyMaybeWithLayout::TyAndLayout(tag_layout(tag)); . } . } . } . . ty::Projection(_) . | ty::Bound(..) . | ty::Placeholder(..) . | ty::Opaque(..) . | ty::Param(_) . | ty::Infer(_) . | ty::Error(_) => bug!("TyAndLayout::field: unexpected type `{}`", this.ty), . } 99,081 ( 0.05%) } . 44,036 ( 0.02%) match field_ty_or_layout(this, cx, i) { 22,002 ( 0.01%) TyMaybeWithLayout::Ty(field_ty) => { . cx.tcx().layout_of(cx.param_env().and(field_ty)).unwrap_or_else(|e| { . bug!( . "failed to get layout for `{}`: {},\n\ . despite it being a field (#{}) of an existing layout: {:#?}", . field_ty, . e, . i, . this . ) . }) . } 24 ( 0.00%) TyMaybeWithLayout::TyAndLayout(field_layout) => field_layout, . } 87,960 ( 0.04%) } . . fn ty_and_layout_pointee_info_at( . this: TyAndLayout<'tcx>, . cx: &C, . offset: Size, . ) -> Option { . let tcx = cx.tcx(); . let param_env = cx.param_env(); -- line 2435 ---------------------------------------- -- line 2725 ---------------------------------------- . /// might (from a foreign exception or similar). . #[inline] . pub fn fn_can_unwind<'tcx>( . tcx: TyCtxt<'tcx>, . codegen_fn_attr_flags: CodegenFnAttrFlags, . abi: SpecAbi, . ) -> bool { . // Special attribute for functions which can't unwind. 23 ( 0.00%) if codegen_fn_attr_flags.contains(CodegenFnAttrFlags::NEVER_UNWIND) { . return false; . } . . // Otherwise if this isn't special then unwinding is generally determined by . // the ABI of the itself. ABIs like `C` have variants which also . // specifically allow unwinding (`C-unwind`), but not all platform-specific . // ABIs have such an option. Otherwise the only other thing here is Rust . // itself, and those ABIs are determined by the panic strategy configured -- line 2741 ---------------------------------------- -- line 2767 ---------------------------------------- . // to `panic=abort`). . // . // Eventually the check against `c_unwind` here will ideally get removed and . // this'll be a little cleaner as it'll be a straightforward check of the . // ABI. . // . // [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/2945-c-unwind-abi.md . use SpecAbi::*; 92 ( 0.00%) match abi { . C { unwind } | Stdcall { unwind } | System { unwind } | Thiscall { unwind } => { . unwind . || (!tcx.features().c_unwind && tcx.sess.panic_strategy() == PanicStrategy::Unwind) . } . Cdecl . | Fastcall . | Vectorcall . | Aapcs -- line 2783 ---------------------------------------- 22,275 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 84 ---------------------------------------- . pub struct SessionGlobals { . symbol_interner: symbol::Interner, . span_interner: Lock, . hygiene_data: Lock, . source_map: Lock>>, . } . . impl SessionGlobals { 12 ( 0.00%) pub fn new(edition: Edition) -> SessionGlobals { 50 ( 0.00%) SessionGlobals { 2 ( 0.00%) symbol_interner: symbol::Interner::fresh(), . span_interner: Lock::new(span_encoding::SpanInterner::default()), 6 ( 0.00%) hygiene_data: Lock::new(hygiene::HygieneData::new(edition)), . source_map: Lock::new(None), . } 10 ( 0.00%) } . } . . #[inline] . pub fn create_session_globals_then(edition: Edition, f: impl FnOnce() -> R) -> R { 1 ( 0.00%) assert!( . !SESSION_GLOBALS.is_set(), . "SESSION_GLOBALS should never be overwritten! \ . Use another thread if you need another SessionGlobals" . ); 3 ( 0.00%) let session_globals = SessionGlobals::new(edition); 7 ( 0.00%) SESSION_GLOBALS.set(&session_globals, f) 1 ( 0.00%) } . . #[inline] . pub fn set_session_globals_then(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R { . assert!( . !SESSION_GLOBALS.is_set(), . "SESSION_GLOBALS should never be overwritten! \ . Use another thread if you need another SessionGlobals" . ); -- line 119 ---------------------------------------- -- line 120 ---------------------------------------- . SESSION_GLOBALS.set(session_globals, f) . } . . #[inline] . pub fn create_default_session_if_not_set_then(f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 4 ( 0.00%) create_session_if_not_set_then(edition::DEFAULT_EDITION, f) . } . . #[inline] . pub fn create_session_if_not_set_then(edition: Edition, f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 1 ( 0.00%) if !SESSION_GLOBALS.is_set() { 3 ( 0.00%) let session_globals = SessionGlobals::new(edition); 11 ( 0.00%) SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f)) 1 ( 0.00%) } else { . SESSION_GLOBALS.with(f) . } . } . . #[inline] . pub fn with_session_globals(f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 11,730 ( 0.01%) SESSION_GLOBALS.with(f) . } . . #[inline] . pub fn create_default_session_globals_then(f: impl FnOnce() -> R) -> R { . create_session_globals_then(edition::DEFAULT_EDITION, f) . } . . // If this ever becomes non thread-local, `decode_syntax_context` . // and `decode_expn_id` will need to be updated to handle concurrent . // deserialization. . scoped_tls::scoped_thread_local!(static SESSION_GLOBALS: SessionGlobals); . . // FIXME: We should use this enum or something like it to get rid of the . // use of magic `/rust/1.x/...` paths across the board. 15 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd)] 620 ( 0.00%) #[derive(Decodable)] . pub enum RealFileName { . LocalPath(PathBuf), . /// For remapped paths (namely paths into libstd that have been mapped . /// to the appropriate spot on the local host's file system, and local file . /// system paths that have been remapped with `FilePathMapping`), . Remapped { . /// `local_path` is the (host-dependent) local path to the file. This is . /// None if the file was imported from another crate -- line 173 ---------------------------------------- -- line 179 ---------------------------------------- . } . . impl Hash for RealFileName { . fn hash(&self, state: &mut H) { . // To prevent #70924 from happening again we should only hash the . // remapped (virtualized) path if that exists. This is because . // virtualized paths to sysroot crates (/rust/$hash or /rust/$version) . // remain stable even if the corresponding local_path changes 1,594 ( 0.00%) self.remapped_path_if_available().hash(state) . } . } . . // This is functionally identical to #[derive(Encodable)], with the exception of . // an added assert statement . impl Encodable for RealFileName { . fn encode(&self, encoder: &mut S) -> Result<(), S::Error> { 4 ( 0.00%) encoder.emit_enum(|encoder| match *self { . RealFileName::LocalPath(ref local_path) => { 16 ( 0.00%) encoder.emit_enum_variant("LocalPath", 0, 1, |encoder| { . encoder.emit_enum_variant_arg(true, |encoder| local_path.encode(encoder))?; . Ok(()) . }) . } . . RealFileName::Remapped { ref local_path, ref virtual_name } => encoder . .emit_enum_variant("Remapped", 1, 2, |encoder| { . // For privacy and build reproducibility, we must not embed host-dependant path in artifacts -- line 205 ---------------------------------------- -- line 224 ---------------------------------------- . p.as_ref().map(PathBuf::as_path) . } . } . } . . /// Returns the path suitable for reading from the file system on the local host, . /// if this information exists. . /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that. 2 ( 0.00%) pub fn into_local_path(self) -> Option { 2 ( 0.00%) match self { . RealFileName::LocalPath(p) => Some(p), . RealFileName::Remapped { local_path: p, virtual_name: _ } => p, . } 3 ( 0.00%) } . . /// Returns the path suitable for embedding into build artifacts. This would still . /// be a local path if it has not been remapped. A remapped path will not correspond . /// to a valid file system path: see `local_path_if_available()` for something that . /// is more likely to return paths into the local host file system. . pub fn remapped_path_if_available(&self) -> &Path { 1,268 ( 0.00%) match self { . RealFileName::LocalPath(p) . | RealFileName::Remapped { local_path: _, virtual_name: p } => &p, . } 3 ( 0.00%) } . . /// Returns the path suitable for reading from the file system on the local host, . /// if this information exists. Otherwise returns the remapped name. . /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that. . pub fn local_path_if_available(&self) -> &Path { 2 ( 0.00%) match self { . RealFileName::LocalPath(path) . | RealFileName::Remapped { local_path: None, virtual_name: path } . | RealFileName::Remapped { local_path: Some(path), virtual_name: _ } => path, . } . } . . pub fn to_string_lossy(&self, display_pref: FileNameDisplayPreference) -> Cow<'_, str> { 2 ( 0.00%) match display_pref { . FileNameDisplayPreference::Local => self.local_path_if_available().to_string_lossy(), . FileNameDisplayPreference::Remapped => { . self.remapped_path_if_available().to_string_lossy() . } . } . } . } . . /// Differentiates between real files and common virtual files. 3,311 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)] 3,761 ( 0.00%) #[derive(Decodable, Encodable)] . pub enum FileName { . Real(RealFileName), . /// Call to `quote!`. 1 ( 0.00%) QuoteExpansion(u64), . /// Command line. . Anon(u64), . /// Hack in `src/librustc_ast/parse.rs`. . // FIXME(jseyfried) . MacroExpansion(u64), . ProcMacroSourceCode(u64), . /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`. . CfgSpec(u64), -- line 285 ---------------------------------------- -- line 288 ---------------------------------------- . /// Custom sources for explicit parser calls from plugins and drivers. . Custom(String), . DocTest(PathBuf, isize), . /// Post-substitution inline assembly from LLVM. . InlineAsm(u64), . } . . impl From for FileName { 14 ( 0.00%) fn from(p: PathBuf) -> Self { 4 ( 0.00%) assert!(!p.to_string_lossy().ends_with('>')); 12 ( 0.00%) FileName::Real(RealFileName::LocalPath(p)) 14 ( 0.00%) } . } . 4 ( 0.00%) #[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)] . pub enum FileNameDisplayPreference { . Remapped, . Local, . } . . pub struct FileNameDisplay<'a> { . inner: &'a FileName, . display_pref: FileNameDisplayPreference, . } . . impl fmt::Display for FileNameDisplay<'_> { 8 ( 0.00%) fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { . use FileName::*; 12 ( 0.00%) match *self.inner { . Real(ref name) => { 12 ( 0.00%) write!(fmt, "{}", name.to_string_lossy(self.display_pref)) . } . QuoteExpansion(_) => write!(fmt, ""), . MacroExpansion(_) => write!(fmt, ""), . Anon(_) => write!(fmt, ""), . ProcMacroSourceCode(_) => write!(fmt, ""), . CfgSpec(_) => write!(fmt, ""), . CliCrateAttr(_) => write!(fmt, ""), . Custom(ref s) => write!(fmt, "<{}>", s), . DocTest(ref path, _) => write!(fmt, "{}", path.display()), . InlineAsm(_) => write!(fmt, ""), . } 10 ( 0.00%) } . } . . impl FileNameDisplay<'_> { . pub fn to_string_lossy(&self) -> Cow<'_, str> { . match self.inner { . FileName::Real(ref inner) => inner.to_string_lossy(self.display_pref), . _ => Cow::from(format!("{}", self)), . } . } . } . . impl FileName { . pub fn is_real(&self) -> bool { . use FileName::*; 630 ( 0.00%) match *self { . Real(_) => true, . Anon(_) . | MacroExpansion(_) . | ProcMacroSourceCode(_) . | CfgSpec(_) . | CliCrateAttr(_) . | Custom(_) . | QuoteExpansion(_) -- line 353 ---------------------------------------- -- line 357 ---------------------------------------- . } . . pub fn prefer_remapped(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Remapped } . } . . // This may include transient local filesystem information. . // Must not be embedded in build outputs. 2 ( 0.00%) pub fn prefer_local(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local } 4 ( 0.00%) } . . pub fn display(&self, display_pref: FileNameDisplayPreference) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref } . } . . pub fn macro_expansion_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); -- line 375 ---------------------------------------- -- line 383 ---------------------------------------- . } . . pub fn proc_macro_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); . FileName::ProcMacroSourceCode(hasher.finish()) . } . 5 ( 0.00%) pub fn cfg_spec_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); 2 ( 0.00%) FileName::QuoteExpansion(hasher.finish()) 5 ( 0.00%) } . . pub fn cli_crate_attr_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); . FileName::CliCrateAttr(hasher.finish()) . } . . pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName { -- line 403 ---------------------------------------- -- line 423 ---------------------------------------- . /// that the length of the span is equal to `span.hi - span.lo`; there may be space in the . /// [`BytePos`] range between files. . /// . /// `SpanData` is public because `Span` uses a thread-local interner and can't be . /// sent to other threads, but some pieces of performance infra run in a separate thread. . /// Using `Span` is generally preferred. . #[derive(Clone, Copy, Hash, PartialEq, Eq)] . pub struct SpanData { 1 ( 0.00%) pub lo: BytePos, 1 ( 0.00%) pub hi: BytePos, . /// Information about where the macro came from, if this piece of . /// code was created by a macro expansion. 3 ( 0.00%) pub ctxt: SyntaxContext, 1 ( 0.00%) pub parent: Option, . } . . // Order spans by position in the file. . impl Ord for SpanData { . fn cmp(&self, other: &Self) -> Ordering { . let SpanData { . lo: s_lo, . hi: s_hi, -- line 444 ---------------------------------------- -- line 485 ---------------------------------------- . } . #[inline] . pub fn with_parent(&self, parent: Option) -> Span { . Span::new(self.lo, self.hi, self.ctxt, parent) . } . /// Returns `true` if this is a dummy span with any hygienic context. . #[inline] . pub fn is_dummy(self) -> bool { 34,552 ( 0.02%) self.lo.0 == 0 && self.hi.0 == 0 . } . /// Returns `true` if `self` fully encloses `other`. . pub fn contains(self, other: Self) -> bool { . self.lo <= other.lo && other.hi <= self.hi . } . } . . // The interner is pointed to by a thread local value which is only set on the main thread -- line 501 ---------------------------------------- -- line 502 ---------------------------------------- . // with parallelization is disabled. So we don't allow `Span` to transfer between threads . // to avoid panics and other errors, even though it would be memory safe to do so. . #[cfg(not(parallel_compiler))] . impl !Send for Span {} . #[cfg(not(parallel_compiler))] . impl !Sync for Span {} . . impl PartialOrd for Span { 4,424 ( 0.00%) fn partial_cmp(&self, rhs: &Self) -> Option { 3,318 ( 0.00%) PartialOrd::partial_cmp(&self.data(), &rhs.data()) 4,424 ( 0.00%) } . } . impl Ord for Span { . fn cmp(&self, rhs: &Self) -> Ordering { . Ord::cmp(&self.data(), &rhs.data()) . } . } . . /// A collection of `Span`s. -- line 520 ---------------------------------------- -- line 532 ---------------------------------------- . } . . impl Span { . #[inline] . pub fn lo(self) -> BytePos { . self.data().lo . } . #[inline] 6,390 ( 0.00%) pub fn with_lo(self, lo: BytePos) -> Span { . self.data().with_lo(lo) 4,260 ( 0.00%) } . #[inline] 400 ( 0.00%) pub fn hi(self) -> BytePos { . self.data().hi 400 ( 0.00%) } . #[inline] 1,035 ( 0.00%) pub fn with_hi(self, hi: BytePos) -> Span { . self.data().with_hi(hi) 690 ( 0.00%) } . #[inline] . pub fn ctxt(self) -> SyntaxContext { . self.data_untracked().ctxt . } . #[inline] 100 ( 0.00%) pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span { . self.data_untracked().with_ctxt(ctxt) 60 ( 0.00%) } . #[inline] . pub fn parent(self) -> Option { . self.data().parent . } . #[inline] . pub fn with_parent(self, ctxt: Option) -> Span { . self.data().with_parent(ctxt) . } -- line 566 ---------------------------------------- -- line 671 ---------------------------------------- . pub fn find_ancestor_inside(mut self, outer: Span) -> Option { . while !outer.contains(self) { . self = self.parent_callsite()?; . } . Some(self) . } . . /// Edition of the crate from which this span came. 519 ( 0.00%) pub fn edition(self) -> edition::Edition { . self.ctxt().edition() 346 ( 0.00%) } . . #[inline] . pub fn rust_2015(self) -> bool { 122 ( 0.00%) self.edition() == edition::Edition::Edition2015 . } . . #[inline] . pub fn rust_2018(self) -> bool { 56 ( 0.00%) self.edition() >= edition::Edition::Edition2018 . } . . #[inline] . pub fn rust_2021(self) -> bool { 30 ( 0.00%) self.edition() >= edition::Edition::Edition2021 . } . . /// Returns the source callee. . /// . /// Returns `None` if the supplied span has no expansion trace, . /// else returns the `ExpnData` for the macro definition . /// corresponding to the source callsite. . pub fn source_callee(self) -> Option { -- line 703 ---------------------------------------- -- line 707 ---------------------------------------- . } . let expn_data = self.ctxt().outer_expn_data(); . if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None } . } . . /// Checks if a span is "internal" to a macro in which `#[unstable]` . /// items can be used (that is, a macro marked with . /// `#[allow_internal_unstable]`). 5 ( 0.00%) pub fn allows_unstable(self, feature: Symbol) -> bool { 1 ( 0.00%) self.ctxt() . .outer_expn_data() . .allow_internal_unstable . .map_or(false, |features| features.iter().any(|&f| f == feature)) 4 ( 0.00%) } . . /// Checks if this span arises from a compiler desugaring of kind `kind`. 112 ( 0.00%) pub fn is_desugaring(self, kind: DesugaringKind) -> bool { 96 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => k == kind, . _ => false, . } 80 ( 0.00%) } . . /// Returns the compiler desugaring that created this span, or `None` . /// if this span is not from a desugaring. 15 ( 0.00%) pub fn desugaring_kind(self) -> Option { 18 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => Some(k), . _ => None, . } 12 ( 0.00%) } . . /// Checks if a span is "internal" to a macro in which `unsafe` . /// can be used without triggering the `unsafe_code` lint. . // (that is, a macro marked with `#[allow_internal_unsafe]`). . pub fn allows_unsafe(self) -> bool { . self.ctxt().outer_expn_data().allow_internal_unsafe . } . -- line 745 ---------------------------------------- -- line 767 ---------------------------------------- . . /// Returns a `Span` that would enclose both `self` and `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^^^^ . /// ``` 42,218 ( 0.02%) pub fn to(self, end: Span) -> Span { . let span_data = self.data(); . let end_data = end.data(); . // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480). . // Return the macro span on its own to avoid weird diagnostic output. It is preferable to . // have an incomplete span than a completely nonsensical one. 7,676 ( 0.00%) if span_data.ctxt != end_data.ctxt { . if span_data.ctxt == SyntaxContext::root() { . return end; . } else if end_data.ctxt == SyntaxContext::root() { . return self; . } . // Both spans fall within a macro. . // FIXME(estebank): check if it is the *same* macro. . } . Span::new( . cmp::min(span_data.lo, end_data.lo), . cmp::max(span_data.hi, end_data.hi), . if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt }, 26,866 ( 0.01%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 34,542 ( 0.02%) } . . /// Returns a `Span` between the end of `self` to the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^ . /// ``` 22 ( 0.00%) pub fn between(self, end: Span) -> Span { . let span = self.data(); . let end = end.data(); . Span::new( . span.hi, . end.lo, . if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt }, 14 ( 0.00%) if span.parent == end.parent { span.parent } else { None }, . ) 16 ( 0.00%) } . . /// Returns a `Span` from the beginning of `self` until the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^ . /// ``` 55 ( 0.00%) pub fn until(self, end: Span) -> Span { . // Most of this function's body is copied from `to`. . // We can't just do `self.to(end.shrink_to_lo())`, . // because to also does some magic where it uses min/max so . // it can handle overlapping spans. Some advanced mis-use of . // `until` with different ctxts makes this visible. . let span_data = self.data(); . let end_data = end.data(); . // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480). . // Return the macro span on its own to avoid weird diagnostic output. It is preferable to . // have an incomplete span than a completely nonsensical one. 10 ( 0.00%) if span_data.ctxt != end_data.ctxt { . if span_data.ctxt == SyntaxContext::root() { . return end; . } else if end_data.ctxt == SyntaxContext::root() { . return self; . } . // Both spans fall within a macro. . // FIXME(estebank): check if it is the *same* macro. . } . Span::new( . span_data.lo, . end_data.lo, . if end_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt }, 35 ( 0.00%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 45 ( 0.00%) } . . pub fn from_inner(self, inner: InnerSpan) -> Span { . let span = self.data(); . Span::new( . span.lo + BytePos::from_usize(inner.start), . span.lo + BytePos::from_usize(inner.end), . span.ctxt, . span.parent, . ) . } . . /// Equivalent of `Span::def_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span { 2 ( 0.00%) self.with_ctxt_from_mark(expn_id, Transparency::Opaque) . } . . /// Equivalent of `Span::call_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_call_site_ctxt(self, expn_id: ExpnId) -> Span { 2 ( 0.00%) self.with_ctxt_from_mark(expn_id, Transparency::Transparent) . } . . /// Equivalent of `Span::mixed_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_mixed_site_ctxt(self, expn_id: ExpnId) -> Span { . self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent) . } . . /// Produces a span with the same location as `self` and context produced by a macro with the . /// given ID and transparency, assuming that macro was defined directly and not produced by . /// some other macro (which is the case for built-in and procedural macros). 24 ( 0.00%) pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { . self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency)) 14 ( 0.00%) } . . #[inline] . pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { . let span = self.data(); . span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency)) . } . . #[inline] -- line 892 ---------------------------------------- -- line 901 ---------------------------------------- . pub fn adjust(&mut self, expn_id: ExpnId) -> Option { . let mut span = self.data(); . let mark = span.ctxt.adjust(expn_id); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } . . #[inline] 1,278 ( 0.00%) pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option { 852 ( 0.00%) let mut span = self.data(); 702 ( 0.00%) let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id); 1,278 ( 0.00%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark 1,412 ( 0.00%) } . . #[inline] . pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option> { . let mut span = self.data(); . let mark = span.ctxt.glob_adjust(expn_id, glob_span); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } -- line 922 ---------------------------------------- -- line 929 ---------------------------------------- . ) -> Option> { . let mut span = self.data(); . let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } . . #[inline] 888 ( 0.00%) pub fn normalize_to_macros_2_0(self) -> Span { . let span = self.data(); . span.with_ctxt(span.ctxt.normalize_to_macros_2_0()) 777 ( 0.00%) } . . #[inline] . pub fn normalize_to_macro_rules(self) -> Span { . let span = self.data(); . span.with_ctxt(span.ctxt.normalize_to_macro_rules()) . } . } . -- line 948 ---------------------------------------- -- line 958 ---------------------------------------- . . /// What label should we attach to this span (if any)? . pub label: Option, . } . . impl Default for Span { . fn default() -> Self { . DUMMY_SP 2 ( 0.00%) } . } . . impl Encodable for Span { . default fn encode(&self, s: &mut E) -> Result<(), E::Error> { . let span = self.data(); . s.emit_struct(false, |s| { . s.emit_struct_field("lo", true, |s| span.lo.encode(s))?; . s.emit_struct_field("hi", false, |s| span.hi.encode(s)) -- line 974 ---------------------------------------- -- line 990 ---------------------------------------- . /// any spans that are debug-printed during the closure's execution. . /// . /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap` . /// (see `rustc_interface::callbacks::span_debug1`). However, some parts . /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before . /// a `TyCtxt` is available. In this case, we fall back to . /// the `SourceMap` provided to this function. If that is not available, . /// we fall back to printing the raw `Span` field values. 9 ( 0.00%) pub fn with_source_map T>(source_map: Lrc, f: F) -> T { . with_session_globals(|session_globals| { 2 ( 0.00%) *session_globals.source_map.borrow_mut() = Some(source_map); . }); . struct ClearSourceMap; . impl Drop for ClearSourceMap { . fn drop(&mut self) { . with_session_globals(|session_globals| { 1 ( 0.00%) session_globals.source_map.borrow_mut().take(); . }); . } . } . . let _guard = ClearSourceMap; 4 ( 0.00%) f() 8 ( 0.00%) } . . pub fn debug_with_source_map( . span: Span, . f: &mut fmt::Formatter<'_>, . source_map: &SourceMap, . ) -> fmt::Result { . write!(f, "{} ({:?})", source_map.span_to_diagnostic_string(span), span.ctxt()) . } -- line 1021 ---------------------------------------- -- line 1048 ---------------------------------------- . . impl MultiSpan { . #[inline] . pub fn new() -> MultiSpan { . MultiSpan { primary_spans: vec![], span_labels: vec![] } . } . . pub fn from_span(primary_span: Span) -> MultiSpan { 95 ( 0.00%) MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] } . } . . pub fn from_spans(mut vec: Vec) -> MultiSpan { . vec.sort(); . MultiSpan { primary_spans: vec, span_labels: vec![] } . } . . pub fn push_span_label(&mut self, span: Span, label: String) { . self.span_labels.push((span, label)); . } . . /// Selects the first primary span (if any). . pub fn primary_span(&self) -> Option { . self.primary_spans.first().cloned() 10 ( 0.00%) } . . /// Returns all primary spans. . pub fn primary_spans(&self) -> &[Span] { . &self.primary_spans . } . . /// Returns `true` if any of the primary spans are displayable. . pub fn has_primary_spans(&self) -> bool { -- line 1079 ---------------------------------------- -- line 1139 ---------------------------------------- . . /// Returns `true` if any of the span labels is displayable. . pub fn has_span_labels(&self) -> bool { . self.span_labels.iter().any(|(sp, _)| !sp.is_dummy()) . } . } . . impl From for MultiSpan { 95 ( 0.00%) fn from(span: Span) -> MultiSpan { . MultiSpan::from_span(span) 95 ( 0.00%) } . } . . impl From> for MultiSpan { . fn from(spans: Vec) -> MultiSpan { . MultiSpan::from_spans(spans) . } . } . . /// Identifies an offset of a multi-byte character in a `SourceFile`. 110 ( 0.00%) #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub struct MultiByteChar { . /// The absolute offset of the character in the `SourceMap`. . pub pos: BytePos, . /// The number of bytes, `>= 2`. . pub bytes: u8, . } . . /// Identifies an offset of a non-narrow character in a `SourceFile`. 378 ( 0.00%) #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub enum NonNarrowChar { . /// Represents a zero-width character. . ZeroWidth(BytePos), . /// Represents a wide (full-width) character. . Wide(BytePos), . /// Represents a tab character, represented visually with a width of 4 characters. . Tab(BytePos), . } . . impl NonNarrowChar { . fn new(pos: BytePos, width: usize) -> Self { 40 ( 0.00%) match width { . 0 => NonNarrowChar::ZeroWidth(pos), . 2 => NonNarrowChar::Wide(pos), . 4 => NonNarrowChar::Tab(pos), . _ => panic!("width {} given for non-narrow character", width), . } . } . . /// Returns the absolute offset of the character in the `SourceMap`. -- line 1188 ---------------------------------------- -- line 1201 ---------------------------------------- . } . } . } . . impl Add for NonNarrowChar { . type Output = Self; . . fn add(self, rhs: BytePos) -> Self { 466 ( 0.00%) match self { . NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs), . NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs), . NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs), . } . } . } . . impl Sub for NonNarrowChar { . type Output = Self; . 134 ( 0.00%) fn sub(self, rhs: BytePos) -> Self { 466 ( 0.00%) match self { . NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs), . NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs), . NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs), . } 402 ( 0.00%) } . } . . /// Identifies an offset of a character that was normalized away from `SourceFile`. . #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub struct NormalizedPos { . /// The absolute offset of the character in the `SourceMap`. . pub pos: BytePos, . /// The difference between original and normalized string at position. . pub diff: u32, . } . 6 ( 0.00%) #[derive(PartialEq, Eq, Clone, Debug)] . pub enum ExternalSource { . /// No external source has to be loaded, since the `SourceFile` represents a local crate. . Unneeded, . Foreign { . kind: ExternalSourceKind, . /// This SourceFile's byte-offset within the source_map of its original crate. . original_start_pos: BytePos, . /// The end of this SourceFile within the source_map of its original crate. -- line 1246 ---------------------------------------- -- line 1267 ---------------------------------------- . _ => None, . } . } . } . . #[derive(Debug)] . pub struct OffsetOverflowError; . 626 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)] . pub enum SourceFileHashAlgorithm { . Md5, . Sha1, . Sha256, . } . . impl FromStr for SourceFileHashAlgorithm { . type Err = (); -- line 1283 ---------------------------------------- -- line 1290 ---------------------------------------- . _ => Err(()), . } . } . } . . rustc_data_structures::impl_stable_hash_via_hash!(SourceFileHashAlgorithm); . . /// The hash of the on-disk source file used for debug info. 12 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Debug)] 1,252 ( 0.00%) #[derive(HashStable_Generic, Encodable, Decodable)] . pub struct SourceFileHash { . pub kind: SourceFileHashAlgorithm, . value: [u8; 32], . } . . impl SourceFileHash { . pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash { . let mut hash = SourceFileHash { kind, value: Default::default() }; . let len = hash.hash_len(); . let value = &mut hash.value[..len]; . let data = src.as_bytes(); . match kind { . SourceFileHashAlgorithm::Md5 => { 9 ( 0.00%) value.copy_from_slice(&Md5::digest(data)); . } . SourceFileHashAlgorithm::Sha1 => { . value.copy_from_slice(&Sha1::digest(data)); . } . SourceFileHashAlgorithm::Sha256 => { . value.copy_from_slice(&Sha256::digest(data)); . } . } -- line 1321 ---------------------------------------- -- line 1329 ---------------------------------------- . . /// The bytes of the hash. . pub fn hash_bytes(&self) -> &[u8] { . let len = self.hash_len(); . &self.value[..len] . } . . fn hash_len(&self) -> usize { 9 ( 0.00%) match self.kind { . SourceFileHashAlgorithm::Md5 => 16, . SourceFileHashAlgorithm::Sha1 => 20, . SourceFileHashAlgorithm::Sha256 => 32, . } . } . } . . /// A single source in the [`SourceMap`]. 116 ( 0.00%) #[derive(Clone)] . pub struct SourceFile { . /// The name of the file that the source came from. Source that doesn't . /// originate from files has names between angle brackets by convention . /// (e.g., ``). . pub name: FileName, . /// The complete source code. 2 ( 0.00%) pub src: Option>, . /// The source code's hash. . pub src_hash: SourceFileHash, . /// The external source code (used for external crates, which will have a `None` . /// value as `self.src`. . pub external_src: Lock, . /// The start position of this source in the `SourceMap`. . pub start_pos: BytePos, . /// The end position of this source in the `SourceMap`. -- line 1361 ---------------------------------------- -- line 1364 ---------------------------------------- . pub lines: Vec, . /// Locations of multi-byte characters in the source code. . pub multibyte_chars: Vec, . /// Width of characters that are not narrow in the source code. . pub non_narrow_chars: Vec, . /// Locations of characters removed during normalization. . pub normalized_pos: Vec, . /// A hash of the filename, used for speeding up hashing in incremental compilation. 2 ( 0.00%) pub name_hash: u128, . /// Indicates which crate this `SourceFile` was imported from. 2 ( 0.00%) pub cnum: CrateNum, . } . . impl Encodable for SourceFile { . fn encode(&self, s: &mut S) -> Result<(), S::Error> { . s.emit_struct(false, |s| { . s.emit_struct_field("name", true, |s| self.name.encode(s))?; . s.emit_struct_field("src_hash", false, |s| self.src_hash.encode(s))?; . s.emit_struct_field("start_pos", false, |s| self.start_pos.encode(s))?; . s.emit_struct_field("end_pos", false, |s| self.end_pos.encode(s))?; . s.emit_struct_field("lines", false, |s| { . let lines = &self.lines[..]; . // Store the length. . s.emit_u32(lines.len() as u32)?; . 8 ( 0.00%) if !lines.is_empty() { . // In order to preserve some space, we exploit the fact that . // the lines list is sorted and individual lines are . // probably not that long. Because of that we can store lines . // as a difference list, using as little space as possible . // for the differences. . let max_line_length = if lines.len() == 1 { . 0 . } else { -- line 1397 ---------------------------------------- -- line 1399 ---------------------------------------- . .array_windows() . .map(|&[fst, snd]| snd - fst) . .map(|bp| bp.to_usize()) . .max() . .unwrap() . }; . . let bytes_per_diff: u8 = match max_line_length { 4 ( 0.00%) 0..=0xFF => 1, . 0x100..=0xFFFF => 2, . _ => 4, . }; . . // Encode the number of bytes used per diff. . bytes_per_diff.encode(s)?; . . // Encode the first element. . lines[0].encode(s)?; . . let diff_iter = lines.array_windows().map(|&[fst, snd]| snd - fst); . 4 ( 0.00%) match bytes_per_diff { . 1 => { . for diff in diff_iter { . (diff.0 as u8).encode(s)? . } . } . 2 => { . for diff in diff_iter { . (diff.0 as u16).encode(s)? -- line 1428 ---------------------------------------- -- line 1436 ---------------------------------------- . _ => unreachable!(), . } . } . . Ok(()) . })?; . s.emit_struct_field("multibyte_chars", false, |s| self.multibyte_chars.encode(s))?; . s.emit_struct_field("non_narrow_chars", false, |s| self.non_narrow_chars.encode(s))?; 6 ( 0.00%) s.emit_struct_field("name_hash", false, |s| self.name_hash.encode(s))?; . s.emit_struct_field("normalized_pos", false, |s| self.normalized_pos.encode(s))?; 22 ( 0.00%) s.emit_struct_field("cnum", false, |s| self.cnum.encode(s)) . }) . } . } . . impl Decodable for SourceFile { 2,817 ( 0.00%) fn decode(d: &mut D) -> SourceFile { . d.read_struct(|d| { . let name: FileName = d.read_struct_field("name", |d| Decodable::decode(d)); . let src_hash: SourceFileHash = . d.read_struct_field("src_hash", |d| Decodable::decode(d)); . let start_pos: BytePos = d.read_struct_field("start_pos", |d| Decodable::decode(d)); . let end_pos: BytePos = d.read_struct_field("end_pos", |d| Decodable::decode(d)); . let lines: Vec = d.read_struct_field("lines", |d| { . let num_lines: u32 = Decodable::decode(d); 313 ( 0.00%) let mut lines = Vec::with_capacity(num_lines as usize); . . if num_lines > 0 { . // Read the number of bytes used per diff. . let bytes_per_diff: u8 = Decodable::decode(d); . . // Read the first element. . let mut line_start: BytePos = Decodable::decode(d); . lines.push(line_start); . . for _ in 1..num_lines { 636,706 ( 0.32%) let diff = match bytes_per_diff { . 1 => d.read_u8() as u32, . 2 => d.read_u16() as u32, . 4 => d.read_u32(), . _ => unreachable!(), . }; . . line_start = line_start + BytePos(diff); . -- line 1480 ---------------------------------------- -- line 1483 ---------------------------------------- . } . . lines . }); . let multibyte_chars: Vec = . d.read_struct_field("multibyte_chars", |d| Decodable::decode(d)); . let non_narrow_chars: Vec = . d.read_struct_field("non_narrow_chars", |d| Decodable::decode(d)); 626 ( 0.00%) let name_hash: u128 = d.read_struct_field("name_hash", |d| Decodable::decode(d)); . let normalized_pos: Vec = . d.read_struct_field("normalized_pos", |d| Decodable::decode(d)); . let cnum: CrateNum = d.read_struct_field("cnum", |d| Decodable::decode(d)); 3,443 ( 0.00%) SourceFile { 2,504 ( 0.00%) name, . start_pos, . end_pos, . src: None, 1,252 ( 0.00%) src_hash, . // Unused - the metadata decoder will construct . // a new SourceFile, filling in `external_src` properly . external_src: Lock::new(ExternalSource::Unneeded), 1,252 ( 0.00%) lines, 1,252 ( 0.00%) multibyte_chars, 1,252 ( 0.00%) non_narrow_chars, 1,252 ( 0.00%) normalized_pos, . name_hash, . cnum, . } . }) 2,817 ( 0.00%) } . } . . impl fmt::Debug for SourceFile { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(fmt, "SourceFile({:?})", self.name) . } . } . . impl SourceFile { 33 ( 0.00%) pub fn new( . name: FileName, . mut src: String, . start_pos: BytePos, . hash_kind: SourceFileHashAlgorithm, . ) -> Self { . // Compute the file hash before any normalization. . let src_hash = SourceFileHash::new(hash_kind, &src); 9 ( 0.00%) let normalized_pos = normalize_src(&mut src, start_pos); . . let name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 6 ( 0.00%) name.hash(&mut hasher); . hasher.finish::() . }; 6 ( 0.00%) let end_pos = start_pos.to_usize() + src.len(); 9 ( 0.00%) assert!(end_pos <= u32::MAX as usize); . 36 ( 0.00%) let (lines, multibyte_chars, non_narrow_chars) = 6 ( 0.00%) analyze_source_file::analyze_source_file(&src, start_pos); . 51 ( 0.00%) SourceFile { . name, . src: Some(Lrc::new(src)), 33 ( 0.00%) src_hash, . external_src: Lock::new(ExternalSource::Unneeded), . start_pos, . end_pos: Pos::from_usize(end_pos), 12 ( 0.00%) lines, 12 ( 0.00%) multibyte_chars, 12 ( 0.00%) non_narrow_chars, 12 ( 0.00%) normalized_pos, . name_hash, . cnum: LOCAL_CRATE, . } 27 ( 0.00%) } . . /// Returns the `BytePos` of the beginning of the current line. . pub fn line_begin_pos(&self, pos: BytePos) -> BytePos { . let line_index = self.lookup_line(pos).unwrap(); . self.lines[line_index] . } . . /// Add externally loaded source. . /// If the hash of the input doesn't match or no input is supplied via None, . /// it is interpreted as an error and the corresponding enum variant is set. . /// The return value signifies whether some kind of source is present. 56 ( 0.00%) pub fn add_external_src(&self, get_src: F) -> bool . where . F: FnOnce() -> Option, . { 8 ( 0.00%) if matches!( 16 ( 0.00%) *self.external_src.borrow(), . ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. } . ) { . let src = get_src(); . let mut external_src = self.external_src.borrow_mut(); . // Check that no-one else have provided the source while we were getting it . if let ExternalSource::Foreign { . kind: src_kind @ ExternalSourceKind::AbsentOk, .. . } = &mut *external_src -- line 1582 ---------------------------------------- -- line 1592 ---------------------------------------- . *src_kind = ExternalSourceKind::AbsentErr; . } . . false . } else { . self.src.is_some() || external_src.get_source().is_some() . } . } else { 8 ( 0.00%) self.src.is_some() || self.external_src.borrow().get_source().is_some() . } 72 ( 0.00%) } . . /// Gets a line from the list of pre-computed line-beginnings. . /// The line number here is 0-based. . pub fn get_line(&self, line_number: usize) -> Option> { . fn get_until_newline(src: &str, begin: usize) -> &str { . // We can't use `lines.get(line_number+1)` because we might . // be parsing when we call this function and thus the current . // line is the last one we have line info for. -- line 1610 ---------------------------------------- -- line 1627 ---------------------------------------- . Some(Cow::Owned(String::from(get_until_newline(src, begin)))) . } else { . None . } . } . . pub fn is_real_file(&self) -> bool { . self.name.is_real() 315 ( 0.00%) } . . pub fn is_imported(&self) -> bool { . self.src.is_none() 7,473 ( 0.00%) } . . pub fn count_lines(&self) -> usize { . self.lines.len() . } . . /// Finds the line containing the given position. The return value is the . /// index into the `lines` array of this `SourceFile`, not the 1-based line . /// number. If the source_file is empty or the position is located before the . /// first line, `None` is returned. . pub fn lookup_line(&self, pos: BytePos) -> Option { 389 ( 0.00%) match self.lines.binary_search(&pos) { . Ok(idx) => Some(idx), . Err(0) => None, . Err(idx) => Some(idx - 1), . } . } . . pub fn line_bounds(&self, line_index: usize) -> Range { 1,093 ( 0.00%) if self.is_empty() { . return self.start_pos..self.end_pos; . } . 858 ( 0.00%) assert!(line_index < self.lines.len()); 1,083 ( 0.00%) if line_index == (self.lines.len() - 1) { 7 ( 0.00%) self.lines[line_index]..self.end_pos . } else { 716 ( 0.00%) self.lines[line_index]..self.lines[line_index + 1] . } . } . . /// Returns whether or not the file contains the given `SourceMap` byte . /// position. The position one past the end of the file is considered to be . /// contained by the file. This implies that files for which `is_empty` . /// returns true still contain one byte position according to this function. . #[inline] -- line 1674 ---------------------------------------- -- line 1692 ---------------------------------------- . Err(i) if i == 0 => 0, . Err(i) => self.normalized_pos[i - 1].diff, . }; . . BytePos::from_u32(pos.0 - self.start_pos.0 + diff) . } . . /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`. 2 ( 0.00%) pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos { . // The number of extra bytes due to multibyte chars in the `SourceFile`. . let mut total_extra_bytes = 0; . 6 ( 0.00%) for mbc in self.multibyte_chars.iter() { . debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos); 4 ( 0.00%) if mbc.pos < bpos { . // Every character is at least one byte, so we only . // count the actual extra bytes. . total_extra_bytes += mbc.bytes as u32 - 1; . // We should never see a byte position in the middle of a . // character. . assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32); . } else { . break; . } . } . 12 ( 0.00%) assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32()); 10 ( 0.00%) CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize) 4 ( 0.00%) } . . /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a . /// given `BytePos`. 7 ( 0.00%) pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) { 2 ( 0.00%) let chpos = self.bytepos_to_file_charpos(pos); . match self.lookup_line(pos) { . Some(a) => { . let line = a + 1; // Line numbers start at 1 1 ( 0.00%) let linebpos = self.lines[a]; 2 ( 0.00%) let linechpos = self.bytepos_to_file_charpos(linebpos); . let col = chpos - linechpos; . debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos); . debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos); . debug!("byte is on line: {}", line); 1 ( 0.00%) assert!(chpos >= linechpos); . (line, col) . } . None => (0, chpos), . } 8 ( 0.00%) } . . /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based) . /// column offset when displayed, for a given `BytePos`. 8 ( 0.00%) pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) { 3 ( 0.00%) let (line, col_or_chpos) = self.lookup_file_pos(pos); 2 ( 0.00%) if line > 0 { . let col = col_or_chpos; 1 ( 0.00%) let linebpos = self.lines[line - 1]; . let col_display = { . let start_width_idx = self . .non_narrow_chars . .binary_search_by_key(&linebpos, |x| x.pos()) . .unwrap_or_else(|x| x); . let end_width_idx = self . .non_narrow_chars . .binary_search_by_key(&pos, |x| x.pos()) . .unwrap_or_else(|x| x); 3 ( 0.00%) let special_chars = end_width_idx - start_width_idx; . let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx] . .iter() . .map(|x| x.width()) . .sum(); 5 ( 0.00%) col.0 - special_chars + non_narrow . }; . (line, col, col_display) . } else { . let chpos = col_or_chpos; . let col_display = { . let end_width_idx = self . .non_narrow_chars . .binary_search_by_key(&pos, |x| x.pos()) . .unwrap_or_else(|x| x); . let non_narrow: usize = . self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum(); . chpos.0 - end_width_idx + non_narrow . }; . (0, chpos, col_display) . } 7 ( 0.00%) } . } . . /// Normalizes the source code and records the normalizations. 30 ( 0.00%) fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec { . let mut normalized_pos = vec![]; . remove_bom(src, &mut normalized_pos); . normalize_newlines(src, &mut normalized_pos); . . // Offset all the positions by start_pos to match the final file positions. . for np in &mut normalized_pos { . np.pos.0 += start_pos.0; . } . . normalized_pos 27 ( 0.00%) } . . /// Removes UTF-8 BOM, if any. . fn remove_bom(src: &mut String, normalized_pos: &mut Vec) { 3 ( 0.00%) if src.starts_with('\u{feff}') { . src.drain(..3); . normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 }); . } . } . . /// Replaces `\r\n` with `\n` in-place in `src`. . /// . /// Returns error if there's a lone `\r` in the string. . fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec) { 3 ( 0.00%) if !src.as_bytes().contains(&b'\r') { . return; . } . . // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding. . // While we *can* call `as_mut_vec` and do surgery on the live string . // directly, let's rather steal the contents of `src`. This makes the code . // safe even if a panic occurs. . -- line 1816 ---------------------------------------- -- line 1877 ---------------------------------------- . ( . $( . $(#[$attr:meta])* . $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty); . )* . ) => { . $( . $(#[$attr])* 9,146 ( 0.00%) $vis struct $ident($inner_vis $inner_ty); . . impl Pos for $ident { . #[inline(always)] . fn from_usize(n: usize) -> $ident { 373 ( 0.00%) $ident(n as $inner_ty) . } . . #[inline(always)] . fn to_usize(&self) -> usize { 22,032 ( 0.01%) self.0 as usize . } . . #[inline(always)] . fn from_u32(n: u32) -> $ident { . $ident(n as $inner_ty) . } . . #[inline(always)] -- line 1903 ---------------------------------------- -- line 1906 ---------------------------------------- . } . } . . impl Add for $ident { . type Output = $ident; . . #[inline(always)] . fn add(self, rhs: $ident) -> $ident { 1,003,527 ( 0.51%) $ident(self.0 + rhs.0) . } . } . . impl Sub for $ident { . type Output = $ident; . . #[inline(always)] . fn sub(self, rhs: $ident) -> $ident { 623,610 ( 0.32%) $ident(self.0 - rhs.0) . } . } . )* . }; . } . . impl_pos! { . /// A byte offset. -- line 1931 ---------------------------------------- -- line 1939 ---------------------------------------- . /// Because of multibyte UTF-8 characters, a byte offset . /// is not equivalent to a character offset. The [`SourceMap`] will convert [`BytePos`] . /// values to `CharPos` values as necessary. . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] . pub struct CharPos(pub usize); . } . . impl Encodable for BytePos { 50 ( 0.00%) fn encode(&self, s: &mut S) -> Result<(), S::Error> { . s.emit_u32(self.0) 60 ( 0.00%) } . } . . impl Decodable for BytePos { . fn decode(d: &mut D) -> BytePos { 17,738 ( 0.01%) BytePos(d.read_u32()) . } . } . . // _____________________________________________________________________________ . // Loc, SourceFileAndLine, SourceFileAndBytePos . // . . /// A source code location used for error reporting. -- line 1962 ---------------------------------------- -- line 2079 ---------------------------------------- . /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column) . /// triple, which stays the same even if the containing `SourceFile` has moved . /// within the `SourceMap`. . /// . /// Also note that we are hashing byte offsets for the column, not unicode . /// codepoint offsets. For the purpose of the hash that's sufficient. . /// Also, hashing filenames is expensive so we avoid doing it twice when the . /// span starts and ends in the same file, which is almost always the case. 49,063 ( 0.02%) fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { . const TAG_VALID_SPAN: u8 = 0; . const TAG_INVALID_SPAN: u8 = 1; . const TAG_RELATIVE_SPAN: u8 = 2; . 7,551 ( 0.00%) if !ctx.hash_spans() { . return; . } . 41,512 ( 0.02%) let span = self.data_untracked(); 19,401 ( 0.01%) span.ctxt.hash_stable(ctx, hasher); 21,027 ( 0.01%) span.parent.hash_stable(ctx, hasher); . 14,064 ( 0.01%) if span.is_dummy() { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . 13,926 ( 0.01%) if let Some(parent) = span.parent { . let def_span = ctx.def_span(parent).data_untracked(); . if def_span.contains(span) { . // This span is enclosed in a definition: only hash the relative position. . Hash::hash(&TAG_RELATIVE_SPAN, hasher); . (span.lo - def_span.lo).to_u32().hash_stable(ctx, hasher); . (span.hi - def_span.lo).to_u32().hash_stable(ctx, hasher); . return; . } . } . . // If this is not an empty or invalid span, we want to hash the last . // position that belongs to it, as opposed to hashing the first . // position past it. 27,852 ( 0.01%) let (file, line_lo, col_lo, line_hi, col_hi) = match ctx.span_data_to_lines_and_cols(&span) . { 13,926 ( 0.01%) Some(pos) => pos, . None => { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . }; . . Hash::hash(&TAG_VALID_SPAN, hasher); . // We truncate the stable ID hash and line and column numbers. The chances -- line 2129 ---------------------------------------- -- line 2134 ---------------------------------------- . // hash only the length, for example, then two otherwise equal spans with . // different end locations will have the same hash. This can cause a problem . // during incremental compilation wherein a previous result for a query that . // depends on the end location of a span will be incorrectly reused when the . // end location of the span it depends on has changed (see issue #74890). A . // similar analysis applies if some query depends specifically on the length . // of the span, but we only hash the end location. So hash both. . 6,963 ( 0.00%) let col_lo_trunc = (col_lo.0 as u64) & 0xFF; . let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8; . let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32; . let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40; . let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc; 6,963 ( 0.00%) let len = (span.hi - span.lo).0; . Hash::hash(&col_line, hasher); . Hash::hash(&len, hasher); 56,072 ( 0.03%) } . } 845,453 ( 0.43%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/source_map.rs -------------------------------------------------------------------------------- Ir -- line 72 ---------------------------------------- . fn deref(&self) -> &Self::Target { . &self.0 . } . } . . impl !DerefMut for MonotonicVec {} . } . 3,118 ( 0.00%) #[derive(Clone, Encodable, Decodable, Debug, Copy, HashStable_Generic)] . pub struct Spanned { . pub node: T, . pub span: Span, . } . . pub fn respan(sp: Span, t: T) -> Spanned { 26,227 ( 0.01%) Spanned { node: t, span: sp } 95 ( 0.00%) } . . pub fn dummy_spanned(t: T) -> Spanned { . respan(DUMMY_SP, t) . } . . // _____________________________________________________________________________ . // SourceFile, MultiByteChar, FileName, FileLines . // -- line 96 ---------------------------------------- -- line 103 ---------------------------------------- . /// Read the contents of a UTF-8 file into memory. . fn read_file(&self, path: &Path) -> io::Result; . } . . /// A FileLoader that uses std::fs to load real files. . pub struct RealFileLoader; . . impl FileLoader for RealFileLoader { 16 ( 0.00%) fn file_exists(&self, path: &Path) -> bool { . path.exists() 16 ( 0.00%) } . 4 ( 0.00%) fn read_file(&self, path: &Path) -> io::Result { . fs::read_to_string(path) 6 ( 0.00%) } . } . . /// This is a [SourceFile] identifier that is used to correlate source files between . /// subsequent compilation sessions (which is something we need to do during . /// incremental compilation). . /// . /// The [StableSourceFileId] also contains the CrateNum of the crate the source . /// file was originally parsed for. This way we get two separate entries in -- line 125 ---------------------------------------- -- line 128 ---------------------------------------- . /// at the point where we discover that there's a local use of the file in . /// addition to the upstream one, we might already have made decisions based on . /// the assumption that it's an upstream file. Treating the two files as . /// different has no real downsides. . #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)] . pub struct StableSourceFileId { . // A hash of the source file's FileName. This is hash so that it's size . // is more predictable than if we included the actual FileName value. 30 ( 0.00%) pub file_name_hash: u64, . . // The CrateNum of the crate this source file was originally parsed for. . // We cannot include this information in the hash because at the time . // of hashing we don't have the context to map from the CrateNum's numeric . // value to a StableCrateId. . pub cnum: CrateNum, . } . . // FIXME: we need a more globally consistent approach to the problem solved by . // StableSourceFileId, perhaps built atop source_file.name_hash. . impl StableSourceFileId { . pub fn new(source_file: &SourceFile) -> StableSourceFileId { 626 ( 0.00%) StableSourceFileId::new_from_name(&source_file.name, source_file.cnum) . } . 1,580 ( 0.00%) fn new_from_name(name: &FileName, cnum: CrateNum) -> StableSourceFileId { . let mut hasher = StableHasher::new(); 316 ( 0.00%) name.hash(&mut hasher); . StableSourceFileId { file_name_hash: hasher.finish(), cnum } 1,896 ( 0.00%) } . } . . // _____________________________________________________________________________ . // SourceMap . // . . #[derive(Default)] . pub(super) struct SourceMapFiles { -- line 164 ---------------------------------------- -- line 176 ---------------------------------------- . // `--remap-path-prefix` to all `SourceFile`s allocated within this `SourceMap`. . path_mapping: FilePathMapping, . . /// The algorithm used for hashing the contents of each source file. . hash_kind: SourceFileHashAlgorithm, . } . . impl SourceMap { 1 ( 0.00%) pub fn new(path_mapping: FilePathMapping) -> SourceMap { . Self::with_file_loader_and_hash_kind( . Box::new(RealFileLoader), 4 ( 0.00%) path_mapping, . SourceFileHashAlgorithm::Md5, . ) 1 ( 0.00%) } . 1 ( 0.00%) pub fn with_file_loader_and_hash_kind( . file_loader: Box, . path_mapping: FilePathMapping, . hash_kind: SourceFileHashAlgorithm, . ) -> SourceMap { 11 ( 0.00%) SourceMap { . used_address_space: AtomicU32::new(0), . files: Default::default(), . file_loader, 4 ( 0.00%) path_mapping, . hash_kind, . } 1 ( 0.00%) } . . pub fn path_mapping(&self) -> &FilePathMapping { 6 ( 0.00%) &self.path_mapping 6 ( 0.00%) } . . pub fn file_exists(&self, path: &Path) -> bool { 20 ( 0.00%) self.file_loader.file_exists(path) . } . 22 ( 0.00%) pub fn load_file(&self, path: &Path) -> io::Result> { 8 ( 0.00%) let src = self.file_loader.read_file(path)?; . let filename = path.to_owned().into(); 36 ( 0.00%) Ok(self.new_source_file(filename, src)) 18 ( 0.00%) } . . /// Loads source file as a binary blob. . /// . /// Unlike `load_file`, guarantees that no normalization like BOM-removal . /// takes place. . pub fn load_binary_file(&self, path: &Path) -> io::Result> { . // Ideally, this should use `self.file_loader`, but it can't . // deal with binary files yet. -- line 226 ---------------------------------------- -- line 233 ---------------------------------------- . // empty string. . let text = std::str::from_utf8(&bytes).unwrap_or("").to_string(); . self.new_source_file(path.to_owned().into(), text); . Ok(bytes) . } . . // By returning a `MonotonicVec`, we ensure that consumers cannot invalidate . // any existing indices pointing into `files`. 11 ( 0.00%) pub fn files(&self) -> MappedReadGuard<'_, monotonic::MonotonicVec>> { . ReadGuard::map(self.files.borrow(), |files| &files.source_files) 33 ( 0.00%) } . 12 ( 0.00%) pub fn source_file_by_stable_id( . &self, . stable_id: StableSourceFileId, . ) -> Option> { . self.files.borrow().stable_id_to_source_file.get(&stable_id).cloned() 15 ( 0.00%) } . . fn allocate_address_space(&self, size: usize) -> Result { 316 ( 0.00%) let size = u32::try_from(size).map_err(|_| OffsetOverflowError)?; . . loop { 316 ( 0.00%) let current = self.used_address_space.load(Ordering::Relaxed); 948 ( 0.00%) let next = current . .checked_add(size) . // Add one so there is some space between files. This lets us distinguish . // positions in the `SourceMap`, even in the presence of zero-length files. . .and_then(|next| next.checked_add(1)) . .ok_or(OffsetOverflowError)?; . . if self . .used_address_space -- line 265 ---------------------------------------- -- line 269 ---------------------------------------- . return Ok(usize::try_from(current).unwrap()); . } . } . } . . /// Creates a new `SourceFile`. . /// If a file already exists in the `SourceMap` with the same ID, that file is returned . /// unmodified. 24 ( 0.00%) pub fn new_source_file(&self, filename: FileName, src: String) -> Lrc { 36 ( 0.00%) self.try_new_source_file(filename, src).unwrap_or_else(|OffsetOverflowError| { . eprintln!("fatal error: rustc does not support files larger than 4GB"); . crate::fatal_error::FatalError.raise() . }) 27 ( 0.00%) } . . fn try_new_source_file( . &self, . filename: FileName, . src: String, . ) -> Result, OffsetOverflowError> { . // Note that filename may not be a valid path, eg it may be `` etc, . // but this is okay because the directory determined by `path.pop()` will . // be empty, so the working directory will be used. 39 ( 0.00%) let (filename, _) = self.path_mapping.map_filename_prefix(&filename); . 6 ( 0.00%) let file_id = StableSourceFileId::new_from_name(&filename, LOCAL_CRATE); . 18 ( 0.00%) let lrc_sf = match self.source_file_by_stable_id(file_id) { . Some(lrc_sf) => lrc_sf, . None => { . let start_pos = self.allocate_address_space(src.len())?; . 18 ( 0.00%) let source_file = Lrc::new(SourceFile::new( 27 ( 0.00%) filename, 9 ( 0.00%) src, . Pos::from_usize(start_pos), . self.hash_kind, . )); . . // Let's make sure the file_id we generated above actually matches . // the ID we generate for the SourceFile we just created. . debug_assert_eq!(StableSourceFileId::new(&source_file), file_id); . -- line 311 ---------------------------------------- -- line 319 ---------------------------------------- . }; . Ok(lrc_sf) . } . . /// Allocates a new `SourceFile` representing a source file from an external . /// crate. The source code of such an "imported `SourceFile`" is not available, . /// but we still know enough to generate accurate debuginfo location . /// information for things inlined from other crates. 2,504 ( 0.00%) pub fn new_imported_source_file( . &self, . filename: FileName, . src_hash: SourceFileHash, . name_hash: u128, . source_len: usize, . cnum: CrateNum, . mut file_local_lines: Vec, . mut file_local_multibyte_chars: Vec, -- line 335 ---------------------------------------- -- line 341 ---------------------------------------- . let start_pos = self . .allocate_address_space(source_len) . .expect("not enough address space for imported source file"); . . let end_pos = Pos::from_usize(start_pos + source_len); . let start_pos = Pos::from_usize(start_pos); . . for pos in &mut file_local_lines { 238,468 ( 0.12%) *pos = *pos + start_pos; . } . . for mbc in &mut file_local_multibyte_chars { 568 ( 0.00%) mbc.pos = mbc.pos + start_pos; . } . . for swc in &mut file_local_non_narrow_chars { 536 ( 0.00%) *swc = *swc + start_pos; . } . . for nc in &mut file_local_normalized_pos { . nc.pos = nc.pos + start_pos; . } . 939 ( 0.00%) let source_file = Lrc::new(SourceFile { 2,504 ( 0.00%) name: filename, . src: None, . src_hash, . external_src: Lock::new(ExternalSource::Foreign { . kind: ExternalSourceKind::AbsentOk, . original_start_pos, . original_end_pos, . }), . start_pos, -- line 373 ---------------------------------------- -- line 383 ---------------------------------------- . let mut files = self.files.borrow_mut(); . . files.source_files.push(source_file.clone()); . files . .stable_id_to_source_file . .insert(StableSourceFileId::new(&source_file), source_file.clone()); . . source_file 2,817 ( 0.00%) } . . // If there is a doctest offset, applies it to the line. . pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize { . match file { . FileName::DocTest(_, offset) => { . if *offset < 0 { . orig - (-(*offset)) as usize . } else { -- line 399 ---------------------------------------- -- line 400 ---------------------------------------- . orig + *offset as usize . } . } . _ => orig, . } . } . . /// Return the SourceFile that contains the given `BytePos` 3 ( 0.00%) pub fn lookup_source_file(&self, pos: BytePos) -> Lrc { 1 ( 0.00%) let idx = self.lookup_source_file_idx(pos); 1 ( 0.00%) (*self.files.borrow().source_files)[idx].clone() 3 ( 0.00%) } . . /// Looks up source information about a `BytePos`. . pub fn lookup_char_pos(&self, pos: BytePos) -> Loc { 5 ( 0.00%) let sf = self.lookup_source_file(pos); 6 ( 0.00%) let (line, col, col_display) = sf.lookup_file_pos_with_col_display(pos); 3 ( 0.00%) Loc { file: sf, line, col, col_display } . } . . // If the corresponding `SourceFile` is empty, does not return a line number. . pub fn lookup_line(&self, pos: BytePos) -> Result> { . let f = self.lookup_source_file(pos); . . match f.lookup_line(pos) { . Some(line) => Ok(SourceFileAndLine { sf: f, line }), -- line 425 ---------------------------------------- -- line 451 ---------------------------------------- . . /// Format the span location to be printed in diagnostics. Must not be emitted . /// to build artifacts as this may leak local file paths. Use span_to_embeddable_string . /// for string suitable for embedding. . pub fn span_to_diagnostic_string(&self, sp: Span) -> String { . self.span_to_string(sp, self.path_mapping.filename_display_for_diagnostics) . } . 11 ( 0.00%) pub fn span_to_filename(&self, sp: Span) -> FileName { 3 ( 0.00%) self.lookup_char_pos(sp.lo()).file.name.clone() 8 ( 0.00%) } . . pub fn filename_for_diagnostics<'a>(&self, filename: &'a FileName) -> FileNameDisplay<'a> { . filename.display(self.path_mapping.filename_display_for_diagnostics) . } . 55 ( 0.00%) pub fn is_multiline(&self, sp: Span) -> bool { 20 ( 0.00%) let lo = self.lookup_source_file_idx(sp.lo()); 20 ( 0.00%) let hi = self.lookup_source_file_idx(sp.hi()); 10 ( 0.00%) if lo != hi { . return true; . } 10 ( 0.00%) let f = (*self.files.borrow().source_files)[lo].clone(); . f.lookup_line(sp.lo()) != f.lookup_line(sp.hi()) 45 ( 0.00%) } . . #[instrument(skip(self), level = "trace")] . pub fn is_valid_span(&self, sp: Span) -> Result<(Loc, Loc), SpanLinesError> { . let lo = self.lookup_char_pos(sp.lo()); . trace!(?lo); . let hi = self.lookup_char_pos(sp.hi()); . trace!(?hi); . if lo.file.start_pos != hi.file.start_pos { -- line 483 ---------------------------------------- -- line 533 ---------------------------------------- . . /// Extracts the source surrounding the given `Span` using the `extract_source` function. The . /// extract function takes three arguments: a string slice containing the source, an index in . /// the slice for the beginning of the span and an index in the slice for the end of the span. . fn span_to_source(&self, sp: Span, extract_source: F) -> Result . where . F: Fn(&str, usize, usize) -> Result, . { 56 ( 0.00%) let local_begin = self.lookup_byte_offset(sp.lo()); 56 ( 0.00%) let local_end = self.lookup_byte_offset(sp.hi()); . 16 ( 0.00%) if local_begin.sf.start_pos != local_end.sf.start_pos { . Err(SpanSnippetError::DistinctSources(DistinctSources { . begin: (local_begin.sf.name.clone(), local_begin.sf.start_pos), . end: (local_end.sf.name.clone(), local_end.sf.start_pos), . })) . } else { . self.ensure_source_file_source_present(local_begin.sf.clone()); . . let start_index = local_begin.pos.to_usize(); . let end_index = local_end.pos.to_usize(); 8 ( 0.00%) let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize(); . 32 ( 0.00%) if start_index > end_index || end_index > source_len { . return Err(SpanSnippetError::MalformedForSourcemap(MalformedSourceMapPositions { . name: local_begin.sf.name.clone(), . source_len, . begin_pos: local_begin.pos, . end_pos: local_end.pos, . })); . } . 24 ( 0.00%) if let Some(ref src) = local_begin.sf.src { . extract_source(src, start_index, end_index) . } else if let Some(src) = local_begin.sf.external_src.borrow().get_source() { . extract_source(src, start_index, end_index) . } else { . Err(SpanSnippetError::SourceNotAvailable { filename: local_begin.sf.name.clone() }) . } . } . } -- line 573 ---------------------------------------- -- line 579 ---------------------------------------- . pub fn is_local_span(&self, sp: Span) -> bool { . let local_begin = self.lookup_byte_offset(sp.lo()); . let local_end = self.lookup_byte_offset(sp.hi()); . // This might be a weird span that covers multiple files . local_begin.sf.src.is_some() && local_end.sf.src.is_some() . } . . /// Returns the source snippet as `String` corresponding to the given `Span`. 96 ( 0.00%) pub fn span_to_snippet(&self, sp: Span) -> Result { . self.span_to_source(sp, |src, start_index, end_index| { . src.get(start_index..end_index) . .map(|s| s.to_string()) . .ok_or(SpanSnippetError::IllFormedSpan(sp)) . }) 72 ( 0.00%) } . . pub fn span_to_margin(&self, sp: Span) -> Option { . Some(self.indentation_before(sp)?.len()) . } . . pub fn indentation_before(&self, sp: Span) -> Option { . self.span_to_source(sp, |src, start_index, _| { . let before = &src[..start_index]; -- line 601 ---------------------------------------- -- line 679 ---------------------------------------- . } . } . . sp . } . . /// Given a `Span`, tries to get a shorter span ending before the first occurrence of `char` . /// `c`. 88 ( 0.00%) pub fn span_until_char(&self, sp: Span, c: char) -> Span { 32 ( 0.00%) match self.span_to_snippet(sp) { 32 ( 0.00%) Ok(snippet) => { . let snippet = snippet.split(c).next().unwrap_or("").trim_end(); 16 ( 0.00%) if !snippet.is_empty() && !snippet.contains('\n') { 40 ( 0.00%) sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32)) . } else { . sp . } . } . _ => sp, . } 72 ( 0.00%) } . . /// Given a `Span`, tries to get a shorter span ending just after the first occurrence of `char` . /// `c`. . pub fn span_through_char(&self, sp: Span, c: char) -> Span { . if let Ok(snippet) = self.span_to_snippet(sp) { . if let Some(offset) = snippet.find(c) { . return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32)); . } -- line 707 ---------------------------------------- -- line 750 ---------------------------------------- . /// Given a `Span`, return a span ending in the closest `{`. This is useful when you have a . /// `Span` enclosing a whole item but we need to point at only the head (usually the first . /// line) of that item. . /// . /// *Only suitable for diagnostics.* . pub fn guess_head_span(&self, sp: Span) -> Span { . // FIXME: extend the AST items to have a head span, or replace callers with pointing at . // the item's ident when appropriate. 16 ( 0.00%) self.span_until_char(sp, '{') . } . . /// Returns a new span representing just the first character of the given span. . pub fn start_point(&self, sp: Span) -> Span { . let width = { . let sp = sp.data(); . let local_begin = self.lookup_byte_offset(sp.lo); . let start_index = local_begin.pos.to_usize(); -- line 766 ---------------------------------------- -- line 782 ---------------------------------------- . }, . } . }; . . sp.with_hi(BytePos(sp.lo().0 + width as u32)) . } . . /// Returns a new span representing just the last character of this span. 8,460 ( 0.00%) pub fn end_point(&self, sp: Span) -> Span { . let pos = sp.hi().0; . 2,820 ( 0.00%) let width = self.find_width_of_character_at_span(sp, false); . let corrected_end_position = pos.checked_sub(width).unwrap_or(pos); . . let end_point = BytePos(cmp::max(corrected_end_position, sp.lo().0)); 7,050 ( 0.00%) sp.with_lo(end_point) . } . . /// Returns a new span representing the next character after the end-point of this span. 66 ( 0.00%) pub fn next_point(&self, sp: Span) -> Span { 6 ( 0.00%) if sp.is_dummy() { . return sp; . } . let start_of_next_point = sp.hi().0; . 24 ( 0.00%) let width = self.find_width_of_character_at_span(sp.shrink_to_hi(), true); . // If the width is 1, then the next span should point to the same `lo` and `hi`. However, . // in the case of a multibyte character, where the width != 1, the next span should . // span multiple bytes to include the whole character. . let end_of_next_point = 12 ( 0.00%) start_of_next_point.checked_add(width - 1).unwrap_or(start_of_next_point); . 12 ( 0.00%) let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point)); . Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt(), None) 54 ( 0.00%) } . . /// Finds the width of the character, either before or after the end of provided span, . /// depending on the `forwards` parameter. 8,532 ( 0.00%) fn find_width_of_character_at_span(&self, sp: Span, forwards: bool) -> u32 { . let sp = sp.data(); 711 ( 0.00%) if sp.lo == sp.hi { . debug!("find_width_of_character_at_span: early return empty span"); . return 1; . } . 4,935 ( 0.00%) let local_begin = self.lookup_byte_offset(sp.lo); 6,345 ( 0.00%) let local_end = self.lookup_byte_offset(sp.hi); . debug!( . "find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`", . local_begin, local_end . ); . 1,410 ( 0.00%) if local_begin.sf.start_pos != local_end.sf.start_pos { . debug!("find_width_of_character_at_span: begin and end are in different files"); . return 1; . } . . let start_index = local_begin.pos.to_usize(); . let end_index = local_end.pos.to_usize(); . debug!( . "find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`", . start_index, end_index . ); . . // Disregard indexes that are at the start or end of their spans, they can't fit bigger . // characters. 2,820 ( 0.00%) if (!forwards && end_index == usize::MIN) || (forwards && start_index == usize::MAX) { . debug!("find_width_of_character_at_span: start or end of span, cannot be multibyte"); . return 1; . } . 705 ( 0.00%) let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize(); . debug!("find_width_of_character_at_span: source_len=`{:?}`", source_len); . // Ensure indexes are also not malformed. 2,820 ( 0.00%) if start_index > end_index || end_index > source_len { . debug!("find_width_of_character_at_span: source indexes are malformed"); . return 1; . } . . let src = local_begin.sf.external_src.borrow(); . . // We need to extend the snippet to the end of the src rather than to end_index so when . // searching forwards for boundaries we've got somewhere to search. 2,115 ( 0.00%) let snippet = if let Some(ref src) = local_begin.sf.src { . &src[start_index..] . } else if let Some(src) = src.get_source() { . &src[start_index..] . } else { . return 1; . }; . debug!("find_width_of_character_at_span: snippet=`{:?}`", snippet); . 4,230 ( 0.00%) let mut target = if forwards { end_index + 1 } else { end_index - 1 }; . debug!("find_width_of_character_at_span: initial target=`{:?}`", target); . 2,820 ( 0.00%) while !snippet.is_char_boundary(target - start_index) && target < source_len { . target = if forwards { . target + 1 . } else { . match target.checked_sub(1) { . Some(target) => target, . None => { . break; . } . } . }; . debug!("find_width_of_character_at_span: target=`{:?}`", target); . } . debug!("find_width_of_character_at_span: final target=`{:?}`", target); . 2,820 ( 0.00%) if forwards { (target - end_index) as u32 } else { (end_index - target) as u32 } 6,399 ( 0.00%) } . . pub fn get_source_file(&self, filename: &FileName) -> Option> { . // Remap filename before lookup . let filename = self.path_mapping().map_filename_prefix(filename).0; . for sf in self.files.borrow().source_files.iter() { . if filename == sf.name { . return Some(sf.clone()); . } . } . None . } . . /// For a global `BytePos`, computes the local offset within the containing `SourceFile`. 7,130 ( 0.00%) pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos { 1,426 ( 0.00%) let idx = self.lookup_source_file_idx(bpos); 2,852 ( 0.00%) let sf = (*self.files.borrow().source_files)[idx].clone(); . let offset = bpos - sf.start_pos; . SourceFileAndBytePos { sf, pos: offset } 7,130 ( 0.00%) } . . // Returns the index of the `SourceFile` (in `self.files`) that contains `pos`. . // This index is guaranteed to be valid for the lifetime of this `SourceMap`, . // since `source_files` is a `MonotonicVec` 4,443 ( 0.00%) pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize { . self.files . .borrow() . .source_files . .binary_search_by_key(&pos, |key| key.start_pos) 2,962 ( 0.00%) .unwrap_or_else(|p| p - 1) 5,924 ( 0.00%) } . . pub fn count_lines(&self) -> usize { . self.files().iter().fold(0, |a, f| a + f.count_lines()) . } . . pub fn generate_fn_name_span(&self, span: Span) -> Option { . let prev_span = self.span_extend_to_prev_str(span, "fn", true); . if let Ok(snippet) = self.span_to_snippet(prev_span) { -- line 931 ---------------------------------------- -- line 1010 ---------------------------------------- . . return Some((sugg_span, new_snippet)); . } . } . . None . } . pub fn ensure_source_file_source_present(&self, source_file: Lrc) -> bool { 56 ( 0.00%) source_file.add_external_src(|| { . match source_file.name { . FileName::Real(ref name) if let Some(local_path) = name.local_path() => { . self.file_loader.read_file(local_path).ok() . } . _ => None, . } . }) . } -- line 1026 ---------------------------------------- -- line 1053 ---------------------------------------- . let span = span.shrink_to_hi().with_hi(BytePos(span.hi().0.checked_add(1)?)); . if self.span_to_snippet(span).as_deref() != Ok(";") { . return None; . } . Some(span) . } . } . 16 ( 0.00%) #[derive(Clone)] . pub struct FilePathMapping { 8 ( 0.00%) mapping: Vec<(PathBuf, PathBuf)>, 4 ( 0.00%) filename_display_for_diagnostics: FileNameDisplayPreference, . } . . impl FilePathMapping { 1 ( 0.00%) pub fn empty() -> FilePathMapping { . FilePathMapping::new(Vec::new()) 1 ( 0.00%) } . 3 ( 0.00%) pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping { . let filename_display_for_diagnostics = if mapping.is_empty() { . FileNameDisplayPreference::Local . } else { . FileNameDisplayPreference::Remapped . }; . 16 ( 0.00%) FilePathMapping { mapping, filename_display_for_diagnostics } 3 ( 0.00%) } . . /// Applies any path prefix substitution as defined by the mapping. . /// The return value is the remapped path and a boolean indicating whether . /// the path was affected by the mapping. 90 ( 0.00%) pub fn map_prefix(&self, path: PathBuf) -> (PathBuf, bool) { . // NOTE: We are iterating over the mapping entries from last to first . // because entries specified later on the command line should . // take precedence. . for &(ref from, ref to) in self.mapping.iter().rev() { . if let Ok(rest) = path.strip_prefix(from) { . return (to.join(rest), true); . } . } . 50 ( 0.00%) (path, false) 90 ( 0.00%) } . 24 ( 0.00%) fn map_filename_prefix(&self, file: &FileName) -> (FileName, bool) { 6 ( 0.00%) match file { 4 ( 0.00%) FileName::Real(realfile) if let RealFileName::LocalPath(local_path) = realfile => { 28 ( 0.00%) let (mapped_path, mapped) = self.map_prefix(local_path.to_path_buf()); 2 ( 0.00%) let realfile = if mapped { . RealFileName::Remapped { . local_path: Some(local_path.clone()), . virtual_name: mapped_path, . } . } else { . realfile.clone() . }; 20 ( 0.00%) (FileName::Real(realfile), mapped) 8 ( 0.00%) } . FileName::Real(_) => unreachable!("attempted to remap an already remapped filename"), 11 ( 0.00%) other => (other.clone(), false), . } 8 ( 0.00%) } . } 11,132 ( 0.01%) -------------------------------------------------------------------------------- -- 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) { 19 ( 0.00%) let old = self.replace(val); 52 ( 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. 7,069 ( 0.00%) 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 { 38,301 ( 0.02%) 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 { 2,241 ( 0.00%) RefCell { 2,962 ( 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. 76 ( 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] 127 ( 0.00%) pub fn borrow(&self) -> Ref<'_, T> { . self.try_borrow().expect("already mutably borrowed") 381 ( 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] 5,488 ( 0.00%) pub fn borrow_mut(&self) -> RefMut<'_, T> { . self.try_borrow_mut().expect("already borrowed") 16,464 ( 0.01%) } . . /// 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. 24 ( 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> { 60,906 ( 0.03%) let b = borrow.get().wrapping_add(1); 34,405 ( 0.02%) 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) { 32,200 ( 0.02%) let borrow = self.borrow.get(); . debug_assert!(is_reading(borrow)); 64,553 ( 0.03%) 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) { 250,512 ( 0.13%) let borrow = self.borrow.get(); . debug_assert!(is_writing(borrow)); 469,520 ( 0.24%) 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. 510,037 ( 0.26%) 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 { 12 ( 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! 193,825 ( 0.10%) 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 ---------------------------------------- 383,483 ( 0.19%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs -------------------------------------------------------------------------------- Ir -- line 8 ---------------------------------------- . }; . use rustc_ast_pretty::pprust::token_to_string; . use rustc_data_structures::fx::FxHashMap; . use rustc_errors::PResult; . use rustc_span::Span; . . impl<'a> StringReader<'a> { . pub(super) fn into_token_trees(self) -> (PResult<'a, TokenStream>, Vec) { 57 ( 0.00%) let mut tt_reader = TokenTreesReader { . string_reader: self, 3 ( 0.00%) token: Token::dummy(), . open_braces: Vec::new(), . unmatched_braces: Vec::new(), . matching_delim_spans: Vec::new(), . last_unclosed_found_span: None, . last_delim_empty_block_spans: FxHashMap::default(), . matching_block_spans: Vec::new(), . }; 3 ( 0.00%) let res = tt_reader.parse_all_token_trees(); 18 ( 0.00%) (res, tt_reader.unmatched_braces) . } . } . . struct TokenTreesReader<'a> { . string_reader: StringReader<'a>, . token: Token, . /// Stack of open delimiters and their spans. Used for error message. . open_braces: Vec<(token::DelimToken, Span)>, -- line 35 ---------------------------------------- -- line 43 ---------------------------------------- . last_delim_empty_block_spans: FxHashMap, . /// Collect the spans of braces (Open, Close). Used only . /// for detecting if blocks are empty and only braces. . matching_block_spans: Vec<(Span, Span)>, . } . . impl<'a> TokenTreesReader<'a> { . // Parse a stream of tokens into a list of `TokenTree`s, up to an `Eof`. 24 ( 0.00%) fn parse_all_token_trees(&mut self) -> PResult<'a, TokenStream> { . let mut buf = TokenStreamBuilder::default(); . . self.bump(); 268 ( 0.00%) while self.token != token::Eof { 1,048 ( 0.00%) buf.push(self.parse_token_tree()?); . } . . Ok(buf.into_token_stream()) 27 ( 0.00%) } . . // Parse a stream of tokens into a list of `TokenTree`s, up to a `CloseDelim`. . fn parse_token_trees_until_close_delim(&mut self) -> TokenStream { . let mut buf = TokenStreamBuilder::default(); . loop { 14,110 ( 0.01%) if let token::CloseDelim(..) = self.token.kind { . return buf.into_token_stream(); . } . 31,620 ( 0.02%) match self.parse_token_tree() { 56,916 ( 0.03%) Ok(tree) => buf.push(tree), . Err(mut e) => { . e.emit(); . return buf.into_token_stream(); . } . } . } . } . 58,095 ( 0.03%) fn parse_token_tree(&mut self) -> PResult<'a, TreeAndSpacing> { 12,910 ( 0.01%) let sm = self.string_reader.sess.source_map(); . 55,171 ( 0.03%) match self.token.kind { . token::Eof => { . let msg = "this file contains an unclosed delimiter"; . let mut err = . self.string_reader.sess.span_diagnostic.struct_span_err(self.token.span, msg); . for &(_, sp) in &self.open_braces { . err.span_label(sp, "unclosed delimiter"); . self.unmatched_braces.push(UnmatchedBrace { . expected_delim: token::DelimToken::Brace, -- line 91 ---------------------------------------- -- line 113 ---------------------------------------- . err.span_label( . *close_sp, . "...as it matches this but it has different indentation", . ); . } . } . Err(err) . } 731 ( 0.00%) token::OpenDelim(delim) => { . // The span for beginning of the delimited section 731 ( 0.00%) let pre_span = self.token.span; . . // Parse the open delimiter. 5,117 ( 0.00%) self.open_braces.push((delim, self.token.span)); . self.bump(); . . // Parse the token trees within the delimiters. . // We stop at any delimiter so we can try to recover if the user . // uses an incorrect delimiter. 731 ( 0.00%) let tts = self.parse_token_trees_until_close_delim(); . . // Expand to cover the entire delimited token tree 3,655 ( 0.00%) let delim_span = DelimSpan::from_pair(pre_span, self.token.span); . 1,462 ( 0.00%) match self.token.kind { . // Correct delimiter. 1,462 ( 0.00%) token::CloseDelim(d) if d == delim => { . let (open_brace, open_brace_span) = self.open_braces.pop().unwrap(); 1,462 ( 0.00%) let close_brace_span = self.token.span; . 2,193 ( 0.00%) if tts.is_empty() { 6 ( 0.00%) let empty_block_span = open_brace_span.to(close_brace_span); 8 ( 0.00%) if !sm.is_multiline(empty_block_span) { . // Only track if the block is in the form of `{}`, otherwise it is . // likely that it was written on purpose. . self.last_delim_empty_block_spans.insert(delim, empty_block_span); . } . } . . //only add braces 2,924 ( 0.00%) if let (DelimToken::Brace, DelimToken::Brace) = (open_brace, delim) { . self.matching_block_spans.push((open_brace_span, close_brace_span)); . } . 731 ( 0.00%) if self.open_braces.is_empty() { . // Clear up these spans to avoid suggesting them as we've found . // properly matched delimiters so far for an entire block. . self.matching_delim_spans.clear(); . } else { . self.matching_delim_spans.push(( . open_brace, . open_brace_span, . close_brace_span, -- line 165 ---------------------------------------- -- line 218 ---------------------------------------- . token::Eof => { . // Silently recover, the EOF token will be seen again . // and an error emitted then. Thus we don't pop from . // self.open_braces here. . } . _ => {} . } . 5,117 ( 0.00%) Ok(TokenTree::Delimited(delim_span, delim, tts).into()) . } . token::CloseDelim(delim) => { . // An unexpected closing delimiter (i.e., there is no . // matching opening delimiter). . let token_str = token_to_string(&self.token); . let msg = format!("unexpected closing delimiter: `{}`", token_str); . let mut err = . self.string_reader.sess.span_diagnostic.struct_span_err(self.token.span, &msg); -- line 234 ---------------------------------------- -- line 253 ---------------------------------------- . err.span_label(parent.1, "...matches this closing brace"); . } . } . . err.span_label(self.token.span, "unexpected closing delimiter"); . Err(err) . } . _ => { 28,620 ( 0.01%) let tt = TokenTree::Token(self.token.take()); . let mut spacing = self.bump(); 11,448 ( 0.01%) if !self.token.is_op() { . spacing = Alone; . } 34,344 ( 0.02%) Ok((tt, spacing)) . } . } 51,640 ( 0.03%) } . . fn bump(&mut self) -> Spacing { 61,037 ( 0.03%) let (spacing, token) = self.string_reader.next_token(); 32,302 ( 0.02%) self.token = token; . spacing . } . } . 731 ( 0.00%) #[derive(Default)] . struct TokenStreamBuilder { . buf: Vec, . } . . impl TokenStreamBuilder { 83,915 ( 0.04%) fn push(&mut self, (tree, joint): TreeAndSpacing) { 41,980 ( 0.02%) if let Some((TokenTree::Token(prev_token), Joint)) = self.buf.last() { 4,158 ( 0.00%) if let TokenTree::Token(token) = &tree { 6,393 ( 0.00%) if let Some(glued) = prev_token.glue(token) { . self.buf.pop(); 468 ( 0.00%) self.buf.push((TokenTree::Token(glued), joint)); . return; . } . } . } 32,080 ( 0.02%) self.buf.push((tree, joint)) 51,640 ( 0.03%) } . . fn into_token_stream(self) -> TokenStream { 7,337 ( 0.00%) TokenStream::new(self.buf) . } . } 21,565 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp.rs -------------------------------------------------------------------------------- Ir -- line 166 ---------------------------------------- . String(Cow<'static, str>), . Break(BreakToken), . Begin(BeginToken), . End, . } . . impl Token { . pub fn is_hardbreak_tok(&self) -> bool { 5,170 ( 0.00%) matches!(self, Token::Break(BreakToken { offset: 0, blank_space: SIZE_INFINITY })) . } . } . . #[derive(Copy, Clone)] . enum PrintFrame { . Fits, . Broken { offset: isize, breaks: Breaks }, . } -- line 182 ---------------------------------------- -- line 213 ---------------------------------------- . . #[derive(Clone)] . struct BufEntry { . token: Token, . size: isize, . } . . impl Printer { 8 ( 0.00%) pub fn new() -> Self { . let linewidth = 78; 413 ( 0.00%) Printer { . out: String::new(), . margin: linewidth as isize, . space: linewidth as isize, . buf: RingBuffer::new(), . left_total: 0, . right_total: 0, . scan_stack: VecDeque::new(), . print_stack: Vec::new(), . pending_indentation: 0, . last_printed: None, . } 10 ( 0.00%) } . . pub fn last_token(&self) -> Option<&Token> { . self.last_token_still_buffered().or_else(|| self.last_printed.as_ref()) . } . . pub fn last_token_still_buffered(&self) -> Option<&Token> { . self.buf.last().map(|last| &last.token) . } . . /// Be very careful with this! . pub fn replace_last_token_still_buffered(&mut self, token: Token) { . self.buf.last_mut().unwrap().token = token; . } . . fn scan_eof(&mut self) { 17 ( 0.00%) if !self.scan_stack.is_empty() { 4 ( 0.00%) self.check_stack(0); 4 ( 0.00%) self.advance_left(); . } . } . . fn scan_begin(&mut self, token: BeginToken) { 3,885 ( 0.00%) if self.scan_stack.is_empty() { 4 ( 0.00%) self.left_total = 1; . self.right_total = 1; . self.buf.clear(); . } 15,540 ( 0.01%) let right = self.buf.push(BufEntry { token: Token::Begin(token), size: -self.right_total }); . self.scan_stack.push_back(right); . } . . fn scan_end(&mut self) { 3,885 ( 0.00%) if self.scan_stack.is_empty() { . self.print_end(); . } else { . let right = self.buf.push(BufEntry { token: Token::End, size: -1 }); . self.scan_stack.push_back(right); . } . } . . fn scan_break(&mut self, token: BreakToken) { 2,585 ( 0.00%) if self.scan_stack.is_empty() { . self.left_total = 1; . self.right_total = 1; . self.buf.clear(); . } else { 5,170 ( 0.00%) self.check_stack(0); . } 10,340 ( 0.01%) let right = self.buf.push(BufEntry { token: Token::Break(token), size: -self.right_total }); . self.scan_stack.push_back(right); 7,755 ( 0.00%) self.right_total += token.blank_space; . } . 58,356 ( 0.03%) fn scan_string(&mut self, string: Cow<'static, str>) { 6,484 ( 0.00%) if self.scan_stack.is_empty() { . self.print_string(&string); . } else { . let len = string.len() as isize; 6,469 ( 0.00%) self.buf.push(BufEntry { token: Token::String(string), size: len }); 19,407 ( 0.01%) self.right_total += len; . self.check_stream(); . } 51,752 ( 0.03%) } . . fn check_stream(&mut self) { 29,111 ( 0.01%) while self.right_total - self.left_total > self.space { 1,941 ( 0.00%) if *self.scan_stack.front().unwrap() == self.buf.index_of_first() { . self.scan_stack.pop_front().unwrap(); 326 ( 0.00%) self.buf.first_mut().unwrap().size = SIZE_INFINITY; . } 1,294 ( 0.00%) self.advance_left(); 647 ( 0.00%) if self.buf.is_empty() { . break; . } . } . } . 27,857 ( 0.01%) fn advance_left(&mut self) { 34,942 ( 0.02%) while self.buf.first().unwrap().size >= 0 { 50,472 ( 0.03%) let left = self.buf.pop_first().unwrap(); . . match &left.token { . Token::String(string) => { 19,407 ( 0.01%) self.left_total += string.len() as isize; . self.print_string(string); . } . Token::Break(token) => { 7,755 ( 0.00%) self.left_total += token.blank_space; . self.print_break(*token, left.size); . } 12 ( 0.00%) Token::Begin(token) => self.print_begin(*token, left.size), . Token::End => self.print_end(), . } . 134,592 ( 0.07%) self.last_printed = Some(left.token); . 16,824 ( 0.01%) if self.buf.is_empty() { . break; . } . } 5,192 ( 0.00%) } . 23,283 ( 0.01%) fn check_stack(&mut self, mut depth: usize) { 21,678 ( 0.01%) while let Some(&index) = self.scan_stack.back() { . let mut entry = &mut self.buf[index]; 44,327 ( 0.02%) match entry.token { . Token::Begin(_) => { 9,058 ( 0.00%) if depth == 0 { . break; . } . self.scan_stack.pop_back().unwrap(); 11,643 ( 0.01%) entry.size += self.right_total; 3,881 ( 0.00%) depth -= 1; . } . Token::End => { . // paper says + not =, but that makes no sense. . self.scan_stack.pop_back().unwrap(); 3,885 ( 0.00%) entry.size = 1; 7,770 ( 0.00%) depth += 1; . } . _ => { . self.scan_stack.pop_back().unwrap(); 6,789 ( 0.00%) entry.size += self.right_total; 6,141 ( 0.00%) if depth == 0 { . break; . } . } . } . } 20,696 ( 0.01%) } . . fn get_top(&self) -> PrintFrame { 7,755 ( 0.00%) *self . .print_stack . .last() . .unwrap_or(&PrintFrame::Broken { offset: 0, breaks: Breaks::Inconsistent }) . } . . fn print_begin(&mut self, token: BeginToken, size: isize) { 11,655 ( 0.01%) if size > self.space { 20 ( 0.00%) let col = self.margin - self.space + token.offset; . self.print_stack.push(PrintFrame::Broken { offset: col, breaks: token.breaks }); . } else { . self.print_stack.push(PrintFrame::Fits); . } . } . . fn print_end(&mut self) { . self.print_stack.pop().unwrap(); . } . . fn print_break(&mut self, token: BreakToken, size: isize) { . let break_offset = 7,750 ( 0.00%) match self.get_top() { . PrintFrame::Fits => None, . PrintFrame::Broken { offset, breaks: Breaks::Consistent } => Some(offset), . PrintFrame::Broken { offset, breaks: Breaks::Inconsistent } => { . if size > self.space { Some(offset) } else { None } . } . }; . if let Some(offset) = break_offset { . self.out.push('\n'); 966 ( 0.00%) self.pending_indentation = offset + token.offset; 1,288 ( 0.00%) self.space = self.margin - (offset + token.offset); . } else { 6,789 ( 0.00%) self.pending_indentation += token.blank_space; 9,052 ( 0.00%) self.space -= token.blank_space; . } . } . . fn print_string(&mut self, string: &str) { . // Write the pending indent. A more concise way of doing this would be: . // . // write!(self.out, "{: >n$}", "", n = self.pending_indentation as usize)?; . // . // But that is significantly slower. This code is sufficiently hot, and indents can get . // sufficiently large, that the difference is significant on some workloads. 6,484 ( 0.00%) self.out.reserve(self.pending_indentation as usize); 1 ( 0.00%) self.out.extend(iter::repeat(' ').take(self.pending_indentation as usize)); 6,484 ( 0.00%) self.pending_indentation = 0; . . self.out.push_str(string); 32,405 ( 0.02%) self.space -= string.len() as isize; . } . . // Convenience functions to talk to the printer. . . /// "raw box" 5,184 ( 0.00%) pub fn rbox(&mut self, indent: usize, breaks: Breaks) { . self.scan_begin(BeginToken { offset: indent as isize, breaks }) 3,888 ( 0.00%) } . . /// Inconsistent breaking box 19,422 ( 0.01%) pub fn ibox(&mut self, indent: usize) { . self.rbox(indent, Breaks::Inconsistent) 16,185 ( 0.01%) } . . /// Consistent breaking box . pub fn cbox(&mut self, indent: usize) { . self.rbox(indent, Breaks::Consistent) . } . 20,680 ( 0.01%) pub fn break_offset(&mut self, n: usize, off: isize) { . self.scan_break(BreakToken { offset: off, blank_space: n as isize }) 15,510 ( 0.01%) } . 15,540 ( 0.01%) pub fn end(&mut self) { . self.scan_end() 15,540 ( 0.01%) } . 85 ( 0.00%) pub fn eof(mut self) -> String { . self.scan_eof(); 68 ( 0.00%) self.out 85 ( 0.00%) } . . pub fn word>>(&mut self, wrd: S) { . let string = wrd.into(); 44,109 ( 0.02%) self.scan_string(string) . } . . fn spaces(&mut self, n: usize) { 10,340 ( 0.01%) self.break_offset(n, 0) . } . . crate fn zerobreak(&mut self) { . self.spaces(0) . } . . pub fn space(&mut self) { . self.spaces(1) . } . . pub fn hardbreak(&mut self) { . self.spaces(SIZE_INFINITY as usize) . } . . pub fn is_beginning_of_line(&self) -> bool { 5,170 ( 0.00%) match self.last_token() { . Some(last_token) => last_token.is_hardbreak_tok(), . None => true, . } . } . . pub fn hardbreak_tok_offset(off: isize) -> Token { . Token::Break(BreakToken { offset: off, blank_space: SIZE_INFINITY }) . } -- line 481 ---------------------------------------- 116,864 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/sub.rs -------------------------------------------------------------------------------- Ir -- line 19 ---------------------------------------- . pub fn new( . f: &'combine mut CombineFields<'infcx, 'tcx>, . a_is_expected: bool, . ) -> Sub<'combine, 'infcx, 'tcx> { . Sub { fields: f, a_is_expected } . } . . fn with_expected_switched R>(&mut self, f: F) -> R { 10,642 ( 0.01%) self.a_is_expected = !self.a_is_expected; . let result = f(self); 29 ( 0.00%) self.a_is_expected = !self.a_is_expected; . result . } . } . . impl<'tcx> TypeRelation<'tcx> for Sub<'_, '_, 'tcx> { . fn tag(&self) -> &'static str { . "Sub" . } . fn tcx(&self) -> TyCtxt<'tcx> { 237 ( 0.00%) self.fields.infcx.tcx 41 ( 0.00%) } . . fn param_env(&self) -> ty::ParamEnv<'tcx> { . self.fields.param_env . } . . fn a_is_expected(&self) -> bool { 40 ( 0.00%) self.a_is_expected . } . . fn with_cause(&mut self, cause: Cause, f: F) -> R . where . F: FnOnce(&mut Self) -> R, . { . debug!("sub with_cause={:?}", cause); . let old_cause = mem::replace(&mut self.fields.cause, Some(cause)); -- line 55 ---------------------------------------- -- line 61 ---------------------------------------- . . fn relate_with_variance>( . &mut self, . variance: ty::Variance, . _info: ty::VarianceDiagInfo<'tcx>, . a: T, . b: T, . ) -> RelateResult<'tcx, T> { 84 ( 0.00%) match variance { 402 ( 0.00%) ty::Invariant => self.fields.equate(self.a_is_expected).relate(a, b), . ty::Covariant => self.relate(a, b), . ty::Bivariant => Ok(a), . ty::Contravariant => self.with_expected_switched(|this| this.relate(b, a)), . } . } . 73,143 ( 0.04%) fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> { . debug!("{}.tys({:?}, {:?})", self.tag(), a, b); . 8,127 ( 0.00%) if a == b { . return Ok(a); . } . 5,472 ( 0.00%) let infcx = self.fields.infcx; 5,472 ( 0.00%) let a = infcx.inner.borrow_mut().type_variables().replace_if_possible(a); 5,472 ( 0.00%) let b = infcx.inner.borrow_mut().type_variables().replace_if_possible(b); 24,621 ( 0.01%) match (a.kind(), b.kind()) { . (&ty::Infer(TyVar(_)), &ty::Infer(TyVar(_))) => { . // Shouldn't have any LBR here, so we can safely put . // this under a binder below without fear of accidental . // capture. . assert!(!a.has_escaping_bound_vars()); . assert!(!b.has_escaping_bound_vars()); . . // can't make progress on `A <: B` if both A and B are -- line 95 ---------------------------------------- -- line 102 ---------------------------------------- . a, . b, . })) . .to_predicate(self.tcx()), . )); . . Ok(a) . } 2,652 ( 0.00%) (&ty::Infer(TyVar(a_id)), _) => { 15,912 ( 0.01%) self.fields.instantiate(b, RelationDir::SupertypeOf, a_id, !self.a_is_expected)?; . Ok(a) . } 46 ( 0.00%) (_, &ty::Infer(TyVar(b_id))) => { 184 ( 0.00%) self.fields.instantiate(a, RelationDir::SubtypeOf, b_id, self.a_is_expected)?; . Ok(a) . } . . (&ty::Error(_), _) | (_, &ty::Error(_)) => { . infcx.set_tainted_by_errors(); . Ok(self.tcx().ty_error()) . } . . _ => { 228 ( 0.00%) self.fields.infcx.super_combine_tys(self, a, b)?; . Ok(a) . } . } 73,143 ( 0.04%) } . 171 ( 0.00%) fn regions( . &mut self, . a: ty::Region<'tcx>, . b: ty::Region<'tcx>, . ) -> RelateResult<'tcx, ty::Region<'tcx>> { . debug!("{}.regions({:?}, {:?}) self.cause={:?}", self.tag(), a, b, self.fields.cause); . . // FIXME -- we have more fine-grained information available . // from the "cause" field, we could perhaps give more tailored . // error messages. 57 ( 0.00%) let origin = SubregionOrigin::Subtype(Box::new(self.fields.trace.clone())); 114 ( 0.00%) self.fields . .infcx . .inner . .borrow_mut() . .unwrap_region_constraints() 114 ( 0.00%) .make_subregion(origin, a, b); . 38 ( 0.00%) Ok(a) 171 ( 0.00%) } . . fn consts( . &mut self, . a: &'tcx ty::Const<'tcx>, . b: &'tcx ty::Const<'tcx>, . ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> { . self.fields.infcx.super_combine_consts(self, a, b) . } -- line 158 ---------------------------------------- -- line 160 ---------------------------------------- . fn binders( . &mut self, . a: ty::Binder<'tcx, T>, . b: ty::Binder<'tcx, T>, . ) -> RelateResult<'tcx, ty::Binder<'tcx, T>> . where . T: Relate<'tcx>, . { 227 ( 0.00%) self.fields.higher_ranked_sub(a, b, self.a_is_expected) . } . } . . impl<'tcx> ConstEquateRelation<'tcx> for Sub<'_, '_, 'tcx> { . fn const_equate_obligation(&mut self, a: &'tcx ty::Const<'tcx>, b: &'tcx ty::Const<'tcx>) { . self.fields.add_const_equate_obligation(self.a_is_expected, a, b); . } . } -- line 176 ---------------------------------------- 29,881 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/type_variable.rs -------------------------------------------------------------------------------- Ir -- line 44 ---------------------------------------- . /// Convert from a specific kind of undo to the more general UndoLog . impl<'tcx> From for UndoLog<'tcx> { . fn from(l: Instantiate) -> Self { . UndoLog::Values(sv::UndoLog::Other(l)) . } . } . . impl<'tcx> Rollback> for TypeVariableStorage<'tcx> { 13,561 ( 0.01%) fn reverse(&mut self, undo: UndoLog<'tcx>) { 56,957 ( 0.03%) match undo { 10,848 ( 0.01%) UndoLog::EqRelation(undo) => self.eq_relations.reverse(undo), 5,434 ( 0.00%) UndoLog::SubRelation(undo) => self.sub_relations.reverse(undo), 10,840 ( 0.01%) UndoLog::Values(undo) => self.values.reverse(undo), . } 27,122 ( 0.01%) } . } . . pub struct TypeVariableStorage<'tcx> { . values: sv::SnapshotVecStorage, . . /// Two variables are unified in `eq_relations` when we have a . /// constraint `?X == ?Y`. This table also stores, for each key, . /// the known value. -- line 66 ---------------------------------------- -- line 136 ---------------------------------------- . DynReturnFn, . LatticeVariable, . } . . pub(crate) struct TypeVariableData { . origin: TypeVariableOrigin, . } . 31,858 ( 0.02%) #[derive(Copy, Clone, Debug)] . pub enum TypeVariableValue<'tcx> { . Known { value: Ty<'tcx> }, . Unknown { universe: ty::UniverseIndex }, . } . . impl<'tcx> TypeVariableValue<'tcx> { . /// If this value is known, returns the type it is known to be. . /// Otherwise, `None`. . pub fn known(&self) -> Option> { 14,256 ( 0.01%) match *self { . TypeVariableValue::Unknown { .. } => None, . TypeVariableValue::Known { value } => Some(value), . } . } . . pub fn is_unknown(&self) -> bool { . match *self { . TypeVariableValue::Unknown { .. } => true, -- line 162 ---------------------------------------- -- line 166 ---------------------------------------- . } . . pub(crate) struct Instantiate; . . pub(crate) struct Delegate; . . impl<'tcx> TypeVariableStorage<'tcx> { . pub fn new() -> TypeVariableStorage<'tcx> { 1,089 ( 0.00%) TypeVariableStorage { . values: sv::SnapshotVecStorage::new(), . eq_relations: ut::UnificationTableStorage::new(), . sub_relations: ut::UnificationTableStorage::new(), . } . } . . #[inline] . pub(crate) fn with_log<'a>( -- line 182 ---------------------------------------- -- line 188 ---------------------------------------- . } . . impl<'tcx> TypeVariableTable<'_, 'tcx> { . /// Returns the origin that was given when `vid` was created. . /// . /// Note that this function does not return care whether . /// `vid` has been unified with something else or not. . pub fn var_origin(&self, vid: ty::TyVid) -> &TypeVariableOrigin { 4 ( 0.00%) &self.storage.values.get(vid.as_usize()).origin . } . . /// Records that `a == b`, depending on `dir`. . /// . /// Precondition: neither `a` nor `b` are known. . pub fn equate(&mut self, a: ty::TyVid, b: ty::TyVid) { . debug_assert!(self.probe(a).is_unknown()); . debug_assert!(self.probe(b).is_unknown()); 42 ( 0.00%) self.eq_relations().union(a, b); 36 ( 0.00%) self.sub_relations().union(a, b); . } . . /// Records that `a <: b`, depending on `dir`. . /// . /// Precondition: neither `a` nor `b` are known. . pub fn sub(&mut self, a: ty::TyVid, b: ty::TyVid) { . debug_assert!(self.probe(a).is_unknown()); . debug_assert!(self.probe(b).is_unknown()); . self.sub_relations().union(a, b); . } . . /// Instantiates `vid` with the type `ty`. . /// . /// Precondition: `vid` must not have been previously instantiated. 14,170 ( 0.01%) pub fn instantiate(&mut self, vid: ty::TyVid, ty: Ty<'tcx>) { . let vid = self.root_var(vid); . debug_assert!(self.probe(vid).is_unknown()); . debug_assert!( . self.eq_relations().probe_value(vid).is_unknown(), . "instantiating type variable `{:?}` twice: new-value = {:?}, old-value={:?}", . vid, . ty, . self.eq_relations().probe_value(vid) . ); 19,838 ( 0.01%) self.eq_relations().union_value(vid, TypeVariableValue::Known { value: ty }); . . // Hack: we only need this so that `types_escaping_snapshot` . // can see what has been unified; see the Delegate impl for . // more details. . self.undo_log.push(Instantiate); 14,170 ( 0.01%) } . . /// Creates a new type variable. . /// . /// - `diverging`: indicates if this is a "diverging" type . /// variable, e.g., one created as the type of a `return` . /// expression. The code in this module doesn't care if a . /// variable is diverging, but the main Rust type-checker will . /// sometimes "unify" such variables with the `!` or `()` types. . /// - `origin`: indicates *why* the type variable was created. . /// The code in this module doesn't care, but it can be useful . /// for improving error messages. 17,148 ( 0.01%) pub fn new_var( . &mut self, . universe: ty::UniverseIndex, . origin: TypeVariableOrigin, . ) -> ty::TyVid { 25,722 ( 0.01%) let eq_key = self.eq_relations().new_key(TypeVariableValue::Unknown { universe }); . 14,290 ( 0.01%) let sub_key = self.sub_relations().new_key(()); 2,858 ( 0.00%) assert_eq!(eq_key.vid, sub_key); . 25,722 ( 0.01%) let index = self.values().push(TypeVariableData { origin }); 11,432 ( 0.01%) assert_eq!(eq_key.vid.as_u32(), index as u32); . . debug!("new_var(index={:?}, universe={:?}, origin={:?}", eq_key.vid, universe, origin,); . . eq_key.vid 20,006 ( 0.01%) } . . /// Returns the number of type variables created thus far. . pub fn num_vars(&self) -> usize { 10 ( 0.00%) self.storage.values.len() . } . . /// Returns the "root" variable of `vid` in the `eq_relations` . /// equivalence table. All type variables that have been equated . /// will yield the same root variable (per the union-find . /// algorithm), so `root_var(a) == root_var(b)` implies that `a == . /// b` (transitively). . pub fn root_var(&mut self, vid: ty::TyVid) -> ty::TyVid { 8,862 ( 0.00%) self.eq_relations().find(vid).vid . } . . /// Returns the "root" variable of `vid` in the `sub_relations` . /// equivalence table. All type variables that have been are . /// related via equality or subtyping will yield the same root . /// variable (per the union-find algorithm), so `sub_root_var(a) . /// == sub_root_var(b)` implies that: . /// . /// exists X. (a <: X || X <: a) && (b <: X || X <: b) 6 ( 0.00%) pub fn sub_root_var(&mut self, vid: ty::TyVid) -> ty::TyVid { 8,559 ( 0.00%) self.sub_relations().find(vid) 12 ( 0.00%) } . . /// Returns `true` if `a` and `b` have same "sub-root" (i.e., exists some . /// type X such that `forall i in {a, b}. (i <: X || X <: i)`. . pub fn sub_unified(&mut self, a: ty::TyVid, b: ty::TyVid) -> bool { . self.sub_root_var(a) == self.sub_root_var(b) . } . . /// Retrieves the type to which `vid` has been instantiated, if . /// any. 65,445 ( 0.03%) pub fn probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> { . self.inlined_probe(vid) 65,445 ( 0.03%) } . . /// An always-inlined variant of `probe`, for very hot call sites. . #[inline(always)] . pub fn inlined_probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> { 27,006 ( 0.01%) self.eq_relations().inlined_probe_value(vid) . } . . /// If `t` is a type-inference variable, and it has been . /// instantiated, then return the with which it was . /// instantiated. Otherwise, returns `t`. . pub fn replace_if_possible(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 17,598 ( 0.01%) match *t.kind() { 19,846 ( 0.01%) ty::Infer(ty::TyVar(v)) => match self.probe(v) { . TypeVariableValue::Unknown { .. } => t, . TypeVariableValue::Known { value } => value, . }, . _ => t, . } . } . . #[inline] -- line 323 ---------------------------------------- -- line 324 ---------------------------------------- . fn values( . &mut self, . ) -> sv::SnapshotVec, &mut InferCtxtUndoLogs<'tcx>> { . self.storage.values.with_log(self.undo_log) . } . . #[inline] . fn eq_relations(&mut self) -> super::UnificationTable<'_, 'tcx, TyVidEqKey<'tcx>> { 56,883 ( 0.03%) self.storage.eq_relations.with_log(self.undo_log) . } . . #[inline] . fn sub_relations(&mut self) -> super::UnificationTable<'_, 'tcx, ty::TyVid> { 5,729 ( 0.00%) self.storage.sub_relations.with_log(self.undo_log) . } . . /// Returns a range of the type variables created during the snapshot. 50 ( 0.00%) pub fn vars_since_snapshot( . &mut self, . value_count: usize, . ) -> (Range, Vec) { . let range = TyVid::from_usize(value_count)..TyVid::from_usize(self.num_vars()); 60 ( 0.00%) ( . range.start..range.end, . (range.start.as_usize()..range.end.as_usize()) . .map(|index| self.storage.values.get(index).origin) . .collect(), . ) 60 ( 0.00%) } . . /// Returns indices of all variables that are not yet . /// instantiated. . pub fn unsolved_variables(&mut self) -> Vec { . (0..self.storage.values.len()) . .filter_map(|i| { . let vid = ty::TyVid::from_usize(i); 748 ( 0.00%) match self.probe(vid) { . TypeVariableValue::Unknown { .. } => Some(vid), . TypeVariableValue::Known { .. } => None, . } . }) . .collect() . } . } . -- line 368 ---------------------------------------- -- line 391 ---------------------------------------- . /// These structs (a newtyped TyVid) are used as the unification key . /// for the `eq_relations`; they carry a `TypeVariableValue` along . /// with them. . #[derive(Copy, Clone, Debug, PartialEq, Eq)] . pub(crate) struct TyVidEqKey<'tcx> { . vid: ty::TyVid, . . // in the table, we map each ty-vid to one of these: 20,332 ( 0.01%) phantom: PhantomData>, . } . . impl<'tcx> From for TyVidEqKey<'tcx> { . #[inline] // make this function eligible for inlining - it is quite hot. . fn from(vid: ty::TyVid) -> Self { . TyVidEqKey { vid, phantom: PhantomData } . } . } -- line 407 ---------------------------------------- -- line 419 ---------------------------------------- . "TyVidEqKey" . } . } . . impl<'tcx> ut::UnifyValue for TypeVariableValue<'tcx> { . type Error = ut::NoError; . . fn unify_values(value1: &Self, value2: &Self) -> Result { 11,366 ( 0.01%) match (value1, value2) { . // We never equate two type variables, both of which . // have known types. Instead, we recursively equate . // those types. . (&TypeVariableValue::Known { .. }, &TypeVariableValue::Known { .. }) => { . bug!("equating two type variables, both of which have known types") . } . . // If one side is known, prefer that one. . (&TypeVariableValue::Known { .. }, &TypeVariableValue::Unknown { .. }) => Ok(*value1), . (&TypeVariableValue::Unknown { .. }, &TypeVariableValue::Known { .. }) => Ok(*value2), . . // If both sides are *unknown*, it hardly matters, does it? . ( 6 ( 0.00%) &TypeVariableValue::Unknown { universe: universe1 }, 6 ( 0.00%) &TypeVariableValue::Unknown { universe: universe2 }, . ) => { . // If we unify two unbound variables, ?T and ?U, then whatever . // value they wind up taking (which must be the same value) must . // be nameable by both universes. Therefore, the resulting . // universe is the minimum of the two universes, because that is . // the one which contains the fewest names in scope. . let universe = cmp::min(universe1, universe2); 24 ( 0.00%) Ok(TypeVariableValue::Unknown { universe }) . } . } . } . } 8,301 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/validity.rs -------------------------------------------------------------------------------- Ir -- line 132 ---------------------------------------- . /// State for tracking recursive validation of references . pub struct RefTracking { . pub seen: FxHashSet, . pub todo: Vec<(T, PATH)>, . } . . impl RefTracking { . pub fn empty() -> Self { 24 ( 0.00%) RefTracking { seen: FxHashSet::default(), todo: vec![] } . } 30 ( 0.00%) pub fn new(op: T) -> Self { . let mut ref_tracking_for_consts = 96 ( 0.00%) RefTracking { seen: FxHashSet::default(), todo: vec![(op, PATH::default())] }; . ref_tracking_for_consts.seen.insert(op); . ref_tracking_for_consts 30 ( 0.00%) } . . pub fn track(&mut self, op: T, path: impl FnOnce() -> PATH) { 18 ( 0.00%) if self.seen.insert(op) { . trace!("Recursing below ptr {:#?}", op); . let path = path(); . // Remember to come back to this later. 22 ( 0.00%) self.todo.push((op, path)); . } . } . } . . /// Format a path . fn write_path(out: &mut String, path: &[PathElem]) { . use self::PathElem::*; . -- line 162 ---------------------------------------- -- line 208 ---------------------------------------- . path: Vec, . ref_tracking: Option<&'rt mut RefTracking, Vec>>, . /// `None` indicates this is not validating for CTFE (but for runtime). . ctfe_mode: Option, . ecx: &'rt InterpCx<'mir, 'tcx, M>, . } . . impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M> { 77,556 ( 0.04%) fn aggregate_field_path_elem(&mut self, layout: TyAndLayout<'tcx>, field: usize) -> PathElem { . // First, check if we are projecting to a variant. 19,389 ( 0.01%) match layout.variants { . Variants::Multiple { tag_field, .. } => { . if tag_field == field { . return match layout.ty.kind() { . ty::Adt(def, ..) if def.is_enum() => PathElem::EnumTag, . ty::Generator(..) => PathElem::GeneratorTag, . _ => bug!("non-variant type {:?}", layout.ty), . }; . } . } . Variants::Single { .. } => {} . } . . // Now we know we are projecting to a field, so figure out which one. 25,852 ( 0.01%) match layout.ty.kind() { . // generators and closures. . ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => { . let mut name = None; . // FIXME this should be more descriptive i.e. CapturePlace instead of CapturedVar . // https://github.com/rust-lang/project-rfc-2229/issues/46 . if let Some(local_def_id) = def_id.as_local() { . let tables = self.ecx.tcx.typeck(local_def_id); . if let Some(captured_place) = -- line 240 ---------------------------------------- -- line 280 ---------------------------------------- . ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field), . . // dyn traits . ty::Dynamic(..) => PathElem::DynDowncast, . . // nothing else has an aggregate layout . _ => bug!("aggregate_field_path_elem: got non-aggregate type {:?}", layout.ty), . } 84,019 ( 0.04%) } . . fn with_elem( . &mut self, . elem: PathElem, . f: impl FnOnce(&mut Self) -> InterpResult<'tcx, R>, . ) -> InterpResult<'tcx, R> { . // Remember the old state 12,926 ( 0.01%) let path_len = self.path.len(); . // Record new element . self.path.push(elem); . // Perform operation 12,926 ( 0.01%) let r = f(self)?; . // Undo changes . self.path.truncate(path_len); . // Done . Ok(r) . } . 9 ( 0.00%) fn check_wide_ptr_meta( . &mut self, . meta: MemPlaceMeta, . pointee: TyAndLayout<'tcx>, . ) -> InterpResult<'tcx> { 7 ( 0.00%) let tail = self.ecx.tcx.struct_tail_erasing_lifetimes(pointee.ty, self.ecx.param_env); 4 ( 0.00%) match tail.kind() { . ty::Dynamic(..) => { . let vtable = self.ecx.scalar_to_ptr(meta.unwrap_meta()); . // Direct call to `check_ptr_access_align` checks alignment even on CTFE machines. . try_validation!( . self.ecx.memory.check_ptr_access_align( . vtable, . 3 * self.ecx.tcx.data_layout.pointer_size, // drop, size, align . self.ecx.tcx.data_layout.pointer_align.abi, -- line 321 ---------------------------------------- -- line 347 ---------------------------------------- . err_ub!(InvalidVtableAlignment(msg)) => . { "invalid vtable: alignment {}", msg }, . err_unsup!(ReadPointerAsBytes) => { "invalid size or align in vtable" }, . ); . // FIXME: More checks for the vtable. . } . ty::Slice(..) | ty::Str => { . let _len = try_validation!( 1 ( 0.00%) meta.unwrap_meta().to_machine_usize(self.ecx), . self.path, . err_unsup!(ReadPointerAsBytes) => { "non-integer slice length in wide pointer" }, . ); . // We do not check that `len * elem_size <= isize::MAX`: . // that is only required for references, and there it falls out of the . // "dereferenceable" check performed by Stacked Borrows. . } . ty::Foreign(..) => { . // Unsized, but not wide. . } . _ => bug!("Unexpected unsized type tail: {:?}", tail), . } . . Ok(()) 9 ( 0.00%) } . . /// Check a reference or `Box`. 22 ( 0.00%) fn check_safe_pointer( . &mut self, . value: &OpTy<'tcx, M::PointerTag>, . kind: &str, . ) -> InterpResult<'tcx> { 6 ( 0.00%) let value = try_validation!( 4 ( 0.00%) self.ecx.read_immediate(value), . self.path, . err_unsup!(ReadPointerAsBytes) => { "part of a pointer" } expected { "a proper pointer or integer value" }, . ); . // Handle wide pointers. . // Check metadata early, for better diagnostics 20 ( 0.00%) let place = try_validation!( 6 ( 0.00%) self.ecx.ref_to_mplace(&value), . self.path, . err_ub!(InvalidUninitBytes(None)) => { "uninitialized {}", kind }, . ); 6 ( 0.00%) if place.layout.is_unsized() { 11 ( 0.00%) self.check_wide_ptr_meta(place.meta, place.layout)?; . } . // Make sure this is dereferenceable and all. 4 ( 0.00%) let size_and_align = try_validation!( 2 ( 0.00%) self.ecx.size_and_align_of_mplace(&place), . self.path, . err_ub!(InvalidMeta(msg)) => { "invalid {} metadata: {}", kind, msg }, . ); . let (size, align) = size_and_align . // for the purpose of validity, consider foreign types to have . // alignment and size determined by the layout (size will be 0, . // alignment should take attributes into account). . .unwrap_or_else(|| (place.layout.size, place.layout.align.abi)); . // Direct call to `check_ptr_access_align` checks alignment even on CTFE machines. . try_validation!( 4 ( 0.00%) self.ecx.memory.check_ptr_access_align( 6 ( 0.00%) place.ptr, . size, . align, . CheckInAllocMsg::InboundsTest, // will anyway be replaced by validity message . ), . self.path, . err_ub!(AlignmentCheckFailed { required, has }) => . { . "an unaligned {} (required {} byte alignment but found {})", -- line 415 ---------------------------------------- -- line 424 ---------------------------------------- . err_ub!(PointerOutOfBounds { .. }) => . { "a dangling {} (going beyond the bounds of its allocation)", kind }, . // This cannot happen during const-eval (because interning already detects . // dangling pointers), but it can happen in Miri. . err_ub!(PointerUseAfterFree(..)) => . { "a dangling {} (use-after-free)", kind }, . ); . // Recursive checking 6 ( 0.00%) if let Some(ref mut ref_tracking) = self.ref_tracking { . // Proceed recursively even for ZST, no reason to skip them! . // `!` is a ZST and we want to validate it. . // Skip validation entirely for some external statics 4 ( 0.00%) if let Ok((alloc_id, _offset, _ptr)) = self.ecx.memory.ptr_try_get_alloc(place.ptr) { . // not a ZST 6 ( 0.00%) let alloc_kind = self.ecx.tcx.get_global_alloc(alloc_id); 4 ( 0.00%) if let Some(GlobalAlloc::Static(did)) = alloc_kind { . assert!(!self.ecx.tcx.is_thread_local_static(did)); . assert!(self.ecx.tcx.is_static(did)); . if matches!( . self.ctfe_mode, . Some(CtfeValidationMode::Const { allow_static_ptrs: false, .. }) . ) { . // See const_eval::machine::MemoryExtra::can_access_statics for why . // this check is so important. -- line 447 ---------------------------------------- -- line 460 ---------------------------------------- . // and that static refers back to us. . // We might miss const-invalid data, . // but things are still sound otherwise (in particular re: consts . // referring to statics). . return Ok(()); . } . } . let path = &self.path; 18 ( 0.00%) ref_tracking.track(place, || { . // We need to clone the path anyway, make sure it gets created . // with enough space for the additional `Deref`. 8 ( 0.00%) let mut new_path = Vec::with_capacity(path.len() + 1); . new_path.clone_from(path); . new_path.push(PathElem::Deref); . new_path . }); . } . Ok(()) 18 ( 0.00%) } . 36,218 ( 0.02%) fn read_scalar( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, ScalarMaybeUninit> { 41,392 ( 0.02%) Ok(try_validation!( 15,522 ( 0.01%) self.ecx.read_scalar(op), . self.path, . err_unsup!(ReadPointerAsBytes) => { "(potentially part of) a pointer" } expected { "plain (non-pointer) bytes" }, . )) 31,044 ( 0.02%) } . . /// Check if this is a value of primitive type, and if yes check the validity of the value . /// at that type. Return `true` if the type is indeed primitive. 58,239 ( 0.03%) fn try_visit_primitive( . &mut self, . value: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, bool> { . // Go over all the primitive types 19,413 ( 0.01%) let ty = value.layout.ty; 38,826 ( 0.02%) match ty.kind() { . ty::Bool => { . let value = self.read_scalar(value)?; . try_validation!( . value.to_bool(), . self.path, . err_ub!(InvalidBool(..)) | err_ub!(InvalidUninitBytes(None)) => . { "{}", value } expected { "a boolean" }, . ); . Ok(true) . } . ty::Char => { 10,336 ( 0.01%) let value = self.read_scalar(value)?; 5,168 ( 0.00%) try_validation!( . value.to_char(), . self.path, . err_ub!(InvalidChar(..)) | err_ub!(InvalidUninitBytes(None)) => . { "{}", value } expected { "a valid unicode scalar value (in `0..=0x10FFFF` but not in `0xD800..=0xDFFF`)" }, . ); . Ok(true) . } . ty::Float(_) | ty::Int(_) | ty::Uint(_) => { 10,360 ( 0.01%) let value = self.read_scalar(value)?; . // NOTE: Keep this in sync with the array optimization for int/float . // types below! . if M::enforce_number_validity(self.ecx) { . // Integers/floats in CTFE: Must be scalar bits, pointers are dangerous . let is_bits = value.check_init().map_or(false, |v| v.try_to_int().is_ok()); . if !is_bits { . throw_validation_failure!(self.path, . { "{}", value } expected { "initialized plain (non-pointer) bytes" } -- line 529 ---------------------------------------- -- line 543 ---------------------------------------- . err_unsup!(ReadPointerAsBytes) => { "part of a pointer" } expected { "a proper pointer or integer value" }, . ); . if place.layout.is_unsized() { . self.check_wide_ptr_meta(place.meta, place.layout)?; . } . Ok(true) . } . ty::Ref(_, ty, mutbl) => { 6 ( 0.00%) if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { .. })) . && *mutbl == hir::Mutability::Mut . { . // A mutable reference inside a const? That does not seem right (except if it is . // a ZST). . let layout = self.ecx.layout_of(ty)?; . if !layout.is_zst() { . throw_validation_failure!(self.path, { "mutable reference in a `const`" }); . } . } 6 ( 0.00%) self.check_safe_pointer(value, "reference")?; . Ok(true) . } . ty::Adt(def, ..) if def.is_box() => { . self.check_safe_pointer(value, "box")?; . Ok(true) . } . ty::FnPtr(_sig) => { . let value = try_validation!( -- line 569 ---------------------------------------- -- line 606 ---------------------------------------- . | ty::Infer(..) . | ty::Placeholder(..) . | ty::Bound(..) . | ty::Param(..) . | ty::Opaque(..) . | ty::Projection(..) . | ty::GeneratorWitness(..) => bug!("Encountered invalid type {:?}", ty), . } 97,065 ( 0.05%) } . . fn visit_scalar( . &mut self, . op: &OpTy<'tcx, M::PointerTag>, . scalar_layout: ScalarAbi, . ) -> InterpResult<'tcx> { . if scalar_layout.valid_range.is_full_for(op.layout.size) { . // Nothing to check -- line 622 ---------------------------------------- -- line 709 ---------------------------------------- . . #[inline] . fn visit_field( . &mut self, . old_op: &OpTy<'tcx, M::PointerTag>, . field: usize, . new_op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 29,728 ( 0.02%) let elem = self.aggregate_field_path_elem(old_op.layout, field); 19,389 ( 0.01%) self.with_elem(elem, move |this| this.visit_value(new_op)) . } . . #[inline] . fn visit_variant( . &mut self, . old_op: &OpTy<'tcx, M::PointerTag>, . variant_id: VariantIdx, . new_op: &OpTy<'tcx, M::PointerTag>, -- line 726 ---------------------------------------- -- line 745 ---------------------------------------- . if !op.layout.ty.is_freeze(self.ecx.tcx.at(DUMMY_SP), self.ecx.param_env) { . throw_validation_failure!(self.path, { "`UnsafeCell` in a `const`" }); . } . } . Ok(()) . } . . #[inline] 58,167 ( 0.03%) fn visit_value(&mut self, op: &OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> { . trace!("visit_value: {:?}, {:?}", *op, op.layout); . . // Check primitive types -- the leafs of our recursive descend. 25,876 ( 0.01%) if self.try_visit_primitive(op)? { . return Ok(()); . } . // Sanity check: `builtin_deref` does not know any pointers that are not primitive. 5,180 ( 0.00%) assert!(op.layout.ty.builtin_deref(true).is_none()); . . // Special check preventing `UnsafeCell` in the inner part of constants 2,590 ( 0.00%) if let Some(def) = op.layout.ty.ty_adt_def() { . if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { inner: true, .. })) . && Some(def.did) == self.ecx.tcx.lang_items().unsafe_cell_type() . { . throw_validation_failure!(self.path, { "`UnsafeCell` in a `const`" }); . } . } . . // Recursively walk the value at its type. 6,475 ( 0.00%) self.walk_value(op)?; . . // *After* all of this, check the ABI. We need to check the ABI to handle . // types like `NonNull` where the `Scalar` info is more restrictive than what . // the fields say (`rustc_layout_scalar_valid_range_start`). . // But in most cases, this will just propagate what the fields say, . // and then we want the error to point at the field -- so, first recurse, . // then check ABI. . // . // FIXME: We could avoid some redundant checks here. For newtypes wrapping . // scalars, we do the same check on every "level" (e.g., first we check . // MyNewtype and then the scalar in there). 6,475 ( 0.00%) match op.layout.abi { . Abi::Uninhabited => { . throw_validation_failure!(self.path, . { "a value of uninhabited type {:?}", op.layout.ty } . ); . } . Abi::Scalar(scalar_layout) => { . self.visit_scalar(op, scalar_layout)?; . } -- line 793 ---------------------------------------- -- line 798 ---------------------------------------- . // that would make skipping them here an issue. . } . Abi::Aggregate { .. } => { . // Nothing to do. . } . } . . Ok(()) 51,704 ( 0.03%) } . . fn visit_aggregate( . &mut self, . op: &OpTy<'tcx, M::PointerTag>, . fields: impl Iterator>, . ) -> InterpResult<'tcx> { 11,655 ( 0.01%) match op.layout.ty.kind() { . ty::Str => { . let mplace = op.assert_mem_place(); // strings are never immediate . let len = mplace.len(self.ecx)?; . try_validation!( . self.ecx.memory.read_bytes(mplace.ptr, Size::from_bytes(len)), . self.path, . err_ub!(InvalidUninitBytes(..)) => { "uninitialized data in `str`" }, . err_unsup!(ReadPointerAsBytes) => { "a pointer in `str`" }, -- line 821 ---------------------------------------- -- line 822 ---------------------------------------- . ); . } . ty::Array(tys, ..) | ty::Slice(tys) . // This optimization applies for types that can hold arbitrary bytes (such as . // integer and floating point types) or for structs or tuples with no fields. . // FIXME(wesleywiser) This logic could be extended further to arbitrary structs . // or tuples made up of integer/floating point types or inhabited ZSTs with no . // padding. 10 ( 0.00%) if matches!(tys.kind(), ty::Int(..) | ty::Uint(..) | ty::Float(..)) . => . { . // Optimized handling for arrays of integer/float type. . . // Arrays cannot be immediate, slices are never immediate. . let mplace = op.assert_mem_place(); . // This is the length of the array/slice. . let len = mplace.len(self.ecx)?; -- line 838 ---------------------------------------- -- line 891 ---------------------------------------- . _ => return Err(err), . } . } . } . } . // Fast path for arrays and slices of ZSTs. We only need to check a single ZST element . // of an array and not all of them, because there's only a single value of a specific . // ZST type, so either validation fails for all elements or none. 18 ( 0.00%) ty::Array(tys, ..) | ty::Slice(tys) if self.ecx.layout_of(tys)?.is_zst() => { . // Validate just the first element (if any). . self.walk_aggregate(op, fields.take(1))? . } . _ => { . self.walk_aggregate(op, fields)? // default handler . } . } . Ok(()) . } . } . . impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { 48 ( 0.00%) fn validate_operand_internal( . &self, . op: &OpTy<'tcx, M::PointerTag>, . path: Vec, . ref_tracking: Option<&mut RefTracking, Vec>>, . ctfe_mode: Option, . ) -> InterpResult<'tcx> { . trace!("validate_operand_internal: {:?}, {:?}", *op, op.layout.ty); . . // Construct a visitor 72 ( 0.00%) let mut visitor = ValidityVisitor { path, ref_tracking, ctfe_mode, ecx: self }; . . // Run it. 24 ( 0.00%) match visitor.visit_value(&op) { . Ok(()) => Ok(()), . // Pass through validation failures. . Err(err) if matches!(err.kind(), err_ub!(ValidationFailure { .. })) => Err(err), . // Also pass through InvalidProgram, those just indicate that we could not . // validate and each caller will know best what to do with them. . Err(err) if matches!(err.kind(), InterpError::InvalidProgram(_)) => Err(err), . // Avoid other errors as those do not show *where* in the value the issue lies. . Err(err) => { . err.print_backtrace(); . bug!("Unexpected error during validation: {}", err); . } . } 56 ( 0.00%) } . . /// This function checks the data at `op` to be const-valid. . /// `op` is assumed to cover valid memory if it is an indirect operand. . /// It will error if the bits at the destination do not match the ones described by the layout. . /// . /// `ref_tracking` is used to record references that we encounter so that they . /// can be checked recursively by an outside driving loop. . /// -- line 946 ---------------------------------------- -- line 950 ---------------------------------------- . #[inline(always)] . pub fn const_validate_operand( . &self, . op: &OpTy<'tcx, M::PointerTag>, . path: Vec, . ref_tracking: &mut RefTracking, Vec>, . ctfe_mode: CtfeValidationMode, . ) -> InterpResult<'tcx> { 80 ( 0.00%) self.validate_operand_internal(op, path, Some(ref_tracking), Some(ctfe_mode)) . } . . /// This function checks the data at `op` to be runtime-valid. . /// `op` is assumed to cover valid memory if it is an indirect operand. . /// It will error if the bits at the destination do not match the ones described by the layout. . #[inline(always)] . pub fn validate_operand(&self, op: &OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> { . self.validate_operand_internal(op, vec![], None, None) -- line 966 ---------------------------------------- 90,543 ( 0.05%) -------------------------------------------------------------------------------- -- 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 { 24 ( 0.00%) fn clone(&self) -> Self { 28 ( 0.00%) HashMap { . hash_builder: self.hash_builder.clone(), 4 ( 0.00%) table: self.table.clone(), . } 27 ( 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, . { 10,784 ( 0.01%) 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, . { 46,845 ( 0.02%) 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, . { 22,731 ( 0.01%) 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)] 4 ( 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) 8 ( 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 { 49,724 ( 0.03%) 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 { 13 ( 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 { 367 ( 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 { 10,941 ( 0.01%) 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)] 28 ( 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)) { . Entry::Occupied(OccupiedEntry { . hash, . key: Some(key), . elem, . table: self, . }) . } else { 35 ( 0.00%) Entry::Vacant(VacantEntry { . hash, . key, . table: self, . }) . } 35 ( 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. 117,892 ( 0.06%) 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, . { 130,722 ( 0.07%) if self.table.is_empty() { . None . } else { 2 ( 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)] 19,504 ( 0.01%) pub fn contains_key(&self, k: &Q) -> bool . where . K: Borrow, . Q: Hash + Eq, . { . self.get_inner(k).is_some() 31,690 ( 0.02%) } . . /// 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)] 24 ( 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. 72 ( 0.00%) match self.get_inner_mut(k) { . Some(&mut (_, ref mut v)) => Some(v), . None => None, . } 48 ( 0.00%) } . . #[inline] . fn get_inner_mut(&mut self, k: &Q) -> Option<&mut (K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 24 ( 0.00%) if self.table.is_empty() { . None . } else { . let hash = make_hash::(&self.hash_builder, k); . self.table.get_mut(hash, equivalent_key(k)) . } . } . . /// Attempts to get mutable references to `N` values in the map at once. -- line 1219 ---------------------------------------- -- 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)] 269,691 ( 0.14%) pub fn insert(&mut self, k: K, v: V) -> Option { . let hash = make_insert_hash::(&self.hash_builder, &k); 5 ( 0.00%) if let Some((_, item)) = self.table.get_mut(hash, equivalent_key(&k)) { . Some(mem::replace(item, v)) . } else { 94,543 ( 0.05%) self.table 100,753 ( 0.05%) .insert(hash, (k, v), make_hasher::(&self.hash_builder)); 6,058 ( 0.00%) None . } 249,690 ( 0.13%) } . . /// 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)] 13,817 ( 0.01%) pub fn remove(&mut self, k: &Q) -> Option . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 46,674 ( 0.02%) match self.remove_entry(k) { 287 ( 0.00%) Some((_, v)) => Some(v), 10,527 ( 0.01%) None => None, . } 34,362 ( 0.02%) } . . /// 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); 16,408 ( 0.01%) 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, . { 99,726 ( 0.05%) 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)] 224,217 ( 0.11%) 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) 245,344 ( 0.12%) } . . #[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, . { 28,412 ( 0.01%) match self.map.table.find(hash, |(k, _)| is_match(k)) { 150,435 ( 0.08%) Some(elem) => RawEntryMut::Occupied(RawOccupiedEntryMut { . elem, . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), 11,741 ( 0.01%) 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)] 99,605 ( 0.05%) pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)> . where . K: Borrow, . Q: Eq, . { 65,170 ( 0.03%) self.from_hash(hash, equivalent(k)) 159,348 ( 0.08%) } . . #[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, . { 181,635 ( 0.09%) 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, . { 18,739 ( 0.01%) 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)] 35 ( 0.00%) fn into_iter(self) -> IntoIter { 893 ( 0.00%) IntoIter { 584 ( 0.00%) inner: self.table.into_iter(), . } 105 ( 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. 12,123 ( 0.01%) match self.inner.next() { . Some(x) => unsafe { . let r = x.as_ref(); 32 ( 0.00%) Some((&r.0, &r.1)) . }, . None => None, . } . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { 3 ( 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)> { 51 ( 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)] 3 ( 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, . } 6 ( 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 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)] 859 ( 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. 783 ( 0.00%) let iter = iter.into_iter(); 325 ( 0.00%) let reserve = if self.is_empty() { . iter.size_hint().0 . } else { 7 ( 0.00%) (iter.size_hint().0 + 1) / 2 . }; . self.reserve(reserve); . iter.for_each(move |(k, v)| { 12,807 ( 0.01%) self.insert(k, v); . }); 433 ( 0.00%) } . . #[inline] . #[cfg(feature = "nightly")] . fn extend_one(&mut self, (k, v): (K, V)) { . self.insert(k, v); . } . . #[inline] -- line 4588 ---------------------------------------- 148,184 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/range.rs -------------------------------------------------------------------------------- Ir -- line 198 ---------------------------------------- . } . . #[inline] . #[allow(arithmetic_overflow)] . #[rustc_inherit_overflow_checks] . fn forward(start: Self, n: usize) -> Self { . // In debug builds, trigger a panic on overflow. . // This should optimize completely out in release builds. 3,185 ( 0.00%) if Self::forward_checked(start, n).is_none() { . let _ = Self::MAX + 1; . } . // Do wrapping math to allow e.g. `Step::forward(-128i8, 255)`. . start.wrapping_add(n as Self) . } . . #[inline] . #[allow(arithmetic_overflow)] -- line 214 ---------------------------------------- -- line 613 ---------------------------------------- . . if taken < n { Err(taken) } else { Ok(()) } . } . } . . impl RangeIteratorImpl for ops::Range { . #[inline] . fn spec_next(&mut self) -> Option { 432,696 ( 0.22%) if self.start < self.end { . // SAFETY: just checked precondition . let n = unsafe { Step::forward_unchecked(self.start.clone(), 1) }; . Some(mem::replace(&mut self.start, n)) . } else { . None . } . } . -- line 629 ---------------------------------------- -- line 657 ---------------------------------------- . // Otherwise 0 is returned which always safe to use. . self.start = unsafe { Step::forward_unchecked(self.start.clone(), taken) }; . . if taken < n { Err(taken) } else { Ok(()) } . } . . #[inline] . fn spec_next_back(&mut self) -> Option { 4,672 ( 0.00%) if self.start < self.end { . // SAFETY: just checked precondition . self.end = unsafe { Step::backward_unchecked(self.end.clone(), 1) }; . Some(self.end.clone()) . } else { . None . } . } . -- line 673 ---------------------------------------- -- line 708 ---------------------------------------- . . #[inline] . fn next(&mut self) -> Option { . self.spec_next() . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 12,864 ( 0.01%) if self.start < self.end { . let hint = Step::steps_between(&self.start, &self.end); . (hint.unwrap_or(usize::MAX), hint) . } else { . (0, Some(0)) . } . } . . #[inline] -- line 724 ---------------------------------------- -- line 857 ---------------------------------------- . impl FusedIterator for ops::Range {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for ops::RangeFrom { . type Item = A; . . #[inline] . fn next(&mut self) -> Option { 273 ( 0.00%) let n = Step::forward(self.start.clone(), 1); . Some(mem::replace(&mut self.start, n)) . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { . (usize::MAX, None) . } . -- line 873 ---------------------------------------- -- line 998 ---------------------------------------- . . try { accum } . } . } . . impl RangeInclusiveIteratorImpl for ops::RangeInclusive { . #[inline] . fn spec_next(&mut self) -> Option { 199 ( 0.00%) if self.is_empty() { . return None; . } . let is_iterating = self.start < self.end; 128 ( 0.00%) Some(if is_iterating { . // SAFETY: just checked precondition . let n = unsafe { Step::forward_unchecked(self.start.clone(), 1) }; . mem::replace(&mut self.start, n) . } else { . self.exhausted = true; . self.start.clone() . }) . } -- line 1018 ---------------------------------------- -- line 1025 ---------------------------------------- . R: Try, . { . if self.is_empty() { . return try { init }; . } . . let mut accum = init; . 968 ( 0.00%) while self.start < self.end { . // SAFETY: just checked precondition . let n = unsafe { Step::forward_unchecked(self.start.clone(), 1) }; . let n = mem::replace(&mut self.start, n); . accum = f(accum, n)?; . } . . self.exhausted = true; . 14 ( 0.00%) if self.start == self.end { . accum = f(accum, self.start.clone())?; . } . . try { accum } . } . . #[inline] . fn spec_next_back(&mut self) -> Option { -- line 1050 ---------------------------------------- -- line 1098 ---------------------------------------- . . #[inline] . fn next(&mut self) -> Option { . self.spec_next() . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 272 ( 0.00%) if self.is_empty() { . return (0, Some(0)); . } . . match Step::steps_between(&self.start, &self.end) { . Some(hint) => (hint.saturating_add(1), hint.checked_add(1)), . None => (usize::MAX, None), . } . } -- line 1114 ---------------------------------------- 78,222 ( 0.04%) -------------------------------------------------------------------------------- -- 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 . // . 221,594 ( 0.11%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 166,194 ( 0.08%) 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. 6,388 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 9,582 ( 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) { 56,985 ( 0.03%) libc::free(ptr as *mut libc::c_void) . } . . #[inline] . unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { 15,772 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 31,544 ( 0.02%) 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/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. 14,500 ( 0.01%) 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. 61,212 ( 0.03%) 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`. 65 ( 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 { 8,601 ( 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 { 23,784 ( 0.01%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 10,407 ( 0.01%) assume(!self.end.is_null()); . } 3,699,513 ( 1.87%) if is_empty!(self) { . None . } else { . Some(next_unchecked!(self)) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 60,821 ( 0.03%) let exact = len!(self); . (exact, Some(exact)) . } . . #[inline] . fn count(self) -> usize { . len!(self) . } . . #[inline] . fn nth(&mut self, n: usize) -> Option<$elem> { 263 ( 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() { 46 ( 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, . { 8 ( 0.00%) while let Some(x) = self.next() { 868 ( 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] . fn any(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 60,900 ( 0.03%) while let Some(x) = self.next() { 124,587 ( 0.06%) if f(x) { . return true; . } . } . false . } . . // 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, . { 281 ( 0.00%) while let Some(x) = self.next() { 2,222 ( 0.00%) if predicate(&x) { . return Some(x); . } . } . None 60 ( 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, . { 768 ( 0.00%) while let Some(x) = self.next() { 9,259 ( 0.00%) if let Some(y) = f(x) { 119 ( 0.00%) return Some(y); . } . } . None 214 ( 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() { 17,131 ( 0.01%) 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; 1,240 ( 0.00%) while let Some(x) = self.next_back() { 18,150 ( 0.01%) i -= 1; 15,643 ( 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` 937 ( 0.00%) 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 351 ---------------------------------------- . . // 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 { . assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 4 ( 0.00%) assume(!self.end.is_null()); . } 57,868 ( 0.03%) if is_empty!(self) { . None . } else { . Some(next_back_unchecked!(self)) . } . } . } . . #[inline] -- line 369 ---------------------------------------- 432,728 ( 0.22%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs -------------------------------------------------------------------------------- Ir -- line 72 ---------------------------------------- . } . . impl From> for LhsExpr { . /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)` . /// and `None` into `LhsExpr::NotYetParsed`. . /// . /// This conversion does not allocate. . fn from(o: Option) -> Self { 8,544 ( 0.00%) if let Some(attrs) = o { LhsExpr::AttributesParsed(attrs) } else { LhsExpr::NotYetParsed } . } . } . . impl From> for LhsExpr { . /// Converts the `expr: P` into `LhsExpr::AlreadyParsed(expr)`. . /// . /// This conversion does not allocate. . fn from(expr: P) -> Self { -- line 88 ---------------------------------------- -- line 103 ---------------------------------------- . pub fn parse_expr_force_collect(&mut self) -> PResult<'a, P> { . self.collect_tokens_no_attrs(|this| this.parse_expr()) . } . . pub fn parse_anon_const_expr(&mut self) -> PResult<'a, AnonConst> { . self.parse_expr().map(|value| AnonConst { id: DUMMY_NODE_ID, value }) . } . 20,880 ( 0.01%) fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P> { 5,220 ( 0.00%) match self.parse_expr() { . Ok(expr) => Ok(expr), . Err(mut err) => match self.token.ident() { . Some((Ident { name: kw::Underscore, .. }, false)) . if self.look_ahead(1, |t| t == &token::Comma) => . { . // Special-case handling of `foo(_, _, _)` . err.emit(); . self.bump(); . Ok(self.mk_expr(self.prev_token.span, ExprKind::Err, AttrVec::new())) . } . _ => Err(err), . }, . } 26,100 ( 0.01%) } . . /// Parses a sequence of expressions delimited by parentheses. . fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec>> { 114 ( 0.00%) self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore()).map(|(r, _)| r) . } . . /// Parses an expression, subject to the given restrictions. . #[inline] . pub(super) fn parse_expr_res( . &mut self, . r: Restrictions, . already_parsed_attrs: Option, -- line 138 ---------------------------------------- -- line 144 ---------------------------------------- . /// . /// This parses an expression accounting for associativity and precedence of the operators in . /// the expression. . #[inline] . fn parse_assoc_expr( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, P> { 10,491 ( 0.01%) self.parse_assoc_expr_with(0, already_parsed_attrs.into()) . } . . /// Parses an associative expression with operators of at least `min_prec` precedence. 29,682 ( 0.02%) pub(super) fn parse_assoc_expr_with( . &mut self, . min_prec: usize, . lhs: LhsExpr, . ) -> PResult<'a, P> { 16,494 ( 0.01%) let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs { 36 ( 0.00%) expr . } else { 6,578 ( 0.00%) let attrs = match lhs { 6,598 ( 0.00%) LhsExpr::AttributesParsed(attrs) => Some(attrs), . _ => None, . }; 3,289 ( 0.00%) if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) { . return self.parse_prefix_range_expr(attrs); . } else { 39,468 ( 0.02%) self.parse_prefix_expr(attrs)? . } . }; 6,596 ( 0.00%) let last_type_ascription_set = self.last_type_ascription.is_some(); . . if !self.should_continue_as_assoc_expr(&lhs) { 15 ( 0.00%) self.last_type_ascription = None; . return Ok(lhs); . } . . self.expected_tokens.push(TokenType::Operator); 40 ( 0.00%) while let Some(op) = self.check_assoc_op() { . // Adjust the span for interpolated LHS to point to the `$lhs` token . // and not to what it refers to. 60 ( 0.00%) let lhs_span = match self.prev_token.kind { . TokenKind::Interpolated(..) => self.prev_token.span, . _ => lhs.span, . }; . 20 ( 0.00%) let cur_op_span = self.token.span; 80 ( 0.00%) let restrictions = if op.node.is_assign_like() { . self.restrictions & Restrictions::NO_STRUCT_LITERAL . } else { . self.restrictions . }; 30 ( 0.00%) let prec = op.node.precedence(); 20 ( 0.00%) if prec < min_prec { . break; . } . // Check for deprecated `...` syntax 36 ( 0.00%) if self.token == token::DotDotDot && op.node == AssocOp::DotDotEq { . self.err_dotdotdot_syntax(self.token.span); . } . 36 ( 0.00%) if self.token == token::LArrow { . self.err_larrow_operator(self.token.span); . } . 9 ( 0.00%) self.bump(); 36 ( 0.00%) if op.node.is_comparison() { . if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? { . return Ok(expr); . } . } . . // Look for JS' `===` and `!==` and recover 9 ( 0.00%) if (op.node == AssocOp::Equal || op.node == AssocOp::NotEqual) . && self.token.kind == token::Eq . && self.prev_token.span.hi() == self.token.span.lo() . { . let sp = op.span.to(self.token.span); . let sugg = match op.node { . AssocOp::Equal => "==", . AssocOp::NotEqual => "!=", . _ => unreachable!(), -- line 225 ---------------------------------------- -- line 231 ---------------------------------------- . sugg.to_string(), . Applicability::MachineApplicable, . ) . .emit(); . self.bump(); . } . . // Look for PHP's `<>` and recover 8 ( 0.00%) if op.node == AssocOp::Less 8 ( 0.00%) && self.token.kind == token::Gt . && self.prev_token.span.hi() == self.token.span.lo() . { . let sp = op.span.to(self.token.span); . self.struct_span_err(sp, "invalid comparison operator `<>`") . .span_suggestion_short( . sp, . "`<>` is not a valid comparison operator, use `!=`", . "!=".to_string(), . Applicability::MachineApplicable, . ) . .emit(); . self.bump(); . } . . // Look for C++'s `<=>` and recover 4 ( 0.00%) if op.node == AssocOp::LessEqual 4 ( 0.00%) && self.token.kind == token::Gt . && self.prev_token.span.hi() == self.token.span.lo() . { . let sp = op.span.to(self.token.span); . self.struct_span_err(sp, "invalid comparison operator `<=>`") . .span_label( . sp, . "`<=>` is not a valid comparison operator, use `std::cmp::Ordering`", . ) . .emit(); . self.bump(); . } . 18 ( 0.00%) let op = op.node; . // Special cases: . if op == AssocOp::As { 10 ( 0.00%) lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?; . continue; . } else if op == AssocOp::Colon { . lhs = self.parse_assoc_op_ascribe(lhs, lhs_span)?; . continue; . } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq { . // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to . // generalise it to the Fixity::None code. . lhs = self.parse_range_expr(prec, lhs, op, cur_op_span)?; . break; . } . 7 ( 0.00%) let fixity = op.fixity(); 21 ( 0.00%) let prec_adjustment = match fixity { . Fixity::Right => 0, . Fixity::Left => 1, . // We currently have no non-associative operators that are not handled above by . // the special cases. The code is here only for future convenience. . Fixity::None => 1, . }; 14 ( 0.00%) let rhs = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| { 35 ( 0.00%) this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed) . })?; . . let span = self.mk_expr_sp(&lhs, lhs_span, rhs.span); 63 ( 0.00%) lhs = match op { . AssocOp::Add . | AssocOp::Subtract . | AssocOp::Multiply . | AssocOp::Divide . | AssocOp::Modulus . | AssocOp::LAnd . | AssocOp::LOr . | AssocOp::BitXor -- line 306 ---------------------------------------- -- line 309 ---------------------------------------- . | AssocOp::ShiftLeft . | AssocOp::ShiftRight . | AssocOp::Equal . | AssocOp::Less . | AssocOp::LessEqual . | AssocOp::NotEqual . | AssocOp::Greater . | AssocOp::GreaterEqual => { 14 ( 0.00%) let ast_op = op.to_ast_binop().unwrap(); . let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs); . self.mk_expr(span, binary, AttrVec::new()) . } . AssocOp::Assign => { . self.mk_expr(span, ExprKind::Assign(lhs, rhs, cur_op_span), AttrVec::new()) . } . AssocOp::AssignOp(k) => { . let aop = match k { -- line 325 ---------------------------------------- -- line 337 ---------------------------------------- . let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs); . self.mk_expr(span, aopexpr, AttrVec::new()) . } . AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => { . self.span_bug(span, "AssocOp should have been handled by special case") . } . }; . 14 ( 0.00%) if let Fixity::None = fixity { . break; . } . } 3,293 ( 0.00%) if last_type_ascription_set { . self.last_type_ascription = None; . } 6,586 ( 0.00%) Ok(lhs) 56,056 ( 0.03%) } . . fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool { 23,096 ( 0.01%) match (self.expr_is_complete(lhs), AssocOp::from_token(&self.token)) { . // Semi-statement forms are odd: . // See https://github.com/rust-lang/rust/issues/29071 . (true, None) => false, . (false, _) => true, // Continue parsing the expression. . // An exhaustive check is done in the following block, but these are checked first . // because they *are* ambiguous but also reasonable looking incorrect syntax, so we . // want to keep their span info to improve diagnostics in these cases in a later stage. . (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3` -- line 364 ---------------------------------------- -- line 401 ---------------------------------------- . err.emit(); . } . . /// Possibly translate the current token to an associative operator. . /// The method does not advance the current token. . /// . /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively. . fn check_assoc_op(&self) -> Option> { 36,332 ( 0.02%) let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) { . // When parsing const expressions, stop parsing when encountering `>`. . ( . Some( . AssocOp::ShiftRight . | AssocOp::Greater . | AssocOp::GreaterEqual . | AssocOp::AssignOp(token::BinOpToken::Shr), . ), . _, . ) if self.restrictions.contains(Restrictions::CONST_EXPR) => { . return None; . } 20 ( 0.00%) (Some(op), _) => (op, self.token.span), . (None, Some((Ident { name: sym::and, span }, false))) => { . self.error_bad_logical_op("and", "&&", "conjunction"); . (AssocOp::LAnd, span) . } . (None, Some((Ident { name: sym::or, span }, false))) => { . self.error_bad_logical_op("or", "||", "disjunction"); . (AssocOp::LOr, span) . } -- line 430 ---------------------------------------- -- line 443 ---------------------------------------- . Applicability::MachineApplicable, . ) . .note("unlike in e.g., python and PHP, `&&` and `||` are used for logical operators") . .emit(); . } . . /// Checks if this expression is a successfully parsed statement. . fn expr_is_complete(&self, e: &Expr) -> bool { 6,607 ( 0.00%) self.restrictions.contains(Restrictions::STMT_EXPR) 110 ( 0.00%) && !classify::expr_requires_semi_to_be_stmt(e) . } . . /// Parses `x..y`, `x..=y`, and `x..`/`x..=`. . /// The other two variants are handled in `parse_prefix_range_expr` below. . fn parse_range_expr( . &mut self, . prec: usize, . lhs: P, -- line 460 ---------------------------------------- -- line 520 ---------------------------------------- . (lo, None) . }; . let range = this.mk_range(None, opt_end, limits); . Ok(this.mk_expr(span, range, attrs.into())) . }) . } . . /// Parses a prefix-unary-operator expr. 23,030 ( 0.01%) fn parse_prefix_expr(&mut self, attrs: Option) -> PResult<'a, P> { 26,320 ( 0.01%) let attrs = self.parse_or_use_outer_attributes(attrs)?; 16,450 ( 0.01%) let lo = self.token.span; . . macro_rules! make_it { . ($this:ident, $attrs:expr, |this, _| $body:expr) => { 9 ( 0.00%) $this.collect_tokens_for_expr($attrs, |$this, attrs| { 17 ( 0.00%) let (hi, ex) = $body?; 16 ( 0.00%) Ok($this.mk_expr(lo.to(hi), ex, attrs.into())) 10 ( 0.00%) }) . }; . } . . let this = self; . . // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr() 19,756 ( 0.01%) match this.token.uninterpolate().kind { . token::Not => make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Not)), // `!expr` . token::Tilde => make_it!(this, attrs, |this, _| this.recover_tilde_expr(lo)), // `~expr` . token::BinOp(token::Minus) => { . make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Neg)) . } // `-expr` . token::BinOp(token::Star) => { . make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Deref)) . } // `*expr` . token::BinOp(token::And) | token::AndAnd => { 2 ( 0.00%) make_it!(this, attrs, |this, _| this.parse_borrow_expr(lo)) . } . token::BinOp(token::Plus) if this.look_ahead(1, |tok| tok.is_numeric_lit()) => { . let mut err = this.struct_span_err(lo, "leading `+` is not supported"); . err.span_label(lo, "unexpected `+`"); . . // a block on the LHS might have been intended to be an expression instead . if let Some(sp) = this.sess.ambiguous_block_expr_parse.borrow().get(&lo) { . this.sess.expr_parentheses_needed(&mut err, *sp); -- line 562 ---------------------------------------- -- line 568 ---------------------------------------- . Applicability::MachineApplicable, . ); . } . err.emit(); . . this.bump(); . this.parse_prefix_expr(None) . } // `+expr` 156 ( 0.00%) token::Ident(..) if this.token.is_keyword(kw::Box) => { . make_it!(this, attrs, |this, _| this.parse_box_expr(lo)) . } . token::Ident(..) if this.is_mistaken_not_ident_negation() => { . make_it!(this, attrs, |this, _| this.recover_not_expr(lo)) . } . _ => return this.parse_dot_or_call_expr(Some(attrs)), . } 32,900 ( 0.02%) } . . fn parse_prefix_expr_common(&mut self, lo: Span) -> PResult<'a, (Span, P)> { . self.bump(); . let expr = self.parse_prefix_expr(None); . let (span, expr) = self.interpolated_or_expr_span(expr)?; . Ok((lo.to(span), expr)) . } . -- line 592 ---------------------------------------- -- line 619 ---------------------------------------- . fn is_mistaken_not_ident_negation(&self) -> bool { . let token_cannot_continue_expr = |t: &Token| match t.uninterpolate().kind { . // These tokens can start an expression after `!`, but . // can't continue an expression after an ident . token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw), . token::Literal(..) | token::Pound => true, . _ => t.is_whole_expr(), . }; 156 ( 0.00%) self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr) . } . . /// Recover on `not expr` in favor of `!expr`. . fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> { . // Emit the error... . let not_token = self.look_ahead(1, |t| t.clone()); . self.struct_span_err( . not_token.span, -- line 635 ---------------------------------------- -- line 651 ---------------------------------------- . . /// Returns the span of expr, if it was not interpolated or the span of the interpolated token. . fn interpolated_or_expr_span( . &self, . expr: PResult<'a, P>, . ) -> PResult<'a, (Span, P)> { . expr.map(|e| { . ( 13,161 ( 0.01%) match self.prev_token.kind { . TokenKind::Interpolated(..) => self.prev_token.span, . _ => e.span, . }, . e, . ) . }) . } . 28 ( 0.00%) fn parse_assoc_op_cast( . &mut self, . lhs: P, . lhs_span: Span, . expr_kind: fn(P, P) -> ExprKind, . ) -> PResult<'a, P> { . let mk_expr = |this: &mut Self, lhs: P, rhs: P| { . this.mk_expr( . this.mk_expr_sp(&lhs, lhs_span, rhs.span), 6 ( 0.00%) expr_kind(lhs, rhs), . AttrVec::new(), . ) . }; . . // Save the state of the parser before parsing type normally, in case there is a . // LessThan comparison after this cast. 4 ( 0.00%) let parser_snapshot_before_type = self.clone(); 6 ( 0.00%) let cast_expr = match self.parse_as_cast_ty() { . Ok(rhs) => mk_expr(self, lhs, rhs), . Err(mut type_err) => { . // Rewind to before attempting to parse the type with generics, to recover . // from situations like `x as usize < y` in which we first tried to parse . // `usize < y` as a type with generic arguments. . let parser_snapshot_after_type = mem::replace(self, parser_snapshot_before_type); . . // Check for typo of `'a: loop { break 'a }` with a missing `'`. -- line 693 ---------------------------------------- -- line 779 ---------------------------------------- . *self = parser_snapshot_after_type; . return Err(type_err); . } . } . } . }; . . self.parse_and_disallow_postfix_after_cast(cast_expr) 24 ( 0.00%) } . . /// Parses a postfix operators such as `.`, `?`, or index (`[]`) after a cast, . /// then emits an error and returns the newly parsed tree. . /// The resulting parse tree for `&x as T[0]` has a precedence of `((&x) as T)[0]`. . fn parse_and_disallow_postfix_after_cast( . &mut self, . cast_expr: P, . ) -> PResult<'a, P> { . // Save the memory location of expr before parsing any following postfix operators. . // This will be compared with the memory location of the output expression. . // If they different we can assume we parsed another expression because the existing expression is not reallocated. . let addr_before = &*cast_expr as *const _ as usize; . let span = cast_expr.span; 12 ( 0.00%) let with_postfix = self.parse_dot_or_call_expr_with_(cast_expr, span)?; . let changed = addr_before != &*with_postfix as *const _ as usize; . . // Check if an illegal postfix operator has been added after the cast. . // If the resulting expression is not a cast, or has a different memory location, it is an illegal postfix operator. 12 ( 0.00%) if !matches!(with_postfix.kind, ExprKind::Cast(_, _) | ExprKind::Type(_, _)) || changed { . let msg = format!( . "casts cannot be followed by {}", . match with_postfix.kind { . ExprKind::Index(_, _) => "indexing", . ExprKind::Try(_) => "`?`", . ExprKind::Field(_, _) => "a field access", . ExprKind::MethodCall(_, _, _) => "a method call", . ExprKind::Call(_, _) => "a function call", -- line 814 ---------------------------------------- -- line 844 ---------------------------------------- . let lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?; . self.sess.gated_spans.gate(sym::type_ascription, lhs.span); . Ok(lhs) . } . . /// Parse `& mut? ` or `& raw [ const | mut ] `. . fn parse_borrow_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> { . self.expect_and()?; 5 ( 0.00%) let has_lifetime = self.token.is_lifetime() && self.look_ahead(1, |t| t != &token::Colon); . let lifetime = has_lifetime.then(|| self.expect_lifetime()); // For recovery, see below. . let (borrow_kind, mutbl) = self.parse_borrow_modifiers(lo); 4 ( 0.00%) let expr = self.parse_prefix_expr(None); 2 ( 0.00%) let (hi, expr) = self.interpolated_or_expr_span(expr)?; 1 ( 0.00%) let span = lo.to(hi); 2 ( 0.00%) if let Some(lt) = lifetime { . self.error_remove_borrow_lifetime(span, lt.ident.span); . } . Ok((span, ExprKind::AddrOf(borrow_kind, mutbl, expr))) . } . . fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) { . self.struct_span_err(span, "borrow expressions cannot be annotated with lifetimes") . .span_label(lt_span, "annotated with lifetime here") -- line 866 ---------------------------------------- -- line 870 ---------------------------------------- . String::new(), . Applicability::MachineApplicable, . ) . .emit(); . } . . /// Parse `mut?` or `raw [ const | mut ]`. . fn parse_borrow_modifiers(&mut self, lo: Span) -> (ast::BorrowKind, ast::Mutability) { 2 ( 0.00%) if self.check_keyword(kw::Raw) && self.look_ahead(1, Token::is_mutability) { . // `raw [ const | mut ]`. . let found_raw = self.eat_keyword(kw::Raw); . assert!(found_raw); . let mutability = self.parse_const_or_mut().unwrap(); . self.sess.gated_spans.gate(sym::raw_ref_op, lo.to(self.prev_token.span)); . (ast::BorrowKind::Raw, mutability) . } else { . // `mut?` -- line 886 ---------------------------------------- -- line 889 ---------------------------------------- . } . . /// Parses `a.b` or `a(13)` or `a[4]` or just `a`. . fn parse_dot_or_call_expr(&mut self, attrs: Option) -> PResult<'a, P> { . let attrs = self.parse_or_use_outer_attributes(attrs)?; . self.collect_tokens_for_expr(attrs, |this, attrs| { . let base = this.parse_bottom_expr(); . let (span, base) = this.interpolated_or_expr_span(base)?; 13,156 ( 0.01%) this.parse_dot_or_call_expr_with(base, span, attrs) . }) . } . . pub(super) fn parse_dot_or_call_expr_with( . &mut self, . e0: P, . lo: Span, . mut attrs: Vec, . ) -> PResult<'a, P> { . // Stitch the list of outer attributes onto the return value. . // A little bit ugly, but the best way given the current code . // structure 23,086 ( 0.01%) self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| { 23,086 ( 0.01%) expr.map(|mut expr| { 3,298 ( 0.00%) attrs.extend::>(expr.attrs.into()); 6,596 ( 0.00%) expr.attrs = attrs.into(); 46,172 ( 0.02%) expr . }) . }) . } . 102,300 ( 0.05%) fn parse_dot_or_call_expr_with_(&mut self, mut e: P, lo: Span) -> PResult<'a, P> { . loop { . if self.eat(&token::Question) { . // `expr?` . e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e), AttrVec::new()); . continue; . } . if self.eat(&token::Dot) { . // expr.f 36 ( 0.00%) e = self.parse_dot_suffix_expr(lo, e)?; . continue; . } 50 ( 0.00%) if self.expr_is_complete(&e) { . return Ok(e); . } 6,697 ( 0.00%) e = match self.token.kind { 24 ( 0.00%) token::OpenDelim(token::Paren) => self.parse_fn_call_expr(lo, e), 2 ( 0.00%) token::OpenDelim(token::Bracket) => self.parse_index_expr(lo, e)?, 3,295 ( 0.00%) _ => return Ok(e), . } . } 29,700 ( 0.02%) } . . fn look_ahead_type_ascription_as_field(&mut self) -> bool { 45 ( 0.00%) self.look_ahead(1, |t| t.is_ident()) . && self.look_ahead(2, |t| t == &token::Colon) . && self.look_ahead(3, |t| t.can_begin_expr()) . } . . fn parse_dot_suffix_expr(&mut self, lo: Span, base: P) -> PResult<'a, P> { 99 ( 0.00%) match self.token.uninterpolate().kind { . token::Ident(..) => self.parse_dot_suffix(base, lo), . token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => { . Ok(self.parse_tuple_field_access_expr(lo, base, symbol, suffix, None)) . } . token::Literal(token::Lit { kind: token::Float, symbol, suffix }) => { . Ok(self.parse_tuple_field_access_expr_float(lo, base, symbol, suffix)) . } . _ => { -- line 957 ---------------------------------------- -- line 1091 ---------------------------------------- . let span = self.prev_token.span; . let field = ExprKind::Field(base, Ident::new(field, span)); . self.expect_no_suffix(span, "a tuple index", suffix); . self.mk_expr(lo.to(span), field, AttrVec::new()) . } . . /// Parse a function call expression, `expr(...)`. . fn parse_fn_call_expr(&mut self, lo: Span, fun: P) -> P { 40 ( 0.00%) let snapshot = if self.token.kind == token::OpenDelim(token::Paren) . && self.look_ahead_type_ascription_as_field() . { . Some((self.clone(), fun.kind.clone())) . } else { 24 ( 0.00%) None . }; 8 ( 0.00%) let open_paren = self.token.span; . 16 ( 0.00%) let mut seq = self.parse_paren_expr_seq().map(|args| { 24 ( 0.00%) self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args), AttrVec::new()) . }); . if let Some(expr) = . self.maybe_recover_struct_lit_bad_delims(lo, open_paren, &mut seq, snapshot) . { . return expr; . } 40 ( 0.00%) self.recover_seq_parse_error(token::Paren, lo, seq) . } . . /// If we encounter a parser state that looks like the user has written a `struct` literal with . /// parentheses instead of braces, recover the parser state and provide suggestions. . #[instrument(skip(self, seq, snapshot), level = "trace")] . fn maybe_recover_struct_lit_bad_delims( . &mut self, . lo: Span, . open_paren: Span, . seq: &mut PResult<'a, P>, . snapshot: Option<(Self, ExprKind)>, . ) -> Option> { 80 ( 0.00%) match (seq.as_mut(), snapshot) { . (Err(ref mut err), Some((mut snapshot, ExprKind::Path(None, path)))) => { . let name = pprust::path_to_string(&path); . snapshot.bump(); // `(` . match snapshot.parse_struct_fields(path, false, token::Paren) { . Ok((fields, ..)) if snapshot.eat(&token::CloseDelim(token::Paren)) => { . // We are certain we have `Enum::Foo(a: 3, b: 4)`, suggest . // `Enum::Foo { a: 3, b: 4 }` or `Enum::Foo(3, 4)`. . *self = snapshot; -- line 1137 ---------------------------------------- -- line 1165 ---------------------------------------- . } . return Some(self.mk_expr_err(span)); . } . Ok(_) => {} . Err(mut err) => err.emit(), . } . } . _ => {} 24 ( 0.00%) } . None . } . . /// Parse an indexing expression `expr[...]`. . fn parse_index_expr(&mut self, lo: Span, base: P) -> PResult<'a, P> { 2 ( 0.00%) self.bump(); // `[` 2 ( 0.00%) let index = self.parse_expr()?; 3 ( 0.00%) self.expect(&token::CloseDelim(token::Bracket))?; 3 ( 0.00%) Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_index(base, index), AttrVec::new())) . } . . /// Assuming we have just parsed `.`, continue parsing into an expression. . fn parse_dot_suffix(&mut self, self_arg: P, lo: Span) -> PResult<'a, P> { 18 ( 0.00%) if self.token.uninterpolated_span().rust_2018() && self.eat_keyword(kw::Await) { . return Ok(self.mk_await_expr(self_arg, lo)); . } . 9 ( 0.00%) let fn_span_lo = self.token.span; 54 ( 0.00%) let mut segment = self.parse_path_segment(PathStyle::Expr, None)?; 45 ( 0.00%) self.check_trailing_angle_brackets(&segment, &[&token::OpenDelim(token::Paren)]); . self.check_turbofish_missing_angle_brackets(&mut segment); . 45 ( 0.00%) if self.check(&token::OpenDelim(token::Paren)) { . // Method call `expr.f()` 9 ( 0.00%) let mut args = self.parse_paren_expr_seq()?; 36 ( 0.00%) args.insert(0, self_arg); . 27 ( 0.00%) let fn_span = fn_span_lo.to(self.prev_token.span); 27 ( 0.00%) let span = lo.to(self.prev_token.span); 45 ( 0.00%) Ok(self.mk_expr(span, ExprKind::MethodCall(segment, args, fn_span), AttrVec::new())) . } else { . // Field access `expr.f` . if let Some(args) = segment.args { . self.struct_span_err( . args.span(), . "field expressions cannot have generic arguments", . ) . .emit(); -- line 1211 ---------------------------------------- -- line 1217 ---------------------------------------- . } . . /// At the bottom (top?) of the precedence hierarchy, . /// Parses things like parenthesized exprs, macros, `return`, etc. . /// . /// N.B., this does not parse outer attributes, and is private because it only works . /// correctly if called from `parse_dot_or_call_expr()`. . fn parse_bottom_expr(&mut self) -> PResult<'a, P> { 7,253 ( 0.00%) maybe_recover_from_interpolated_ty_qpath!(self, true); 9,867 ( 0.00%) maybe_whole_expr!(self); . . // Outer attributes are already parsed and will be . // added to the return value after the fact. . // . // Therefore, prevent sub-parser from parsing . // attributes by giving them an empty "already-parsed" list. 3,289 ( 0.00%) let attrs = AttrVec::new(); . . // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`. 692 ( 0.00%) let lo = self.token.span; 9,867 ( 0.00%) if let token::Literal(_) = self.token.kind { . // This match arm is a special-case of the `_` match arm below and . // could be removed without changing functionality, but it's faster . // to have it here, especially for programs with large constants. 10,388 ( 0.01%) self.parse_lit_expr(attrs) 3,460 ( 0.00%) } else if self.check(&token::OpenDelim(token::Paren)) { 1,941 ( 0.00%) self.parse_tuple_parens_expr(attrs) 225 ( 0.00%) } else if self.check(&token::OpenDelim(token::Brace)) { 16 ( 0.00%) self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs) 415 ( 0.00%) } else if self.check(&token::BinOp(token::Or)) || self.check(&token::OrOr) { 12 ( 0.00%) self.parse_closure_expr(attrs) 200 ( 0.00%) } else if self.check(&token::OpenDelim(token::Bracket)) { 5 ( 0.00%) self.parse_array_or_repeat_expr(attrs, token::Bracket) 156 ( 0.00%) } else if self.check_path() { 124 ( 0.00%) self.parse_path_start_expr(attrs) 80 ( 0.00%) } else if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) { . self.parse_closure_expr(attrs) 40 ( 0.00%) } else if self.eat_keyword(kw::If) { 8 ( 0.00%) self.parse_if_expr(attrs) 30 ( 0.00%) } else if self.check_keyword(kw::For) { . if self.choose_generics_over_qpath(1) { . // NOTE(Centril, eddyb): DO NOT REMOVE! Beyond providing parser recovery, . // this is an insurance policy in case we allow qpaths in (tuple-)struct patterns. . // When `for ::Proj in $expr $block` is wanted, . // you can disambiguate in favor of a pattern with `(...)`. . self.recover_quantified_closure_expr(attrs) . } else { . assert!(self.eat_keyword(kw::For)); . self.parse_for_expr(None, self.prev_token.span, attrs) . } 30 ( 0.00%) } else if self.eat_keyword(kw::While) { . self.parse_while_expr(None, self.prev_token.span, attrs) 24 ( 0.00%) } else if let Some(label) = self.eat_label() { . self.parse_labeled_expr(label, attrs, true) 30 ( 0.00%) } else if self.eat_keyword(kw::Loop) { . self.parse_loop_expr(None, self.prev_token.span, attrs) 30 ( 0.00%) } else if self.eat_keyword(kw::Continue) { . let kind = ExprKind::Continue(self.eat_label()); . Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs)) 24 ( 0.00%) } else if self.eat_keyword(kw::Match) { 4 ( 0.00%) let match_sp = self.prev_token.span; 16 ( 0.00%) self.parse_match_expr(attrs).map_err(|mut err| { . err.span_label(match_sp, "while parsing this match expression"); . err . }) 16 ( 0.00%) } else if self.eat_keyword(kw::Unsafe) { . self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided), attrs) 16 ( 0.00%) } else if self.check_inline_const(0) { . self.parse_const_block(lo.to(self.token.span), false) 12 ( 0.00%) } else if self.is_do_catch_block() { . self.recover_do_catch(attrs) 12 ( 0.00%) } else if self.is_try_block() { . self.expect_keyword(kw::Try)?; . self.parse_try_block(lo, attrs) 16 ( 0.00%) } else if self.eat_keyword(kw::Return) { . self.parse_return_expr(attrs) 16 ( 0.00%) } else if self.eat_keyword(kw::Break) { . self.parse_break_expr(attrs) 16 ( 0.00%) } else if self.eat_keyword(kw::Yield) { . self.parse_yield_expr(attrs) 16 ( 0.00%) } else if self.eat_keyword(kw::Let) { . self.parse_let_expr(attrs) 16 ( 0.00%) } else if self.eat_keyword(kw::Underscore) { . Ok(self.mk_expr(self.prev_token.span, ExprKind::Underscore, attrs)) 4 ( 0.00%) } else if !self.unclosed_delims.is_empty() && self.check(&token::Semi) { . // Don't complain about bare semicolons after unclosed braces . // recovery in order to keep the error count down. Fixing the . // delimiters will possibly also fix the bare semicolon found in . // expression context. For example, silence the following error: . // . // error: expected expression, found `;` . // --> file.rs:2:13 . // | . // 2 | foo(bar(; . // | ^ expected expression . self.bump(); . Ok(self.mk_expr_err(self.token.span)) 8 ( 0.00%) } else if self.token.uninterpolated_span().rust_2018() { . // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly. . if self.check_keyword(kw::Async) { . if self.is_async_block() { . // Check for `async {` and `async move {`. . self.parse_async_block(attrs) . } else { . self.parse_closure_expr(attrs) . } . } else if self.eat_keyword(kw::Await) { . self.recover_incorrect_await_syntax(lo, self.prev_token.span, attrs) . } else { . self.parse_lit_expr(attrs) . } . } else { 16 ( 0.00%) self.parse_lit_expr(attrs) . } . } . 26,010 ( 0.01%) fn parse_lit_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { 5,202 ( 0.00%) let lo = self.token.span; 10,404 ( 0.01%) match self.parse_opt_lit() { 15,606 ( 0.01%) Some(literal) => { 23,409 ( 0.01%) let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(literal), attrs); 26,010 ( 0.01%) self.maybe_recover_from_bad_qpath(expr, true) . } . None => self.try_macro_suggestion(), . } . } . . fn parse_tuple_parens_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { 1,294 ( 0.00%) let lo = self.token.span; 1,941 ( 0.00%) self.expect(&token::OpenDelim(token::Paren))?; . let (es, trailing_comma) = match self.parse_seq_to_end( . &token::CloseDelim(token::Paren), . SeqSep::trailing_allowed(token::Comma), 5,174 ( 0.00%) |p| p.parse_expr_catch_underscore(), . ) { . Ok(x) => x, . Err(err) => return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err))), . }; 3,235 ( 0.00%) let kind = if es.len() == 1 && !trailing_comma { . // `(e)` is parenthesized `e`. . ExprKind::Paren(es.into_iter().next().unwrap()) . } else { . // `(e,)` is a tuple with only one field, `e`. 3,235 ( 0.00%) ExprKind::Tup(es) . }; 1,941 ( 0.00%) let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs); 1,941 ( 0.00%) self.maybe_recover_from_bad_qpath(expr, true) . } . 11 ( 0.00%) fn parse_array_or_repeat_expr( . &mut self, . attrs: AttrVec, . close_delim: token::DelimToken, . ) -> PResult<'a, P> { 3 ( 0.00%) let lo = self.token.span; 1 ( 0.00%) self.bump(); // `[` or other open delim . 3 ( 0.00%) let close = &token::CloseDelim(close_delim); . let kind = if self.eat(close) { . // Empty vector . ExprKind::Array(Vec::new()) . } else { . // Non-empty vector 2 ( 0.00%) let first_expr = self.parse_expr()?; . if self.eat(&token::Semi) { . // Repeating array syntax: `[ 0; 512 ]` . let count = self.parse_anon_const_expr()?; . self.expect(close)?; . ExprKind::Repeat(first_expr, count) . } else if self.eat(&token::Comma) { . // Vector with two or more elements. . let sep = SeqSep::trailing_allowed(token::Comma); . let (remaining_exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?; 1 ( 0.00%) let mut exprs = vec![first_expr]; . exprs.extend(remaining_exprs); 5 ( 0.00%) ExprKind::Array(exprs) . } else { . // Vector with one element . self.expect(close)?; . ExprKind::Array(vec![first_expr]) . } . }; 3 ( 0.00%) let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs); 3 ( 0.00%) self.maybe_recover_from_bad_qpath(expr, true) 10 ( 0.00%) } . 310 ( 0.00%) fn parse_path_start_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { 248 ( 0.00%) let (qself, path) = if self.eat_lt() { . let (qself, path) = self.parse_qpath(PathStyle::Expr)?; . (Some(qself), path) . } else { 62 ( 0.00%) (None, self.parse_path(PathStyle::Expr)?) . }; 31 ( 0.00%) let lo = path.span; . . // `!`, as an operator, is prefix, so we know this isn't that. 465 ( 0.00%) let (hi, kind) = if self.eat(&token::Not) { . // MACRO INVOCATION expression . if qself.is_some() { . self.struct_span_err(path.span, "macros cannot use qualified paths").emit(); . } . let mac = MacCall { . path, . args: self.parse_mac_args()?, . prior_type_ascription: self.last_type_ascription, . }; . (self.prev_token.span, ExprKind::MacCall(mac)) 155 ( 0.00%) } else if self.check(&token::OpenDelim(token::Brace)) { . if let Some(expr) = self.maybe_parse_struct_expr(qself.as_ref(), &path, &attrs) { . if qself.is_some() { . self.sess.gated_spans.gate(sym::more_qualified_paths, path.span); . } . return expr; . } else { . (path.span, ExprKind::Path(qself, path)) . } . } else { . (path.span, ExprKind::Path(qself, path)) . }; . 62 ( 0.00%) let expr = self.mk_expr(lo.to(hi), kind, attrs); 93 ( 0.00%) self.maybe_recover_from_bad_qpath(expr, true) 372 ( 0.00%) } . . /// Parse `'label: $expr`. The label is already parsed. . fn parse_labeled_expr( . &mut self, . label: Label, . attrs: AttrVec, . mut consume_colon: bool, . ) -> PResult<'a, P> { -- line 1447 ---------------------------------------- -- line 1607 ---------------------------------------- . symbol_unescaped, . }), . _ => Err(Some(lit)), . }, . None => Err(None), . } . } . 153 ( 0.00%) pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> { 17 ( 0.00%) self.parse_opt_lit().ok_or_else(|| { 20 ( 0.00%) if let token::Interpolated(inner) = &self.token.kind { . let expr = match inner.as_ref() { . token::NtExpr(expr) => Some(expr), . token::NtLiteral(expr) => Some(expr), . _ => None, . }; . if let Some(expr) = expr { . if matches!(expr.kind, ExprKind::Err) { . self.diagnostic() . .delay_span_bug(self.token.span, &"invalid interpolated expression"); . return self.diagnostic().struct_dummy(); . } . } . } 110 ( 0.00%) let msg = format!("unexpected token: {}", super::token_descr(&self.token)); 10 ( 0.00%) self.struct_span_err(self.token.span, &msg) . }) 119 ( 0.00%) } . . /// Matches `lit = true | false | token_lit`. . /// Returns `None` if the next token is not a literal. 23,562 ( 0.01%) pub(super) fn parse_opt_lit(&mut self) -> Option { 2,618 ( 0.00%) let mut recovered = None; 15,708 ( 0.01%) if self.token == token::Dot { . // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where . // dot would follow an optional literal, so we do this unconditionally. . recovered = self.look_ahead(1, |next_token| { . if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = . next_token.kind . { . if self.token.span.hi() == next_token.span.lo() { . let s = String::from("0.") + symbol.as_str(); -- line 1648 ---------------------------------------- -- line 1654 ---------------------------------------- . }); . if let Some(token) = &recovered { . self.bump(); . self.error_float_lits_must_have_int_part(&token); . } . } . . let token = recovered.as_ref().unwrap_or(&self.token); 7,884 ( 0.00%) match Lit::from_token(token) { 15,648 ( 0.01%) Ok(lit) => { 5,216 ( 0.00%) self.bump(); 15,648 ( 0.01%) Some(lit) . } 10 ( 0.00%) Err(LitError::NotLiteral) => None, . Err(err) => { . let span = token.span; . let lit = match token.kind { . token::Literal(lit) => lit, . _ => unreachable!(), . }; . self.bump(); . self.report_lit_error(err, lit, span); -- line 1675 ---------------------------------------- -- line 1676 ---------------------------------------- . // Pack possible quotes and prefixes from the original literal into . // the error literal's symbol so they can be pretty-printed faithfully. . let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None); . let symbol = Symbol::intern(&suffixless_lit.to_string()); . let lit = token::Lit::new(token::Err, symbol, lit.suffix); . Some(Lit::from_lit_token(lit, span).unwrap_or_else(|_| unreachable!())) . } . } 20,944 ( 0.01%) } . . fn error_float_lits_must_have_int_part(&self, token: &Token) { . self.struct_span_err(token.span, "float literals must have an integer part") . .span_suggestion( . token.span, . "must have an integer part", . pprust::token_to_string(token).into(), . Applicability::MachineApplicable, -- line 1692 ---------------------------------------- -- line 1795 ---------------------------------------- . }; . err.span_label(sp, format!("invalid suffix `{}`", suf)); . err.emit(); . } . } . . /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`). . /// Keep this in sync with `Token::can_begin_literal_maybe_minus`. 8 ( 0.00%) pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P> { 2 ( 0.00%) maybe_whole_expr!(self); . 1 ( 0.00%) let lo = self.token.span; . let minus_present = self.eat(&token::BinOp(token::Minus)); 2 ( 0.00%) let lit = self.parse_lit()?; 1 ( 0.00%) let expr = self.mk_expr(lit.span, ExprKind::Lit(lit), AttrVec::new()); . 2 ( 0.00%) if minus_present { . Ok(self.mk_expr( . lo.to(self.prev_token.span), . self.mk_unary(UnOp::Neg, expr), . AttrVec::new(), . )) . } else { . Ok(expr) . } 9 ( 0.00%) } . . fn is_array_like_block(&mut self) -> bool { 7 ( 0.00%) self.look_ahead(1, |t| matches!(t.kind, TokenKind::Ident(..) | TokenKind::Literal(_))) . && self.look_ahead(2, |t| t == &token::Comma) . && self.look_ahead(3, |t| t.can_begin_expr()) . } . . /// Emits a suggestion if it looks like the user meant an array but . /// accidentally used braces, causing the code to be interpreted as a block . /// expression. . fn maybe_suggest_brackets_instead_of_braces( -- line 1831 ---------------------------------------- -- line 1855 ---------------------------------------- . Err(mut e) => { . e.cancel(); . None . } . } . } . . /// Parses a block or unsafe block. 28 ( 0.00%) pub(super) fn parse_block_expr( . &mut self, . opt_label: Option { . #[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 { 580 ( 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) { 735 ( 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::() . ); 15,699 ( 0.01%) 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 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 { 2 ( 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); . 3 ( 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(), 63 ( 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 { 28 ( 0.00%) assert!(len <= A::size()); 84 ( 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 { 14 ( 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(); 4,091 ( 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 { 3,277 ( 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 { 94,861 ( 0.05%) 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 { 261,925 ( 0.13%) if self.spilled() { 3,870 ( 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 { 230,731 ( 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] 715 ( 0.00%) pub fn push(&mut self, value: A::Item) { . unsafe { . let (mut ptr, mut len, cap) = self.triple_mut(); 28,618 ( 0.01%) if *len == cap { 10 ( 0.00%) self.reserve(1); 754 ( 0.00%) let &mut (heap_ptr, ref mut heap_len) = self.data.heap_mut(); . ptr = heap_ptr; . len = heap_len; . } 1,384 ( 0.00%) ptr::write(ptr.add(*len), value); 53,329 ( 0.03%) *len += 1; . } 572 ( 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(); 20,844 ( 0.01%) if *len_ptr == 0 { . return None; . } 6,512 ( 0.00%) let last_index = *len_ptr - 1; 6,514 ( 0.00%) *len_ptr = last_index; 6,488 ( 0.00%) Some(ptr::read(ptr.add(last_index))) . } . } . . /// Moves all the elements of `other` into `self`, leaving `other` empty. . /// . /// # Example . /// . /// ``` -- line 861 ---------------------------------------- -- 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 7 ( 0.00%) pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> { . unsafe { 1 ( 0.00%) let (ptr, &mut len, cap) = self.triple_mut(); . let unspilled = !self.spilled(); 1,480 ( 0.00%) assert!(new_cap >= len); 1,480 ( 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); 1,480 ( 0.00%) } else if new_cap != cap { 1,456 ( 0.00%) let layout = layout_array::(new_cap)?; . debug_assert!(layout.size() > 0); . let new_alloc; 740 ( 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`. 42 ( 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(); . } 1,480 ( 0.00%) self.data = SmallVecData::from_heap(new_alloc, len); 2,172 ( 0.00%) self.capacity = new_cap; . } . Ok(()) . } 8 ( 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] 16,197 ( 0.01%) pub fn reserve(&mut self, additional: usize) { 18,817 ( 0.01%) infallible(self.try_reserve(additional)) 18,488 ( 0.01%) } . . /// Reserve capacity for `additional` more elements to be inserted. . /// . /// May reserve more space to avoid frequent reallocations. 59,961 ( 0.03%) 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() 48 ( 0.00%) let (_, &mut len, cap) = self.triple_mut(); 59,567 ( 0.03%) 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)?; 2 ( 0.00%) self.try_grow(new_cap) 66,061 ( 0.03%) } . . /// Reserve the minimum capacity for `additional` more elements to be inserted. . /// . /// Panics if the new capacity overflows `usize`. . pub fn reserve_exact(&mut self, additional: usize) { . infallible(self.try_reserve_exact(additional)) . } . . /// 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(); 883 ( 0.00%) if cap - len >= additional { . return Ok(()); . } . let new_cap = len . .checked_add(additional) . .ok_or(CollectionAllocErr::CapacityOverflow)?; . self.try_grow(new_cap) . } . -- line 974 ---------------------------------------- -- 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(); 408 ( 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. 4 ( 0.00%) pub fn remove(&mut self, index: usize) -> A::Item { . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 8 ( 0.00%) let len = *len_ptr; 33 ( 0.00%) assert!(index < len); 5,322 ( 0.00%) *len_ptr = len - 1; . ptr = ptr.add(index); . let item = ptr::read(ptr); 22 ( 0.00%) ptr::copy(ptr.add(1), ptr, len - index - 1); . item . } 5 ( 0.00%) } . . /// Insert an element at position `index`, shifting all elements after it to the right. . /// . /// Panics if `index` is out of bounds. 251 ( 0.00%) pub fn insert(&mut self, index: usize, element: A::Item) { . self.reserve(1); . . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 23 ( 0.00%) let len = *len_ptr; 46 ( 0.00%) assert!(index <= len); 92 ( 0.00%) *len_ptr = len + 1; . ptr = ptr.add(index); 46 ( 0.00%) ptr::copy(ptr, ptr.add(1), len - index); . ptr::write(ptr, element); . } 162 ( 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. 909 ( 0.00%) pub fn retain bool>(&mut self, mut f: F) { . let mut del = 0; . let len = self.len(); . for i in 0..len { 436 ( 0.00%) if !f(&mut self[i]) { 64 ( 0.00%) del += 1; 94 ( 0.00%) } else if del > 0 { 48 ( 0.00%) self.swap(i - del, i); . } . } 202 ( 0.00%) self.truncate(len - del); 808 ( 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, . ); 26 ( 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`. 2,514 ( 0.00%) pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) { . self.reserve(slice.len()); . . let len = self.len(); 753 ( 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()); 502 ( 0.00%) self.set_len(len + slice.len()); . } 2,008 ( 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(); 678 ( 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`. -- line 1473 ---------------------------------------- -- line 1522 ---------------------------------------- . } . } . } . . impl ops::DerefMut for SmallVec { . #[inline] . fn deref_mut(&mut self) -> &mut [A::Item] { . unsafe { 116 ( 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 1716 ---------------------------------------- . SmallVec::extend_from_slice(self, other) . } . } . . impl FromIterator for SmallVec { . #[inline] . fn from_iter>(iterable: I) -> SmallVec { . let mut v = SmallVec::new(); 39,295 ( 0.02%) v.extend(iterable); . v . } . } . . impl Extend for SmallVec { 93,445 ( 0.05%) fn extend>(&mut self, iterable: I) { 27,914 ( 0.01%) let mut iter = iterable.into_iter(); . let (lower_size_bound, _) = iter.size_hint(); 3,753 ( 0.00%) self.reserve(lower_size_bound); . . unsafe { . let (ptr, len_ptr, cap) = self.triple_mut(); . let mut len = SetLenOnDrop::new(len_ptr); 83,197 ( 0.04%) while len.get() < cap { 23,134 ( 0.01%) if let Some(out) = iter.next() { . ptr::write(ptr.add(len.get()), out); . len.increment_len(1); . } else { . return; . } . } . } . 1,766 ( 0.00%) for elem in iter { 168 ( 0.00%) self.push(elem); . } 85,839 ( 0.04%) } . } . . 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 { 23,711 ( 0.01%) fn drop(&mut self) { . unsafe { 54,399 ( 0.03%) if self.spilled() { . let (ptr, len) = self.data.heap(); . Vec::from_raw_parts(ptr, len, self.capacity); . } else { . ptr::drop_in_place(&mut self[..]); . } . } 23,629 ( 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 { 79 ( 0.00%) fn drop(&mut self) { 717 ( 0.00%) for _ in self {} 72 ( 0.00%) } . } . . impl Iterator for IntoIter { . type Item = A::Item; . . #[inline] . fn next(&mut self) -> Option { 24,523 ( 0.01%) if self.current == self.end { . None . } else { . unsafe { . let current = self.current; 2,017 ( 0.00%) self.current += 1; 81 ( 0.00%) Some(ptr::read(self.data.as_ptr().add(current))) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 103 ( 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); 8,027 ( 0.00%) IntoIter { 17,907 ( 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 { 14,049 ( 0.01%) local_len: *len, . len, . } . } . . #[inline] . fn get(&self) -> usize { . self.local_len . } . . #[inline] . fn increment_len(&mut self, increment: usize) { 21,894 ( 0.01%) self.local_len += increment; . } . } . . impl<'a> Drop for SetLenOnDrop<'a> { . #[inline] . fn drop(&mut self) { 21,403 ( 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 ---------------------------------------- 149,574 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/expr.rs -------------------------------------------------------------------------------- Ir -- line 56 ---------------------------------------- . } . . pub fn check_expr_has_type_or_error( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Ty<'tcx>, . extend_err: impl Fn(&mut DiagnosticBuilder<'_>), . ) -> Ty<'tcx> { 6 ( 0.00%) self.check_expr_meets_expectation_or_error(expr, ExpectHasType(expected), extend_err) . } . . fn check_expr_meets_expectation_or_error( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Expectation<'tcx>, . extend_err: impl Fn(&mut DiagnosticBuilder<'_>), . ) -> Ty<'tcx> { . let expected_ty = expected.to_option(&self).unwrap_or(self.tcx.types.bool); . let mut ty = self.check_expr_with_expectation(expr, expected); . . // While we don't allow *arbitrary* coercions here, we *do* allow . // coercions from ! to `expected`. 8 ( 0.00%) if ty.is_never() { . assert!( . !self.typeck_results.borrow().adjustments().contains_key(expr.hir_id), . "expression with never type wound up being adjusted" . ); . let adj_ty = self.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::AdjustmentType, . span: expr.span, . }); . self.apply_adjustments( . expr, . vec![Adjustment { kind: Adjust::NeverToAny, target: adj_ty }], . ); . ty = adj_ty; . } . 62 ( 0.00%) if let Some(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) { . let expr = expr.peel_drop_temps(); . self.suggest_deref_ref_or_into(&mut err, expr, expected_ty, ty, None); . extend_err(&mut err); . err.emit(); . } . ty . } . 23,382 ( 0.01%) pub(super) fn check_expr_coercable_to_type( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Ty<'tcx>, . expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>, . ) -> Ty<'tcx> { . let ty = self.check_expr_with_hint(expr, expected); . // checks don't need two phase . self.demand_coerce(expr, ty, expected, expected_ty_expr, AllowTwoPhase::No) 18,186 ( 0.01%) } . . pub(super) fn check_expr_with_hint( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Ty<'tcx>, . ) -> Ty<'tcx> { 9 ( 0.00%) self.check_expr_with_expectation(expr, ExpectHasType(expected)) . } . . fn check_expr_with_expectation_and_needs( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Expectation<'tcx>, . needs: Needs, . ) -> Ty<'tcx> { . let ty = self.check_expr_with_expectation(expr, expected); . . // If the expression is used in a place whether mutable place is required . // e.g. LHS of assignment, perform the conversion. 1 ( 0.00%) if let Needs::MutPlace = needs { . self.convert_place_derefs_to_mutable(expr); . } . . ty . } . . pub(super) fn check_expr(&self, expr: &'tcx hir::Expr<'tcx>) -> Ty<'tcx> { . self.check_expr_with_expectation(expr, NoExpectation) -- line 140 ---------------------------------------- -- line 159 ---------------------------------------- . /// that there are actually multiple representations for `Error`, so avoid . /// that when err needs to be handled differently. . #[instrument(skip(self, expr), level = "debug")] . pub(super) fn check_expr_with_expectation( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Expectation<'tcx>, . ) -> Ty<'tcx> { 18,055 ( 0.01%) self.check_expr_with_expectation_and_args(expr, expected, &[]) . } . . /// Same as `check_expr_with_expectation`, but allows us to pass in the arguments of a . /// `ExprKind::Call` when evaluating its callee when it is an `ExprKind::Path`. 43,446 ( 0.02%) pub(super) fn check_expr_with_expectation_and_args( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Expectation<'tcx>, . args: &'tcx [hir::Expr<'tcx>], . ) -> Ty<'tcx> { 13,368 ( 0.01%) if self.tcx().sess.verbose() { . // make this code only run with -Zverbose because it is probably slow . if let Ok(lint_str) = self.tcx.sess.source_map().span_to_snippet(expr.span) { . if !lint_str.contains('\n') { . debug!("expr text: {}", lint_str); . } else { . let mut lines = lint_str.lines(); . if let Some(line0) = lines.next() { . let remaining_lines = lines.count(); -- line 186 ---------------------------------------- -- line 189 ---------------------------------------- . } . } . } . } . . // True if `expr` is a `Try::from_ok(())` that is a result of desugaring a try block . // without the final expr (e.g. `try { return; }`). We don't want to generate an . // unreachable_code lint for it since warnings for autogenerated code are confusing. 6,684 ( 0.00%) let is_try_block_generated_unit_expr = match expr.kind { 40 ( 0.00%) ExprKind::Call(_, args) if expr.span.is_desugaring(DesugaringKind::TryBlock) => { . args.len() == 1 && args[0].span.is_desugaring(DesugaringKind::TryBlock) . } . . _ => false, . }; . . // Warn for expressions after diverging siblings. . if !is_try_block_generated_unit_expr { 23,394 ( 0.01%) self.warn_if_unreachable(expr.hir_id, expr.span, "expression"); . } . . // Hide the outer diverging and has_errors flags. . let old_diverges = self.diverges.replace(Diverges::Maybe); . let old_has_errors = self.has_errors.replace(false); . 6,764 ( 0.00%) let ty = ensure_sufficient_stack(|| match &expr.kind { . hir::ExprKind::Path( . qpath @ hir::QPath::Resolved(..) | qpath @ hir::QPath::TypeRelative(..), 240 ( 0.00%) ) => self.check_expr_path(qpath, expr, args), 16,510 ( 0.01%) _ => self.check_expr_kind(expr, expected), . }); . . // Warn for non-block expressions with diverging children. 13,368 ( 0.01%) match expr.kind { . ExprKind::Block(..) . | ExprKind::If(..) . | ExprKind::Let(..) . | ExprKind::Loop(..) . | ExprKind::Match(..) => {} . // If `expr` is a result of desugaring the try block and is an ok-wrapped . // diverging expression (e.g. it arose from desugaring of `try { return }`), . // we skip issuing a warning because it is autogenerated code. 40 ( 0.00%) ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {} 40 ( 0.00%) ExprKind::Call(callee, _) => self.warn_if_unreachable(expr.hir_id, callee.span, "call"), 9 ( 0.00%) ExprKind::MethodCall(segment, ..) => { 27 ( 0.00%) self.warn_if_unreachable(expr.hir_id, segment.ident.span, "call") . } 19,842 ( 0.01%) _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"), . } . . // Any expression that produces a value of type `!` must have diverged 3,342 ( 0.00%) if ty.is_never() { . self.diverges.set(self.diverges.get() | Diverges::always(expr.span)); . } . . // Record the type, which applies it effects. . // We need to do this after the warning above, so that . // we don't warn for the diverging expression itself. 16,710 ( 0.01%) self.write_ty(expr.hir_id, ty); . . // Combine the diverging and has_error flags. . self.diverges.set(self.diverges.get() | old_diverges); 3,342 ( 0.00%) self.has_errors.set(self.has_errors.get() | old_has_errors); . . debug!("type of {} is...", self.tcx.hir().node_to_string(expr.hir_id)); . debug!("... {:?}, expected is {:?}", ty, expected); . . ty 30,078 ( 0.02%) } . 65,761 ( 0.03%) #[instrument(skip(self, expr), level = "debug")] . fn check_expr_kind( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Expectation<'tcx>, . ) -> Ty<'tcx> { . trace!("expr={:#?}", expr); . 3,302 ( 0.00%) let tcx = self.tcx; 19,812 ( 0.01%) match expr.kind { . ExprKind::Box(subexpr) => self.check_expr_box(subexpr, expected), . ExprKind::Lit(ref lit) => self.check_lit(&lit, expected), 98 ( 0.00%) ExprKind::Binary(op, lhs, rhs) => self.check_binop(expr, op, lhs, rhs), . ExprKind::Assign(lhs, rhs, ref span) => { . self.check_expr_assign(expr, expected, lhs, rhs, span) . } . ExprKind::AssignOp(op, lhs, rhs) => self.check_binop_assign(expr, op, lhs, rhs), . ExprKind::Unary(unop, oprnd) => self.check_expr_unary(unop, oprnd, expected, expr), 9 ( 0.00%) ExprKind::AddrOf(kind, mutbl, oprnd) => { . self.check_expr_addr_of(kind, mutbl, oprnd, expected, expr) . } . ExprKind::Path(QPath::LangItem(lang_item, _, hir_id)) => { . self.check_lang_item_path(lang_item, expr, hir_id) . } . ExprKind::Path(ref qpath) => self.check_expr_path(qpath, expr, &[]), . ExprKind::InlineAsm(asm) => self.check_expr_asm(asm), . ExprKind::Break(destination, ref expr_opt) => { -- line 285 ---------------------------------------- -- line 293 ---------------------------------------- . tcx.ty_error() . } . } . ExprKind::Ret(ref expr_opt) => self.check_expr_return(expr_opt.as_deref(), expr), . ExprKind::Let(let_expr) => self.check_expr_let(let_expr), . ExprKind::Loop(body, _, source, _) => { . self.check_expr_loop(body, source, expected, expr) . } 6 ( 0.00%) ExprKind::Match(discrim, arms, match_src) => { 14 ( 0.00%) self.check_match(expr, &discrim, arms, expected, match_src) . } 9 ( 0.00%) ExprKind::Closure(capture, decl, body_id, _, gen) => { 36 ( 0.00%) self.check_expr_closure(expr, capture, &decl, body_id, gen, expected) . } 143 ( 0.00%) ExprKind::Block(body, _) => self.check_block_with_expected(&body, expected), 64 ( 0.00%) ExprKind::Call(callee, args) => self.check_call(expr, &callee, args, expected), 9 ( 0.00%) ExprKind::MethodCall(segment, args, _) => { . self.check_method_call(expr, segment, args, expected) . } 6 ( 0.00%) ExprKind::Cast(e, t) => self.check_expr_cast(e, t, expr), . ExprKind::Type(e, t) => { . let ty = self.to_ty_saving_user_provided_ty(&t); . self.check_expr_eq_type(&e, ty); . ty . } 15 ( 0.00%) ExprKind::If(cond, then_expr, opt_else_expr) => { 3 ( 0.00%) self.check_then_else(cond, then_expr, opt_else_expr, expr.span, expected) . } 3 ( 0.00%) ExprKind::DropTemps(e) => self.check_expr_with_expectation(e, expected), 2 ( 0.00%) ExprKind::Array(args) => self.check_expr_array(args, expected, expr), . ExprKind::ConstBlock(ref anon_const) => { . self.check_expr_const_block(anon_const, expected, expr) . } . ExprKind::Repeat(element, ref count) => { . self.check_expr_repeat(element, count, expected, expr) . } 1,941 ( 0.00%) ExprKind::Tup(elts) => self.check_expr_tuple(elts, expected, expr), . ExprKind::Struct(qpath, fields, ref base_expr) => { . self.check_expr_struct(expr, expected, qpath, fields, base_expr) . } . ExprKind::Field(base, field) => self.check_field(expr, &base, field), 3 ( 0.00%) ExprKind::Index(base, idx) => self.check_expr_index(base, idx, expr), . ExprKind::Yield(value, ref src) => self.check_expr_yield(value, expr, src), . hir::ExprKind::Err => tcx.ty_error(), . } . } . . fn check_expr_box(&self, expr: &'tcx hir::Expr<'tcx>, expected: Expectation<'tcx>) -> Ty<'tcx> { . let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| match ty.kind() { . ty::Adt(def, _) if def.is_box() => Expectation::rvalue_hint(self, ty.boxed_ty()), -- line 342 ---------------------------------------- -- line 409 ---------------------------------------- . &self, . kind: hir::BorrowKind, . mutbl: hir::Mutability, . oprnd: &'tcx hir::Expr<'tcx>, . expected: Expectation<'tcx>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { . let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| { 5 ( 0.00%) match ty.kind() { . ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => { 4 ( 0.00%) if oprnd.is_syntactic_place_expr() { . // Places may legitimately have unsized types. . // For example, dereferences of a fat pointer and . // the last field of a struct can be unsized. . ExpectHasType(ty) . } else { 6 ( 0.00%) Expectation::rvalue_hint(self, ty) . } . } . _ => NoExpectation, . } 3 ( 0.00%) }); . let ty = . self.check_expr_with_expectation_and_needs(&oprnd, hint, Needs::maybe_mut_place(mutbl)); . . let tm = ty::TypeAndMut { ty, mutbl }; 1 ( 0.00%) match kind { 1 ( 0.00%) _ if tm.ty.references_error() => self.tcx.ty_error(), . hir::BorrowKind::Raw => { . self.check_named_place_expr(oprnd); . self.tcx.mk_ptr(tm) . } . hir::BorrowKind::Ref => { . // Note: at this point, we cannot say what the best lifetime . // is to use for resulting pointer. We want to use the . // shortest lifetime possible so as to avoid spurious borrowck -- line 444 ---------------------------------------- -- line 448 ---------------------------------------- . // type inference is complete. . // . // Therefore, here we simply generate a region variable. The . // region inferencer will then select a suitable value. . // Finally, borrowck will infer the value of the region again, . // this time with enough precision to check that the value . // whose address was taken can actually be made to live as long . // as it needs to live. 5 ( 0.00%) let region = self.next_region_var(infer::AddrOfRegion(expr.span)); 1 ( 0.00%) self.tcx.mk_ref(region, tm) . } . } . } . . /// Does this expression refer to a place that either: . /// * Is based on a local or static. . /// * Contains a dereference . /// Note that the adjustments for the children of `expr` should already -- line 465 ---------------------------------------- -- line 492 ---------------------------------------- . &self, . lang_item: hir::LangItem, . expr: &'tcx hir::Expr<'tcx>, . hir_id: Option, . ) -> Ty<'tcx> { . self.resolve_lang_item_path(lang_item, expr.span, expr.hir_id, hir_id).1 . } . 440 ( 0.00%) pub(crate) fn check_expr_path( . &self, . qpath: &'tcx hir::QPath<'tcx>, . expr: &'tcx hir::Expr<'tcx>, . args: &'tcx [hir::Expr<'tcx>], . ) -> Ty<'tcx> { 40 ( 0.00%) let tcx = self.tcx; 440 ( 0.00%) let (res, opt_ty, segs) = 400 ( 0.00%) self.resolve_ty_and_res_fully_qualified_call(qpath, expr.hir_id, expr.span); 192 ( 0.00%) let ty = match res { . Res::Err => { . self.set_tainted_by_errors(); . tcx.ty_error() . } . Res::Def(DefKind::Ctor(_, CtorKind::Fictive), _) => { . report_unexpected_variant_res(tcx, res, expr.span); . tcx.ty_error() . } 720 ( 0.00%) _ => self.instantiate_value_path(segs, opt_ty, res, expr.span, expr.hir_id).0, . }; . 120 ( 0.00%) if let ty::FnDef(..) = ty.kind() { 30 ( 0.00%) let fn_sig = ty.fn_sig(tcx); 40 ( 0.00%) if !tcx.features().unsized_fn_params { . // We want to remove some Sized bounds from std functions, . // but don't want to expose the removal to stable Rust. . // i.e., we don't want to allow . // . // ```rust . // drop as fn(str); . // ``` . // . // to work in stable even if the Sized bound on `drop` is relaxed. . for i in 0..fn_sig.inputs().skip_binder().len() { . // We just want to check sizedness, so instead of introducing . // placeholder lifetimes with probing, we just replace higher lifetimes . // with fresh vars. 14 ( 0.00%) let span = args.get(i).map(|a| a.span).unwrap_or(expr.span); . let input = self . .replace_bound_vars_with_fresh_vars( . span, . infer::LateBoundRegionConversionTime::FnCall, . fn_sig.input(i), . ) . .0; 72 ( 0.00%) self.require_type_is_sized_deferred( . input, . span, 54 ( 0.00%) traits::SizedArgumentType(None), . ); . } . } . // Here we want to prevent struct constructors from returning unsized types. . // There were two cases this happened: fn pointer coercion in stable . // and usual function call in presence of unsized_locals. . // Also, as we just want to check sizedness, instead of introducing . // placeholder lifetimes with probing, we just replace higher lifetimes -- line 556 ---------------------------------------- -- line 557 ---------------------------------------- . // with fresh vars. . let output = self . .replace_bound_vars_with_fresh_vars( . expr.span, . infer::LateBoundRegionConversionTime::FnCall, . fn_sig.output(), . ) . .0; 60 ( 0.00%) self.require_type_is_sized_deferred(output, expr.span, traits::SizedReturnType); . } . . // We always require that the type provided as the value for . // a type parameter outlives the moment of instantiation. 160 ( 0.00%) let substs = self.typeck_results.borrow().node_substs(expr.hir_id); . self.add_wf_bounds(substs, expr); . . ty 320 ( 0.00%) } . . fn check_expr_break( . &self, . destination: hir::Destination, . expr_opt: Option<&'tcx hir::Expr<'tcx>>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { . let tcx = self.tcx; -- line 582 ---------------------------------------- -- line 791 ---------------------------------------- . coercion.coerce_forced_unit(self, &cause, &mut |_| (), true); . } . } . self.tcx.types.never . } . . /// `explicit_return` is `true` if we're checkng an explicit `return expr`, . /// and `false` if we're checking a trailing expression. 72 ( 0.00%) pub(super) fn check_return_expr( . &self, . return_expr: &'tcx hir::Expr<'tcx>, . explicit_return: bool, . ) { . let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| { . span_bug!(return_expr.span, "check_return_expr called outside fn body") . }); . . let ret_ty = ret_coercion.borrow().expected_ty(); . let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty); 9 ( 0.00%) let mut span = return_expr.span; . // Use the span of the trailing expression for our cause, . // not the span of the entire function 18 ( 0.00%) if !explicit_return { 25 ( 0.00%) if let ExprKind::Block(body, _) = return_expr.kind { 21 ( 0.00%) if let Some(last_expr) = body.expr { 7 ( 0.00%) span = last_expr.span; . } . } . } . ret_coercion.borrow_mut().coerce( . self, 18 ( 0.00%) &self.cause(span, ObligationCauseCode::ReturnValue(return_expr.hir_id)), . return_expr, . return_expr_ty, . ); 72 ( 0.00%) } . . pub(crate) fn check_lhs_assignable( . &self, . lhs: &'tcx hir::Expr<'tcx>, . err_code: &'static str, . op_span: Span, . ) { . if lhs.is_syntactic_place_expr() { -- line 834 ---------------------------------------- -- line 894 ---------------------------------------- . cond_expr: &'tcx hir::Expr<'tcx>, . then_expr: &'tcx hir::Expr<'tcx>, . opt_else_expr: Option<&'tcx hir::Expr<'tcx>>, . sp: Span, . orig_expected: Expectation<'tcx>, . ) -> Ty<'tcx> { . let cond_ty = self.check_expr_has_type_or_error(cond_expr, self.tcx.types.bool, |_| {}); . 15 ( 0.00%) self.warn_if_unreachable( 6 ( 0.00%) cond_expr.hir_id, 3 ( 0.00%) then_expr.span, . "block in `if` or `while` expression", . ); . 6 ( 0.00%) let cond_diverges = self.diverges.get(); . self.diverges.set(Diverges::Maybe); . . let expected = orig_expected.adjust_for_branches(self); . let then_ty = self.check_expr_with_expectation(then_expr, expected); . let then_diverges = self.diverges.get(); . self.diverges.set(Diverges::Maybe); . . // We've already taken the expected type's preferences -- line 916 ---------------------------------------- -- line 919 ---------------------------------------- . // `expected` if it represents a *hard* constraint . // (`only_has_type`); otherwise, we just go with a . // fresh type variable. . let coerce_to_ty = expected.coercion_target_type(self, sp); . let mut coerce: DynamicCoerceMany<'_> = CoerceMany::new(coerce_to_ty); . . coerce.coerce(self, &self.misc(sp), then_expr, then_ty); . 6 ( 0.00%) if let Some(else_expr) = opt_else_expr { 6 ( 0.00%) let else_ty = if sp.desugaring_kind() == Some(DesugaringKind::LetElse) { . // todo introduce `check_expr_with_expectation(.., Expectation::LetElse)` . // for errors that point to the offending expression rather than the entire block. . // We could use `check_expr_eq_type(.., tcx.types.never)`, but then there is no . // way to detect that the expected type originated from let-else and provide . // a customized error. . let else_ty = self.check_expr(else_expr); . let cause = self.cause(else_expr.span, ObligationCauseCode::LetElse); . -- line 936 ---------------------------------------- -- line 943 ---------------------------------------- . else_ty . } . } else { . self.check_expr_with_expectation(else_expr, expected) . }; . let else_diverges = self.diverges.get(); . . let opt_suggest_box_span = 24 ( 0.00%) self.opt_suggest_box_span(else_expr.span, else_ty, orig_expected); . let if_cause = . self.if_cause(sp, then_expr, else_expr, then_ty, else_ty, opt_suggest_box_span); . . coerce.coerce(self, &if_cause, else_expr, else_ty); . . // We won't diverge unless both branches do (or the condition does). 51 ( 0.00%) self.diverges.set(cond_diverges | then_diverges & else_diverges); . } else { . self.if_fallback_coercion(sp, then_expr, &mut coerce); . . // If the condition is false we can't diverge. . self.diverges.set(cond_diverges); . } . 39 ( 0.00%) let result_ty = coerce.complete(self); 3 ( 0.00%) if cond_ty.references_error() { self.tcx.ty_error() } else { result_ty } . } . . /// Type check assignment expression `expr` of form `lhs = rhs`. . /// The expected type is `()` and is passed to the function for the purposes of diagnostics. . fn check_expr_assign( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Expectation<'tcx>, -- line 975 ---------------------------------------- -- line 1095 ---------------------------------------- . /// Checks a method call. . fn check_method_call( . &self, . expr: &'tcx hir::Expr<'tcx>, . segment: &hir::PathSegment<'_>, . args: &'tcx [hir::Expr<'tcx>], . expected: Expectation<'tcx>, . ) -> Ty<'tcx> { 18 ( 0.00%) let rcvr = &args[0]; . let rcvr_t = self.check_expr(&rcvr); . // no need to check for bot/err -- callee does that 36 ( 0.00%) let rcvr_t = self.structurally_resolved_type(args[0].span, rcvr_t); 9 ( 0.00%) let span = segment.ident.span; . 144 ( 0.00%) let method = match self.lookup_method(rcvr_t, segment, span, expr, rcvr, args) { 18 ( 0.00%) Ok(method) => { . // We could add a "consider `foo::`" suggestion here, but I wasn't able to . // trigger this codepath causing `structuraly_resolved_type` to emit an error. . 99 ( 0.00%) self.write_method_call(expr.hir_id, method); 45 ( 0.00%) Ok(method) . } . Err(error) => { . if segment.ident.name != kw::Empty { . if let Some(mut err) = self.report_method_error( . span, . rcvr_t, . segment.ident, . SelfSource::MethodCall(&args[0]), -- line 1123 ---------------------------------------- -- line 1127 ---------------------------------------- . err.emit(); . } . } . Err(()) . } . }; . . // Call the generic checker. 126 ( 0.00%) self.check_method_argument_types( . span, . expr, 54 ( 0.00%) method, . &args[1..], . DontTupleArguments, . expected, . ) . } . . fn check_expr_cast( . &self, . e: &'tcx hir::Expr<'tcx>, . t: &'tcx hir::Ty<'tcx>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { . // Find the type of `e`. Supply hints based on the type we are casting to, . // if appropriate. 8 ( 0.00%) let t_cast = self.to_ty_saving_user_provided_ty(t); . let t_cast = self.resolve_vars_if_possible(t_cast); . let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast)); . let t_expr = self.resolve_vars_if_possible(t_expr); . . // Eagerly check for some obvious errors. 4 ( 0.00%) if t_expr.references_error() || t_cast.references_error() { . self.tcx.ty_error() . } else { . // Defer other checks until we're done type checking. . let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut(); 6 ( 0.00%) match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) { . Ok(cast_check) => { . debug!( . "check_expr_cast: deferring cast from {:?} to {:?}: {:?}", . t_cast, t_expr, cast_check, . ); . deferred_cast_checks.push(cast_check); . t_cast . } -- line 1172 ---------------------------------------- -- line 1176 ---------------------------------------- . } . . fn check_expr_array( . &self, . args: &'tcx [hir::Expr<'tcx>], . expected: Expectation<'tcx>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { 1 ( 0.00%) let element_ty = if !args.is_empty() { 3 ( 0.00%) let coerce_to = expected . .to_option(self) 3 ( 0.00%) .and_then(|uty| match *uty.kind() { . ty::Array(ty, _) | ty::Slice(ty) => Some(ty), . _ => None, . }) . .unwrap_or_else(|| { . self.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::TypeInference, . span: expr.span, . }) . }); . let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args); 1 ( 0.00%) assert_eq!(self.diverges.get(), Diverges::Maybe); . for e in args { . let e_ty = self.check_expr_with_hint(e, coerce_to); 646 ( 0.00%) let cause = self.misc(e.span); 3,876 ( 0.00%) coerce.coerce(self, &cause, e, e_ty); . } 12 ( 0.00%) coerce.complete(self) . } else { . self.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::TypeInference, . span: expr.span, . }) . }; 6 ( 0.00%) self.tcx.mk_array(element_ty, args.len() as u64) . } . . fn check_expr_const_block( . &self, . anon_const: &'tcx hir::AnonConst, . expected: Expectation<'tcx>, . _expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { -- line 1219 ---------------------------------------- -- line 1270 ---------------------------------------- . } . . fn check_expr_tuple( . &self, . elts: &'tcx [hir::Expr<'tcx>], . expected: Expectation<'tcx>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { 1,294 ( 0.00%) let flds = expected.only_has_type(self).and_then(|ty| { 647 ( 0.00%) let ty = self.resolve_vars_with_obligations(ty); 1,294 ( 0.00%) match ty.kind() { 647 ( 0.00%) ty::Tuple(flds) => Some(&flds[..]), . _ => None, . } . }); . 7,761 ( 0.00%) let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| match flds { 5,174 ( 0.00%) Some(fs) if i < fs.len() => { 5,174 ( 0.00%) let ety = fs[i].expect_ty(); 12,935 ( 0.01%) self.check_expr_coercable_to_type(&e, ety, None); . ety . } . _ => self.check_expr_with_expectation(&e, NoExpectation), . }); 1,294 ( 0.00%) let tuple = self.tcx.mk_tup(elt_ts_iter); 647 ( 0.00%) if tuple.references_error() { . self.tcx.ty_error() . } else { 4,529 ( 0.00%) self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized); . tuple . } . } . . fn check_expr_struct( . &self, . expr: &hir::Expr<'_>, . expected: Expectation<'tcx>, -- line 1306 ---------------------------------------- -- line 2301 ---------------------------------------- . &self, . base: &'tcx hir::Expr<'tcx>, . idx: &'tcx hir::Expr<'tcx>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { . let base_t = self.check_expr(&base); . let idx_t = self.check_expr(&idx); . 1 ( 0.00%) if base_t.references_error() { . base_t 1 ( 0.00%) } else if idx_t.references_error() { . idx_t . } else { 6 ( 0.00%) let base_t = self.structurally_resolved_type(base.span, base_t); 2 ( 0.00%) match self.lookup_indexing(expr, base, base_t, idx, idx_t) { . Some((index_ty, element_ty)) => { . // two-phase not needed because index_ty is never mutable . self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No); . element_ty . } . None => { . let mut err = type_error_struct!( . self.tcx.sess, -- line 2323 ---------------------------------------- 41,142 ( 0.02%) -------------------------------------------------------------------------------- -- 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. 8 ( 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. 8 ( 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 }, . } 16 ( 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,815 ( 0.00%) fn new() -> InferCtxtInner<'tcx> { 12,342 ( 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(), 1,089 ( 0.00%) region_constraint_storage: Some(RegionConstraintStorage::new()), . region_obligations: vec![], . opaque_types: Default::default(), . opaque_types_vars: Default::default(), . } 2,178 ( 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> { 136 ( 0.00%) self.projection_cache.with_log(&mut self.undo_log) . } . . #[inline] . fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> { 40,227 ( 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>, . >, . > { 10 ( 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, -- line 258 ---------------------------------------- -- line 268 ---------------------------------------- . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::ConstVid<'tcx>, . &mut ut::UnificationStorage>, . &mut InferCtxtUndoLogs<'tcx>, . >, . > { 10 ( 0.00%) self.const_unification_storage.with_log(&mut self.undo_log) . } . . #[inline] . pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> { 695 ( 0.00%) self.region_constraint_storage . .as_mut() . .expect("region constraints already solved") 897 ( 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. 792 ( 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 717 ( 0.00%) #[derive(Clone, Debug)] . pub enum SubregionOrigin<'tcx> { . /// Arose from a subtyping relation 47 ( 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. . RelateParamBound(Span, Ty<'tcx>, Option), -- line 402 ---------------------------------------- -- line 410 ---------------------------------------- . . /// Creating a pointer `b` to contents of an upvar . ReborrowUpvar(Span, ty::UpvarId), . . /// Data with type `Ty<'tcx>` was borrowed . DataBorrowed(Ty<'tcx>, Span), . . /// (&'a &'b T) where a >= b 2 ( 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> { 363 ( 0.00%) fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> { 1,089 ( 0.00%) InferCtxtBuilder { tcx: self, defining_use_anchor: None, fresh_typeck_results: None } 363 ( 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. 216 ( 0.00%) pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self { 264 ( 0.00%) self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner))); 120 ( 0.00%) self.with_opaque_type_inference(table_owner) 168 ( 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. 22 ( 0.00%) pub fn with_opaque_type_inference(mut self, defining_use_anchor: LocalDefId) -> Self { 11 ( 0.00%) self.defining_use_anchor = Some(defining_use_anchor); 70 ( 0.00%) self 33 ( 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`). 744 ( 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| { 944 ( 0.00%) let (value, subst) = 78 ( 0.00%) infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical); 1,444 ( 0.00%) f(infcx, value, subst) . }) 808 ( 0.00%) } . 1,840 ( 0.00%) pub fn enter(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R { 979 ( 0.00%) let InferCtxtBuilder { tcx, defining_use_anchor, ref fresh_typeck_results } = *self; . let in_progress_typeck_results = fresh_typeck_results.as_ref(); 15,518 ( 0.01%) f(InferCtxt { . tcx, . defining_use_anchor, . in_progress_typeck_results, 363 ( 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), 363 ( 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,936 ( 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 { 2 ( 0.00%) let InferOk { value, obligations } = self; 8 ( 0.00%) for obligation in obligations { . fulfill_cx.register_predicate_obligation(infcx, obligation); . } . value . } . } . . impl<'tcx> InferOk<'tcx, ()> { 150 ( 0.00%) pub fn into_obligations(self) -> PredicateObligations<'tcx> { 600 ( 0.00%) self.obligations 150 ( 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() 994 ( 0.00%) } . 22,856 ( 0.01%) pub fn freshen>(&self, t: T) -> T { 25,713 ( 0.01%) t.fold_with(&mut self.freshener()) 25,713 ( 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`. 8 ( 0.00%) pub fn type_var_origin(&'a self, ty: Ty<'tcx>) -> Option { 16 ( 0.00%) match *ty.kind() { 4 ( 0.00%) ty::Infer(ty::TyVar(vid)) => { 16 ( 0.00%) Some(*self.inner.borrow_mut().type_variables().var_origin(vid)) . } . _ => None, . } 16 ( 0.00%) } . 2,857 ( 0.00%) pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, false) 2,857 ( 0.00%) } . . /// Like `freshener`, but does not replace `'static` regions. 3,822 ( 0.00%) pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, true) 3,822 ( 0.00%) } . 44 ( 0.00%) pub fn unsolved_variables(&self) -> Vec> { 22 ( 0.00%) let mut inner = self.inner.borrow_mut(); 22 ( 0.00%) let mut vars: Vec> = inner . .type_variables() . .unsolved_variables() . .into_iter() 8 ( 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 }) 2 ( 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 }) . .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none()) . .map(|v| self.tcx.mk_float_var(v)), . ); . vars 77 ( 0.00%) } . 5,660 ( 0.00%) fn combine_fields( . &'a self, . trace: TypeTrace<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> CombineFields<'a, 'tcx> { 22,640 ( 0.01%) CombineFields { . infcx: self, 56,600 ( 0.03%) trace, . cause: None, . param_env, . obligations: PredicateObligations::new(), . } 5,660 ( 0.00%) } . . /// 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); 60 ( 0.00%) let result = func(self); . self.in_snapshot.set(flag); . result . } . 33,764 ( 0.02%) 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(); . 101,292 ( 0.05%) 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. 16,882 ( 0.01%) _in_progress_typeck_results: self . .in_progress_typeck_results . .map(|typeck_results| typeck_results.borrow()), . } 67,528 ( 0.03%) } . 32,516 ( 0.02%) #[instrument(skip(self, snapshot), level = "debug")] . fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 2,956 ( 0.00%) undo_snapshot, 2,956 ( 0.00%) region_constraints_snapshot, 2,956 ( 0.00%) universe, 2,956 ( 0.00%) was_in_snapshot, 5,912 ( 0.00%) _in_progress_typeck_results, . } = snapshot; . . self.in_snapshot.set(was_in_snapshot); . self.universe.set(universe); . . let mut inner = self.inner.borrow_mut(); 2,956 ( 0.00%) inner.rollback_to(undo_snapshot); . inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot); . } . 208,890 ( 0.11%) #[instrument(skip(self, snapshot), level = "debug")] . fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 13,926 ( 0.01%) undo_snapshot, . region_constraints_snapshot: _, . universe: _, 13,926 ( 0.01%) was_in_snapshot, 27,852 ( 0.01%) _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. 690 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 847 ( 0.00%) pub fn commit_unconditionally(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 77 ( 0.00%) let snapshot = self.start_snapshot(); 246 ( 0.00%) let r = f(&snapshot); 539 ( 0.00%) self.commit_from(snapshot); 459 ( 0.00%) r . } . . /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`. 67,937 ( 0.03%) #[instrument(skip(self, f), level = "debug")] 84,824 ( 0.04%) pub fn commit_if_ok(&self, f: F) -> Result . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result, . { 19,237 ( 0.01%) let snapshot = self.start_snapshot(); 39,542 ( 0.02%) let r = f(&snapshot); . debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok()); 26,990 ( 0.01%) match r { . Ok(_) => { 97,151 ( 0.05%) self.commit_from(snapshot); . } . Err(_) => { 26,807 ( 0.01%) self.rollback_to("commit_if_ok -- error", snapshot); . } . } 125,060 ( 0.06%) r . } . . /// Execute `f` then unroll any bindings it creates. 2,115 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 2,420 ( 0.00%) pub fn probe(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 524 ( 0.00%) let snapshot = self.start_snapshot(); 697 ( 0.00%) let r = f(&snapshot); 2,475 ( 0.00%) self.rollback_to("probe", snapshot); 286 ( 0.00%) r . } . . /// If `should_skip` is true, then execute `f` then unroll any bindings it creates. . #[instrument(skip(self, f), level = "debug")] . pub fn probe_maybe_skip_leak_check(&self, should_skip: bool, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { -- line 875 ---------------------------------------- -- line 884 ---------------------------------------- . 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 254 ( 0.00%) pub fn region_constraints_added_in_snapshot( . &self, . snapshot: &CombinedSnapshot<'a, 'tcx>, . ) -> Option { 508 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() . .region_constraints_added_in_snapshot(&snapshot.undo_snapshot) 381 ( 0.00%) } . . pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) { . self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup); . } . . pub fn can_sub(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx> . where . T: at::ToTrace<'tcx>, -- line 908 ---------------------------------------- -- line 911 ---------------------------------------- . self.probe(|_| { . self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| { . // Ignore obligations, since we are unrolling . // everything anyway. . }) . }) . } . 144 ( 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. . }) . }) 108 ( 0.00%) } . 180 ( 0.00%) #[instrument(skip(self), level = "debug")] . pub fn sub_regions( . &self, . origin: SubregionOrigin<'tcx>, . a: ty::Region<'tcx>, . b: ty::Region<'tcx>, . ) { 162 ( 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 1022 ---------------------------------------- . self.replace_bound_vars_with_placeholders(predicate); . . let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?; . . Ok(ok.unit()) . })) . } . 120 ( 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) . }); 100 ( 0.00%) self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b` . Ok(()) . }) 80 ( 0.00%) } . . /// Number of type variables created so far. 3 ( 0.00%) pub fn num_ty_vars(&self) -> usize { . self.inner.borrow_mut().type_variables().num_vars() 6 ( 0.00%) } . 5,422 ( 0.00%) pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid { 27,110 ( 0.01%) self.inner.borrow_mut().type_variables().new_var(self.universe(), origin) 8,133 ( 0.00%) } . 5,412 ( 0.00%) pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> { 18,972 ( 0.01%) self.tcx.mk_ty_var(self.next_ty_var_id(origin)) 8,118 ( 0.00%) } . 38 ( 0.00%) pub fn next_ty_var_in_universe( . &self, . origin: TypeVariableOrigin, . universe: ty::UniverseIndex, . ) -> Ty<'tcx> { 209 ( 0.00%) let vid = self.inner.borrow_mut().type_variables().new_var(universe, origin); 19 ( 0.00%) self.tcx.mk_ty_var(vid) 57 ( 0.00%) } . . pub fn next_const_var( . &self, . ty: Ty<'tcx>, . origin: ConstVariableOrigin, . ) -> &'tcx ty::Const<'tcx> { . self.tcx.mk_const_var(self.next_const_var_id(origin), ty) . } -- line 1074 ---------------------------------------- -- line 1090 ---------------------------------------- . pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> { . self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue { . origin, . val: ConstVariableValue::Unknown { universe: self.universe() }, . }) . } . . fn next_int_var_id(&self) -> IntVid { 5 ( 0.00%) self.inner.borrow_mut().int_unification_table().new_key(None) . } . 3 ( 0.00%) pub fn next_int_var(&self) -> Ty<'tcx> { . self.tcx.mk_int_var(self.next_int_var_id()) 4 ( 0.00%) } . . fn next_float_var_id(&self) -> FloatVid { . self.inner.borrow_mut().float_unification_table().new_key(None) . } . . pub fn next_float_var(&self) -> Ty<'tcx> { . self.tcx.mk_float_var(self.next_float_var_id()) . } . . /// 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. 27 ( 0.00%) pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> { 1,009 ( 0.00%) self.next_region_var_in_universe(origin, self.universe()) 54 ( 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. 484 ( 0.00%) pub fn next_region_var_in_universe( . &self, . origin: RegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { . let region_var = 3,146 ( 0.00%) self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin); 1,210 ( 0.00%) self.tcx.mk_region(ty::ReVar(region_var)) 726 ( 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. 34 ( 0.00%) pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex { . self.inner.borrow_mut().unwrap_region_constraints().universe(r) 51 ( 0.00%) } . . /// Number of region variables created so far. 94 ( 0.00%) pub fn num_region_vars(&self) -> usize { . self.inner.borrow_mut().unwrap_region_constraints().num_region_vars() 141 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 100 ( 0.00%) pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> { . self.next_region_var(RegionVariableOrigin::Nll(origin)) 200 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 1 ( 0.00%) pub fn next_nll_region_var_in_universe( . &self, . origin: NllRegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { 7 ( 0.00%) self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe) 2 ( 0.00%) } . 1,376 ( 0.00%) pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 772 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { . // Create a region inference variable for the given . // region parameter definition. 44 ( 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)`. 512 ( 0.00%) let ty_var_id = self.inner.borrow_mut().type_variables().new_var( . self.universe(), 640 ( 0.00%) TypeVariableOrigin { . kind: TypeVariableOriginKind::TypeParameterDefinition( 128 ( 0.00%) param.name, 128 ( 0.00%) Some(param.def_id), . ), . span, . }, . ); . 128 ( 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, -- line 1196 ---------------------------------------- -- line 1202 ---------------------------------------- . }); . self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into() . } . } . } . . /// Given a set of generics defined on a type or impl, returns a substitution mapping each . /// type/region parameter to a fresh inference variable. 339 ( 0.00%) pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> { 1,353 ( 0.00%) InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param)) 226 ( 0.00%) } . . /// 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). 24 ( 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() . ); . 996 ( 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() 36 ( 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`. 1,064 ( 0.00%) pub fn resolve_regions( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) -> Vec> { 2,888 ( 0.00%) let (var_infos, data) = { . let mut inner = self.inner.borrow_mut(); . let inner = &mut *inner; 152 ( 0.00%) assert!( 456 ( 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() 152 ( 0.00%) }; . . let region_rels = 152 ( 0.00%) &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map()); . 1,368 ( 0.00%) let (lexical_region_resolutions, errors) = 3,648 ( 0.00%) lexical_region_resolve::resolve(region_rels, var_infos, data, mode); . 608 ( 0.00%) let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions)); 152 ( 0.00%) assert!(old_value.is_none()); . . errors 1,368 ( 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`. 1,520 ( 0.00%) pub fn resolve_regions_and_report_errors( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) { 304 ( 0.00%) let errors = self.resolve_regions(region_context, outlives_env, mode); . 456 ( 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. 304 ( 0.00%) self.report_region_errors(&errors); . } 760 ( 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(); 280 ( 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. 55 ( 0.00%) pub fn take_region_var_origins(&self) -> VarInfos { . let mut inner = self.inner.borrow_mut(); 209 ( 0.00%) let (var_infos, data) = inner . .region_constraint_storage . .take() . .expect("regions already resolved") . .with_log(&mut inner.undo_log) 11 ( 0.00%) .into_infos_and_data(); 11 ( 0.00%) assert!(data.is_empty()); . var_infos 88 ( 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)`. 138 ( 0.00%) pub fn probe_ty_var(&self, vid: TyVid) -> Result, ty::UniverseIndex> { . use self::type_variable::TypeVariableValue; . 414 ( 0.00%) match self.inner.borrow_mut().type_variables().probe(vid) { . TypeVariableValue::Known { value } => Ok(value), . TypeVariableValue::Unknown { universe } => Err(universe), . } 483 ( 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>, . { 34,387 ( 0.02%) value.fold_with(&mut ShallowResolver { infcx: self }) . } . 202 ( 0.00%) pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid { . self.inner.borrow_mut().type_variables().root_var(var) 303 ( 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. . pub fn resolve_vars_if_possible(&self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { 10,334 ( 0.01%) if !value.needs_infer() { 7,490 ( 0.00%) return value; // Avoid duplicated subst-folding. . } 1,821 ( 0.00%) let mut r = resolve::OpportunisticVarResolver::new(self); 2,761 ( 0.00%) value.fold_with(&mut r) . } . . /// 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)> -- line 1414 ---------------------------------------- -- 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) . } . 135 ( 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 = 323 ( 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 }, . ) . }; 1,709 ( 0.00%) self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c) 90 ( 0.00%) } . . /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method. 16 ( 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); . 6 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() 34 ( 0.00%) .verify_generic_bound(origin, kind, a, bound); 14 ( 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. 80 ( 0.00%) pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option { 160 ( 0.00%) let closure_kind_ty = closure_substs.as_closure().kind_ty(); . let closure_kind_ty = self.shallow_resolve(closure_kind_ty); 120 ( 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 { 26,483 ( 0.01%) self.universe.get() 6,281 ( 0.00%) } . . /// Creates and return a fresh universe that extends all previous . /// universes. Updates `self.universe` to that new universe. . pub fn create_next_universe(&self) -> ty::UniverseIndex { . let u = self.universe.get().next_universe(); . self.universe.set(u); . u . } -- line 1568 ---------------------------------------- -- 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`. 121,856 ( 0.06%) fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> { 37,075 ( 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`. 6,560 ( 0.00%) let known = self.inner.borrow_mut().type_variables().probe(v).known(); . known.map_or(typ, |t| self.shallow_resolve_ty(t)) . } . 16 ( 0.00%) ty::Infer(ty::IntVar(v)) => self . .inner . .borrow_mut() . .int_unification_table() . .probe_value(v) 9 ( 0.00%) .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . . ty::Infer(ty::FloatVar(v)) => self . .inner . .borrow_mut() . .float_unification_table() . .probe_value(v) . .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . . _ => typ, . } 137,088 ( 0.07%) } . . /// `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))`. 2,133 ( 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 -- line 1678 ---------------------------------------- -- 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`). 73 ( 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, . } 73 ( 0.00%) } . . /// Tries to extract an inference variable from a type, returns `None` . /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`). . pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option { 629 ( 0.00%) match *ty.kind() { 138 ( 0.00%) ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)), . ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)), . ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)), . _ => None, . } . } . . /// Tries to extract an inference variable from a constant, returns `None` . /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`). -- line 1744 ---------------------------------------- -- line 1755 ---------------------------------------- . } . . 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> { 29,018 ( 0.01%) self.infcx.shallow_resolve_ty(ty) . } . . fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { . if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct { . self.infcx . .inner . .borrow_mut() . .const_unification_table() -- line 1771 ---------------------------------------- -- line 1818 ---------------------------------------- . CompareImplTypeObligation { span, .. } => span, . } . } . . pub fn from_obligation_cause(cause: &traits::ObligationCause<'tcx>, default: F) -> Self . where . F: FnOnce() -> Self, . { 160 ( 0.00%) match *cause.code() { 30 ( 0.00%) traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => { 150 ( 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 ---------------------------------------- 42,294 ( 0.02%) -------------------------------------------------------------------------------- -- 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 { 114,141 ( 0.06%) 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)); 5,749 ( 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::()); 2,405,357 ( 1.22%) 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" . ); . 10,892 ( 0.01%) self.stride += Group::WIDTH; 10,892 ( 0.01%) self.pos += self.stride; 9,206 ( 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. 4,536 ( 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. 8,835 ( 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. 3,006 ( 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 { 11,147 ( 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. 4,080 ( 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 = 9,715 ( 0.00%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 12,667 ( 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 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 { 9 ( 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 { 25 ( 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 { 276 ( 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")] 379 ( 0.00%) pub unsafe fn erase_no_drop(&mut self, item: &Bucket) { 379 ( 0.00%) let index = self.bucket_index(item); . self.table.erase(index); 758 ( 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. 204 ( 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 { 554 ( 0.00%) self.erase_no_drop(&item); . item.read() . } . . /// Finds and removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] 54,035 ( 0.03%) pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option { . // Avoid `Option::map` because it bloats LLVM IR. 22 ( 0.00%) match self.find(hash, eq) { 109 ( 0.00%) Some(bucket) => Some(unsafe { self.remove(bucket) }), 22,085 ( 0.01%) None => None, . } 81,362 ( 0.04%) } . . /// 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) { 386 ( 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) { 13,146 ( 0.01%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 7,778 ( 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)] 18,261 ( 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 . }, . ) . } 11,184 ( 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)] 180,388 ( 0.09%) 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. 291 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 128,628 ( 0.07%) 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); 4 ( 0.00%) bucket.write(value); . bucket . } 133,797 ( 0.07%) } . . /// 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)] 26,216 ( 0.01%) pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T { 14 ( 0.00%) unsafe { self.insert(hash, value, hasher).as_mut() } 19,662 ( 0.01%) } . . /// 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"))] 27 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 16,965 ( 0.01%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 1,355 ( 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. 35,549 ( 0.02%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 26,781 ( 0.01%) self.table.items += 1; . bucket 41 ( 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] 56 ( 0.00%) pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { 10,121 ( 0.01%) let result = self.table.find_inner(hash, &mut |index| unsafe { 5,089 ( 0.00%) eq(self.bucket(index).as_ref()) 6,476 ( 0.00%) }); . . // Avoid `Option::map` because it bloats LLVM IR. . match result { 1,532 ( 0.00%) Some(index) => Some(unsafe { self.bucket(index) }), . None => None, . } 56 ( 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. 3,181 ( 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] . pub fn get_mut(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&mut T> { . // Avoid `Option::map` because it bloats LLVM IR. 27 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_mut() }), . None => None, . } . } . . /// 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. -- line 855 ---------------------------------------- -- 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 { 131,168 ( 0.07%) 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()), 21,789 ( 0.01%) 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(); 280 ( 0.00%) let allocation = self.into_allocation(); 210 ( 0.00%) RawIntoIter { 350 ( 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)> { 105 ( 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(( 27 ( 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 { 73,113 ( 0.04%) 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)] 16,227 ( 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()); . } . 3,994 ( 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)); 9,882 ( 0.01%) Ok(Self { . ctrl, 3,920 ( 0.00%) bucket_mask: buckets - 1, . items: 0, . growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 11,916 ( 0.01%) } . . #[inline] 1,312 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 334 ( 0.00%) if capacity == 0 { 193 ( 0.00%) Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = . capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 7,559 ( 0.00%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; . result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 761 ( 0.00%) Ok(result) . } . } 1,312 ( 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] 5,733 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { . let index = self.find_insert_slot(hash); 5,733 ( 0.00%) let old_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . (index, old_ctrl) 11,466 ( 0.01%) } . . /// 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)); 75,378 ( 0.04%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 220,812 ( 0.11%) 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). 105,756 ( 0.05%) 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); . 1,200 ( 0.00%) loop { . let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 322,293 ( 0.16%) for bit in group.match_byte(h2_hash) { 602,090 ( 0.31%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 329,955 ( 0.17%) if likely(eq(index)) { . return Some(index); . } . } . 104,033 ( 0.05%) if likely(group.match_empty().any_bit_set()) { . return None; . } . . probe_seq.move_next(self.bucket_mask); . } . } . . #[allow(clippy::mut_mut)] -- line 1198 ---------------------------------------- -- 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(); 272,568 ( 0.14%) 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,736,959 ( 0.88%) 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) { 160,785 ( 0.08%) self.growth_left -= special_is_empty(old_ctrl) as usize; . self.set_ctrl_h2(index, hash); 128,628 ( 0.07%) 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; . probe_index(i) == probe_index(new_i) -- line 1281 ---------------------------------------- -- 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] | . // --------------------------------------------- 215,931 ( 0.11%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 71,977 ( 0.04%) *self.ctrl(index) = ctrl; 71,977 ( 0.04%) *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 { 38,168 ( 0.02%) self.bucket_mask + 1 . } . . #[inline] . fn num_ctrl_bytes(&self) -> usize { 8,676 ( 0.00%) self.bucket_mask + 1 + Group::WIDTH . } . . #[inline] . fn is_empty_singleton(&self) -> bool { 115,937 ( 0.06%) 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. 288 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( . self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 4,841 ( 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_| { 2,237 ( 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. 4,475 ( 0.00%) let new_items = match self.items.checked_add(additional) { . Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 4,474 ( 0.00%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 9,429 ( 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); . Ok(()) . } else { . // Otherwise, conservatively resize to at least the next size up . // to avoid churning deletes into frequent rehashes. . self.resize_inner( 2,237 ( 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> { 717 ( 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() { 40,542 ( 0.02%) 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); . 2,237 ( 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 1554 ---------------------------------------- . #[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( 1,343 ( 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) { 123 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 187 ( 0.00%) self.items = 0; 123 ( 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))); 4,579 ( 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. 18,316 ( 0.01%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 22,895 ( 0.01%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 18,316 ( 0.01%) self.items -= 1; . } . } . . impl Clone for RawTable { 40 ( 0.00%) fn clone(&self) -> Self { 8 ( 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) . } . } 45 ( 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; 10 ( 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)] 44,801 ( 0.02%) fn drop(&mut self) { 49,240 ( 0.02%) if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); . self.free_buckets(); . } . } 54,312 ( 0.03%) } . } . #[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)] 280 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 350 ( 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 { 22,655 ( 0.01%) if let Some(index) = self.current_group.lowest_set_bit() { 3,851 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 6,939 ( 0.00%) return Some(self.data.next_n(index)); . } . 25,718 ( 0.01%) 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). 381 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); 574 ( 0.00%) self.data = self.data.next_n(Group::WIDTH); 529 ( 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) { 78 ( 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)] 4,075 ( 0.00%) fn next(&mut self) -> Option> { 8,052 ( 0.00%) if let Some(b) = self.iter.next() { 23,897 ( 0.01%) 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 . } 8,150 ( 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)] 172 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 485 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 50 ( 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)] 26 ( 0.00%) fn next(&mut self) -> Option { 15 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 53 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 2 ( 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)] 8 ( 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 ( 0.00%) self.orig_table . .as_ptr() . .copy_from_nonoverlapping(&*self.table, 1); . } 8 ( 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 ---------------------------------------- 856,130 ( 0.43%) -------------------------------------------------------------------------------- -- 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> { 34,807 ( 0.02%) ptr: NonZeroUsize, 64,877 ( 0.03%) 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; . 1,602 ( 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> { 429 ( 0.00%) fn pack(self) -> GenericArg<'tcx> { 429 ( 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) . } . }; . 1,595 ( 0.00%) GenericArg { ptr: unsafe { NonZeroUsize::new_unchecked(ptr | tag) }, marker: PhantomData } 429 ( 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), -- line 75 ---------------------------------------- -- line 85 ---------------------------------------- . . impl<'tcx> PartialOrd for GenericArg<'tcx> { . fn partial_cmp(&self, other: &GenericArg<'_>) -> Option { . Some(self.cmp(&other)) . } . } . . impl<'tcx> From> for GenericArg<'tcx> { 939 ( 0.00%) fn from(r: ty::Region<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Lifetime(r).pack() 939 ( 0.00%) } . } . . impl<'tcx> From> for GenericArg<'tcx> { 31,796 ( 0.02%) fn from(ty: Ty<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Type(ty).pack() 31,796 ( 0.02%) } . } . . impl<'tcx> From<&'tcx ty::Const<'tcx>> for GenericArg<'tcx> { . fn from(c: &'tcx ty::Const<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Const(c).pack() . } . } . . impl<'tcx> GenericArg<'tcx> { . #[inline] . pub fn unpack(self) -> GenericArgKind<'tcx> { . let ptr = self.ptr.get(); . unsafe { 340,779 ( 0.17%) match ptr & TAG_MASK { 687 ( 0.00%) REGION_TAG => GenericArgKind::Lifetime(&*((ptr & !TAG_MASK) as *const _)), 78,817 ( 0.04%) TYPE_TAG => GenericArgKind::Type(&*((ptr & !TAG_MASK) as *const _)), 2 ( 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"), . } 31,990 ( 0.02%) } . . /// 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 170 ---------------------------------------- . GenericArgKind::Type(ty) => ty.visit_with(visitor), . 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> { 153 ( 0.00%) self.unpack().encode(e) . } . } . . impl<'tcx, D: TyDecoder<'tcx>> Decodable for GenericArg<'tcx> { 2,145 ( 0.00%) fn decode(d: &mut D) -> GenericArg<'tcx> { 2,145 ( 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. 134 ( 0.00%) pub fn as_closure(&'a self) -> ClosureSubsts<'a> { . ClosureSubsts { substs: self } 134 ( 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. 600 ( 0.00%) pub fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: DefId) -> SubstsRef<'tcx> { 108 ( 0.00%) Self::for_item(tcx, def_id, |param, _| tcx.mk_param_from_def(param)) 540 ( 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. 1,422 ( 0.00%) 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); 676 ( 0.00%) Self::fill_item(&mut substs, tcx, defs, &mut mk_kind); 310 ( 0.00%) tcx.intern_substs(&substs) 1,449 ( 0.00%) } . . 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)) . }) . } . 2,812 ( 0.00%) 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>, . { 1,171 ( 0.00%) if let Some(def_id) = defs.parent { . let parent_defs = tcx.generics_of(def_id); 285 ( 0.00%) Self::fill_item(substs, tcx, parent_defs, mk_kind); . } . Self::fill_single(substs, defs, mk_kind) 2,224 ( 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 { . let kind = mk_kind(param, substs); 1,101 ( 0.00%) assert_eq!(param.index as usize, substs.len()); . substs.push(kind); . } . } . . #[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 }) -- line 281 ---------------------------------------- -- 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> { 7,485 ( 0.00%) 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. 224 ( 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); 64 ( 0.00%) tcx.mk_substs(target_substs.iter().chain(self.iter().skip(defs.params.len()))) 256 ( 0.00%) } . . pub fn truncate_to(&self, tcx: TyCtxt<'tcx>, generics: &ty::Generics) -> SubstsRef<'tcx> { . tcx.mk_substs(self.iter().take(generics.count())) . } . } . . impl<'tcx> TypeFoldable<'tcx> for SubstsRef<'tcx> { 952 ( 0.00%) 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`. 55,468 ( 0.03%) match self.len() { . 1 => { 2,683 ( 0.00%) let param0 = self[0].try_fold_with(folder)?; 9,006 ( 0.00%) if param0 == self[0] { Ok(self) } else { Ok(folder.tcx().intern_substs(&[param0])) } . } . 2 => { 6,764 ( 0.00%) let param0 = self[0].try_fold_with(folder)?; 19,366 ( 0.01%) let param1 = self[1].try_fold_with(folder)?; 24,743 ( 0.01%) if param0 == self[0] && param1 == self[1] { . Ok(self) . } else { 34,607 ( 0.02%) Ok(folder.tcx().intern_substs(&[param0, param1])) . } . } . 0 => Ok(self), . _ => { . let params: SmallVec<[_; 8]> = 11,462 ( 0.01%) self.iter().map(|k| k.try_fold_with(folder)).collect::>()?; 85 ( 0.00%) if params[..] == self[..] { . Ok(self) . } else { 197 ( 0.00%) Ok(folder.tcx().intern_substs(¶ms)) . } . } . } 1,337 ( 0.00%) } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { 11,526 ( 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 { 21,756 ( 0.01%) 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> { 869 ( 0.00%) self.tcx . } . . fn fold_binder>( . &mut self, . t: ty::Binder<'tcx, T>, . ) -> ty::Binder<'tcx, T> { 1,178 ( 0.00%) self.binders_passed += 1; 248 ( 0.00%) let t = t.super_fold_with(self); 1,178 ( 0.00%) self.binders_passed -= 1; . t . } . 630 ( 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()`. 210 ( 0.00%) match *r { 178 ( 0.00%) ty::ReEarlyBound(data) => { 178 ( 0.00%) let rk = self.substs.get(data.index as usize).map(|k| k.unpack()); . match rk { 89 ( 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, . } 735 ( 0.00%) } . 14,193 ( 0.01%) fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 4,731 ( 0.00%) if !t.needs_subst() { . return t; . } . 2,212 ( 0.00%) match *t.kind() { 3,900 ( 0.00%) ty::Param(p) => self.ty_for_param(p, t), 1,956 ( 0.00%) _ => t.super_fold_with(self), . } 22,025 ( 0.01%) } . 18,186 ( 0.01%) fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 5,196 ( 0.00%) if let ty::ConstKind::Param(p) = c.val { . self.const_for_param(p, c) . } else { 23,382 ( 0.01%) c.super_fold_with(self) . } . } . . #[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. 1,560 ( 0.00%) 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 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() . ); . 2,839 ( 0.00%) 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> { 193 ( 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)] 52 ( 0.00%) #[derive(HashStable, TypeFoldable, Lift)] . pub struct UserSubsts<'tcx> { . /// The substitutions for the item as given by the user. . pub substs: SubstsRef<'tcx>, . . /// The self type, in the case of a `::Item` path (when applied . /// to an inherent impl). See `UserSelfTy` below. 7 ( 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 ---------------------------------------- 64,273 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/levels.rs -------------------------------------------------------------------------------- Ir -- line 20 ---------------------------------------- . Level, Lint, LintId, . }; . use rustc_session::parse::feature_err; . use rustc_session::Session; . use rustc_span::symbol::{sym, Symbol}; . use rustc_span::{source_map::MultiSpan, Span, DUMMY_SP}; . use tracing::debug; . 9 ( 0.00%) fn lint_levels(tcx: TyCtxt<'_>, (): ()) -> LintLevelMap { . let store = unerased_lint_store(tcx); . let levels = 6 ( 0.00%) LintLevelsBuilder::new(tcx.sess, false, &store, &tcx.resolutions(()).registered_tools); 13 ( 0.00%) let mut builder = LintLevelMapBuilder { levels, tcx }; 3 ( 0.00%) let krate = tcx.hir().krate(); . 2 ( 0.00%) builder.levels.id_to_set.reserve(krate.owners.len() + 1); . 8 ( 0.00%) let push = builder.levels.push(tcx.hir().attrs(hir::CRATE_HIR_ID), true); . builder.levels.register_id(hir::CRATE_HIR_ID); . tcx.hir().walk_toplevel_module(&mut builder); . builder.levels.pop(push); . 16 ( 0.00%) builder.levels.build_map() 9 ( 0.00%) } . . pub struct LintLevelsBuilder<'s> { . sess: &'s Session, . sets: LintLevelSets, . id_to_set: FxHashMap, . cur: LintStackIndex, . warn_about_weird_lints: bool, . store: &'s LintStore, -- line 51 ---------------------------------------- -- line 53 ---------------------------------------- . } . . pub struct BuilderPush { . prev: LintStackIndex, . pub changed: bool, . } . . impl<'s> LintLevelsBuilder<'s> { 52 ( 0.00%) pub fn new( . sess: &'s Session, . warn_about_weird_lints: bool, . store: &'s LintStore, . registered_tools: &'s RegisteredTools, . ) -> Self { 44 ( 0.00%) let mut builder = LintLevelsBuilder { . sess, 4 ( 0.00%) sets: LintLevelSets::new(), . cur: COMMAND_LINE, . id_to_set: Default::default(), . warn_about_weird_lints, . store, . registered_tools, . }; . builder.process_command_line(sess, store); 12 ( 0.00%) assert_eq!(builder.sets.list.len(), 1); . builder 36 ( 0.00%) } . . pub(crate) fn sess(&self) -> &Session { 193 ( 0.00%) self.sess . } . . pub(crate) fn lint_store(&self) -> &LintStore { . self.store . } . . fn process_command_line(&mut self, sess: &Session, store: &LintStore) { . let mut specs = FxHashMap::default(); 8 ( 0.00%) self.sets.lint_cap = sess.opts.lint_cap.unwrap_or(Level::Forbid); . 8 ( 0.00%) for &(ref lint_name, level) in &sess.opts.lint_opts { 40 ( 0.00%) store.check_lint_name_cmdline(sess, &lint_name, level, self.registered_tools); . let orig_level = level; 16 ( 0.00%) let lint_flag_val = Symbol::intern(lint_name); . 40 ( 0.00%) let ids = match store.find_lints(&lint_name) { 32 ( 0.00%) Ok(ids) => ids, . Err(_) => continue, // errors handled in check_lint_name_cmdline above . }; 24 ( 0.00%) for id in ids { . // ForceWarn and Forbid cannot be overriden . if let Some((Level::ForceWarn | Level::Forbid, _)) = specs.get(&id) { . continue; . } . 32 ( 0.00%) self.check_gated_lint(id, DUMMY_SP); . let src = LintLevelSource::CommandLine(lint_flag_val, orig_level); 16 ( 0.00%) specs.insert(id, (level, src)); . } . } . 32 ( 0.00%) self.cur = self.sets.list.push(LintSet { specs, parent: COMMAND_LINE }); . } . . /// Attempts to insert the `id` to `level_src` map entry. If unsuccessful . /// (e.g. if a forbid was already inserted on the same scope), then emits a . /// diagnostic with no change to `specs`. 165 ( 0.00%) fn insert_spec( . &mut self, . specs: &mut FxHashMap, . id: LintId, 90 ( 0.00%) (level, src): LevelAndSource, . ) { 75 ( 0.00%) let (old_level, old_src) = 105 ( 0.00%) self.sets.get_lint_level(id.lint, self.cur, Some(&specs), &self.sess); . // Setting to a non-forbid level is an error if the lint previously had . // a forbid level. Note that this is not necessarily true even with a . // `#[forbid(..)]` attribute present, as that is overriden by `--cap-lints`. . // . // This means that this only errors if we're truly lowering the lint . // level from forbid. 15 ( 0.00%) if level != Level::Forbid { 60 ( 0.00%) if let Level::Forbid = old_level { . // Backwards compatibility check: . // . // We used to not consider `forbid(lint_group)` . // as preventing `allow(lint)` for some lint `lint` in . // `lint_group`. For now, issue a future-compatibility . // warning for this case. . let id_name = id.lint.name_lower(); . let fcw_warning = match old_src { -- line 143 ---------------------------------------- -- line 202 ---------------------------------------- . if !fcw_warning { . return; . } . } . } . if let Level::ForceWarn = old_level { . specs.insert(id, (old_level, old_src)); . } else { 60 ( 0.00%) specs.insert(id, (level, src)); . } 120 ( 0.00%) } . . /// Pushes a list of AST lint attributes onto this context. . /// . /// This function will return a `BuilderPush` object which should be passed . /// to `pop` when this scope for the attributes provided is exited. . /// . /// This function will perform a number of tasks: . /// . /// * It'll validate all lint-related attributes in `attrs` . /// * It'll mark all lint-related attributes as used . /// * Lint levels will be updated based on the attributes provided . /// * Lint attributes are validated, e.g., a `#[forbid]` can't be switched to . /// `#[allow]` . /// . /// Don't forget to call `pop`! 81,600 ( 0.04%) pub(crate) fn push(&mut self, attrs: &[ast::Attribute], is_crate_node: bool) -> BuilderPush { . let mut specs = FxHashMap::default(); 20,400 ( 0.01%) let sess = self.sess; 10,200 ( 0.01%) let bad_attr = |span| struct_span_err!(sess, span, E0452, "malformed lint attribute input"); . for attr in attrs { 1,687 ( 0.00%) let Some(level) = Level::from_symbol(attr.name_or_empty()) else { . continue . }; . 54 ( 0.00%) let Some(mut metas) = attr.meta_item_list() else { . continue . }; . 6 ( 0.00%) if metas.is_empty() { . // FIXME (#55112): issue unused-attributes lint for `#[level()]` . continue; . } . . // Before processing the lint names, look for a reason (RFC 2383) . // at the end. . let mut reason = None; 6 ( 0.00%) let tail_li = &metas[metas.len() - 1]; 18 ( 0.00%) if let Some(item) = tail_li.meta_item() { 30 ( 0.00%) match item.kind { . ast::MetaItemKind::Word => {} // actual lint names handled later . ast::MetaItemKind::NameValue(ref name_value) => { . if item.path == sym::reason { . // FIXME (#55112): issue unused-attributes lint if we thereby . // don't have any lint names (`#[level(reason = "foo")]`) . if let ast::LitKind::Str(rationale, _) = name_value.kind { . if !self.sess.features_untracked().lint_reasons { . feature_err( -- line 259 ---------------------------------------- -- line 279 ---------------------------------------- . } . } . ast::MetaItemKind::List(_) => { . bad_attr(item.span).span_label(item.span, "bad attribute argument").emit(); . } . } . } . 294 ( 0.00%) for li in metas { 60 ( 0.00%) let sp = li.span(); 30 ( 0.00%) let mut meta_item = match li { 270 ( 0.00%) ast::NestedMetaItem::MetaItem(meta_item) if meta_item.is_word() => meta_item, . _ => { . let mut err = bad_attr(sp); . let mut add_label = true; . if let Some(item) = li.meta_item() { . if let ast::MetaItemKind::NameValue(_) = item.kind { . if item.path == sym::reason { . err.span_label(sp, "reason in lint attribute must come last"); . add_label = false; -- line 298 ---------------------------------------- -- line 301 ---------------------------------------- . } . if add_label { . err.span_label(sp, "bad attribute argument"); . } . err.emit(); . continue; . } . }; 45 ( 0.00%) let tool_ident = if meta_item.path.segments.len() > 1 { . Some(meta_item.path.segments.remove(0).ident) . } else { 15 ( 0.00%) None . }; 15 ( 0.00%) let tool_name = tool_ident.map(|ident| ident.name); 45 ( 0.00%) let name = pprust::path_to_string(&meta_item.path); . let lint_result = 75 ( 0.00%) self.store.check_lint_name(&name, tool_name, self.registered_tools); 45 ( 0.00%) match &lint_result { . CheckLintNameResult::Ok(ids) => { . let src = LintLevelSource::Node( . meta_item.path.segments.last().expect("empty lint name").ident.name, . sp, . reason, . ); 45 ( 0.00%) for &id in *ids { 75 ( 0.00%) self.check_gated_lint(id, attr.span); 180 ( 0.00%) self.insert_spec(&mut specs, id, (level, src)); . } . } . . CheckLintNameResult::Tool(result) => { . match *result { . Ok(ids) => { . let complete_name = . &format!("{}::{}", tool_ident.unwrap().name, name); -- line 335 ---------------------------------------- -- line 454 ---------------------------------------- . } . db.emit(); . }); . } . } . // If this lint was renamed, apply the new lint instead of ignoring the attribute. . // This happens outside of the match because the new lint should be applied even if . // we don't warn about the name change. 75 ( 0.00%) if let CheckLintNameResult::Warning(_, Some(new_name)) = lint_result { . // Ignore any errors or warnings that happen because the new name is inaccurate . // NOTE: `new_name` already includes the tool name, so we don't have to add it again. . if let CheckLintNameResult::Ok(ids) = . self.store.check_lint_name(&new_name, None, self.registered_tools) . { . let src = LintLevelSource::Node(Symbol::intern(&new_name), sp, reason); . for &id in ids { . self.check_gated_lint(id, attr.span); . self.insert_spec(&mut specs, id, (level, src)); . } . } else { . panic!("renamed lint does not exist: {}", new_name); . } . } 60 ( 0.00%) } . } . 20,400 ( 0.01%) if !is_crate_node { 12 ( 0.00%) for (id, &(level, ref src)) in specs.iter() { 18 ( 0.00%) if !id.lint.crate_level_only { . continue; . } . . let LintLevelSource::Node(lint_attr_name, lint_attr_span, _) = *src else { . continue . }; . . let lint = builtin::UNUSED_ATTRIBUTES; -- line 490 ---------------------------------------- -- line 505 ---------------------------------------- . db.emit(); . }, . ); . // don't set a separate error for every lint in the group . break; . } . } . 10,200 ( 0.01%) let prev = self.cur; 10,200 ( 0.01%) if !specs.is_empty() { 36 ( 0.00%) self.cur = self.sets.list.push(LintSet { specs, parent: prev }); . } . . BuilderPush { prev, changed: prev != self.cur } 91,800 ( 0.05%) } . . /// Checks if the lint is gated on a feature that is not enabled. 161 ( 0.00%) fn check_gated_lint(&self, lint_id: LintId, span: Span) { 69 ( 0.00%) if let Some(feature) = lint_id.lint.feature_gate { . if !self.sess.features_untracked().enabled(feature) { . feature_err( . &self.sess.parse_sess, . feature, . span, . &format!("the `{}` lint is unstable", lint_id.lint.name_lower()), . ) . .emit(); . } . } 184 ( 0.00%) } . . /// Called after `push` when the scope of a set of attributes are exited. . pub fn pop(&mut self, push: BuilderPush) { 13,461 ( 0.01%) self.cur = push.prev; 6,795 ( 0.00%) } . . /// Find the lint level for a lint. 8 ( 0.00%) pub fn lint_level(&self, lint: &'static Lint) -> (Level, LintLevelSource) { 56 ( 0.00%) self.sets.get_lint_level(lint, self.cur, None, self.sess) 12 ( 0.00%) } . . /// Used to emit a lint-related diagnostic based on the current state of . /// this lint context. 44 ( 0.00%) pub fn struct_lint( . &self, . lint: &'static Lint, . span: Option, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { 32 ( 0.00%) let (level, src) = self.lint_level(lint); 4 ( 0.00%) struct_lint_level(self.sess, lint, level, src, span, decorate) 28 ( 0.00%) } . . /// Registers the ID provided with the current set of lints stored in . /// this context. . pub fn register_id(&mut self, id: HirId) { 3 ( 0.00%) self.id_to_set.insert(id, self.cur); . } . . pub fn build_map(self) -> LintLevelMap { 8 ( 0.00%) LintLevelMap { sets: self.sets, id_to_set: self.id_to_set } . } . } . . struct LintLevelMapBuilder<'tcx> { . levels: LintLevelsBuilder<'tcx>, . tcx: TyCtxt<'tcx>, . } . . impl LintLevelMapBuilder<'_> { . fn with_lint_attrs(&mut self, id: hir::HirId, f: F) . where . F: FnOnce(&mut Self), . { . let is_crate_hir = id == hir::CRATE_HIR_ID; 20,298 ( 0.01%) let attrs = self.tcx.hir().attrs(id); 20,340 ( 0.01%) let push = self.levels.push(attrs, is_crate_hir); 3,399 ( 0.00%) if push.changed { . self.levels.register_id(id); . } . f(self); . self.levels.pop(push); . } . } . . impl<'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'tcx> { . type NestedFilter = nested_filter::All; . . fn nested_visit_map(&mut self) -> Self::Map { 53 ( 0.00%) self.tcx.hir() . } . . fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) { 24 ( 0.00%) self.with_lint_attrs(param.hir_id, |builder| { . intravisit::walk_param(builder, param); . }); . } . . fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) { 34 ( 0.00%) self.with_lint_attrs(it.hir_id(), |builder| { 102 ( 0.00%) intravisit::walk_item(builder, it); . }); . } . . fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) { . self.with_lint_attrs(it.hir_id(), |builder| { . intravisit::walk_foreign_item(builder, it); . }) . } . . fn visit_stmt(&mut self, e: &'tcx hir::Stmt<'tcx>) { . // We will call `with_lint_attrs` when we walk . // the `StmtKind`. The outer statement itself doesn't . // define the lint levels. 24 ( 0.00%) intravisit::walk_stmt(self, e); . } . 27 ( 0.00%) fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) { 6,658 ( 0.00%) self.with_lint_attrs(e.hir_id, |builder| { 13,249 ( 0.01%) intravisit::walk_expr(builder, e); . }) 24 ( 0.00%) } . . fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) { . self.with_lint_attrs(s.hir_id, |builder| { . intravisit::walk_field_def(builder, s); . }) . } . . fn visit_variant( -- line 634 ---------------------------------------- -- line 638 ---------------------------------------- . item_id: hir::HirId, . ) { . self.with_lint_attrs(v.id, |builder| { . intravisit::walk_variant(builder, v, g, item_id); . }) . } . . fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) { 2 ( 0.00%) self.with_lint_attrs(l.hir_id, |builder| { 4 ( 0.00%) intravisit::walk_local(builder, l); . }) . } . . fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) { 14 ( 0.00%) self.with_lint_attrs(a.hir_id, |builder| { 28 ( 0.00%) intravisit::walk_arm(builder, a); . }) . } . . fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) { 4 ( 0.00%) self.with_lint_attrs(trait_item.hir_id(), |builder| { 12 ( 0.00%) intravisit::walk_trait_item(builder, trait_item); . }); . } . . fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) { 4 ( 0.00%) self.with_lint_attrs(impl_item.hir_id(), |builder| { 12 ( 0.00%) intravisit::walk_impl_item(builder, impl_item); . }); . } . } . . pub fn provide(providers: &mut Providers) { 2 ( 0.00%) providers.lint_levels = lint_levels; . } 10,405 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs -------------------------------------------------------------------------------- Ir -- line 55 ---------------------------------------- . Immediate::Scalar(ScalarMaybeUninit::from_pointer(p, cx)) . } . . pub fn from_maybe_pointer(p: Pointer>, cx: &impl HasDataLayout) -> Self { . Immediate::Scalar(ScalarMaybeUninit::from_maybe_pointer(p, cx)) . } . . pub fn new_slice(val: Scalar, len: u64, cx: &impl HasDataLayout) -> Self { 2 ( 0.00%) Immediate::ScalarPair(val.into(), Scalar::from_machine_usize(len, cx).into()) . } . . pub fn new_dyn_trait( . val: Scalar, . vtable: Pointer>, . cx: &impl HasDataLayout, . ) -> Self { . Immediate::ScalarPair(val.into(), ScalarMaybeUninit::from_maybe_pointer(vtable, cx)) . } . . #[inline] . pub fn to_scalar_or_uninit(self) -> ScalarMaybeUninit { 10,350 ( 0.01%) match self { 20,696 ( 0.01%) Immediate::Scalar(val) => val, . Immediate::ScalarPair(..) => bug!("Got a scalar pair where a scalar was expected"), . } . } . . #[inline] . pub fn to_scalar(self) -> InterpResult<'tcx, Scalar> { . self.to_scalar_or_uninit().check_init() . } -- line 85 ---------------------------------------- -- line 159 ---------------------------------------- . fn deref(&self) -> &Immediate { . &self.imm . } . } . . /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate, . /// or still in memory. The latter is an optimization, to delay reading that chunk of . /// memory and to avoid having to store arbitrary-sized data here. 11 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, HashStable, Hash, Debug)] . pub enum Operand { . Immediate(Immediate), . Indirect(MemPlace), . } . . #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] . pub struct OpTy<'tcx, Tag: Provenance = AllocId> { . op: Operand, // Keep this private; it helps enforce invariants. -- line 175 ---------------------------------------- -- line 185 ---------------------------------------- . fn deref(&self) -> &Operand { . &self.op . } . } . . impl<'tcx, Tag: Provenance> From> for OpTy<'tcx, Tag> { . #[inline(always)] . fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self { 64 ( 0.00%) OpTy { op: Operand::Indirect(*mplace), layout: mplace.layout } . } . } . . impl<'tcx, Tag: Provenance> From<&'_ MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> { . #[inline(always)] . fn from(mplace: &MPlaceTy<'tcx, Tag>) -> Self { . OpTy { op: Operand::Indirect(**mplace), layout: mplace.layout } . } -- line 201 ---------------------------------------- -- line 248 ---------------------------------------- . . impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { . /// Try reading an immediate in memory; this is interesting particularly for `ScalarPair`. . /// Returns `None` if the layout does not permit loading this as a value. . fn try_read_immediate_from_mplace( . &self, . mplace: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Option>> { 7,125 ( 0.00%) if mplace.layout.is_unsized() { . // Don't touch unsized . return Ok(None); . } . 17,493 ( 0.01%) let alloc = match self.get_alloc(mplace)? { 29,155 ( 0.01%) Some(ptr) => ptr, . None => { . return Ok(Some(ImmTy { . // zero-sized type . imm: Scalar::ZST.into(), . layout: mplace.layout, . })); . } . }; . 46,644 ( 0.02%) match mplace.layout.abi { . Abi::Scalar(..) => { 5,182 ( 0.00%) let scalar = alloc.read_scalar(alloc_range(Size::ZERO, mplace.layout.size))?; . Ok(Some(ImmTy { imm: scalar.into(), layout: mplace.layout })) . } 6 ( 0.00%) Abi::ScalarPair(a, b) => { . // We checked `ptr_align` above, so all fields will have the alignment they need. . // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`, . // which `ptr.offset(b_offset)` cannot possibly fail to satisfy. . let (a, b) = (a.value, b.value); . let (a_size, b_size) = (a.size(self), b.size(self)); . let b_offset = a_size.align_to(b.align(self).abi); 4 ( 0.00%) assert!(b_offset.bytes() > 0); // we later use the offset to tell apart the fields . let a_val = alloc.read_scalar(alloc_range(Size::ZERO, a_size))?; 6 ( 0.00%) let b_val = alloc.read_scalar(alloc_range(b_offset, b_size))?; 10 ( 0.00%) Ok(Some(ImmTy { imm: Immediate::ScalarPair(a_val, b_val), layout: mplace.layout })) . } . _ => Ok(None), . } . } . . /// Try returning an immediate for the operand. . /// If the layout does not permit loading this as an immediate, return where in memory . /// we can find the data. . /// Note that for a given layout, this operation will either always fail or always . /// succeed! Whether it succeeds depends on whether the layout can be represented . /// in an `Immediate`, not on which data is stored there currently. 75,951 ( 0.04%) pub fn try_read_immediate( . &self, . src: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Result, MPlaceTy<'tcx, M::PointerTag>>> { 151,902 ( 0.08%) Ok(match src.try_as_mplace() { . Ok(ref mplace) => { 11,662 ( 0.01%) if let Some(val) = self.try_read_immediate_from_mplace(mplace)? { . Ok(val) . } else { . Err(*mplace) . } . } 26,080 ( 0.01%) Err(val) => Ok(val), . }) 75,951 ( 0.04%) } . . /// Read an immediate from a place, asserting that that is possible with the given layout. . #[inline(always)] . pub fn read_immediate( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> { 15,585 ( 0.01%) if let Ok(imm) = self.try_read_immediate(op)? { 41,498 ( 0.02%) Ok(imm) . } else { . span_bug!(self.cur_span(), "primitive read failed for type: {:?}", op.layout.ty); . } . } . . /// Read a scalar from a place 56,914 ( 0.03%) pub fn read_scalar( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, ScalarMaybeUninit> { 5,174 ( 0.00%) Ok(self.read_immediate(op)?.to_scalar_or_uninit()) 46,566 ( 0.02%) } . . /// Read a pointer from a place. . pub fn read_pointer( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Pointer>> { . Ok(self.scalar_to_ptr(self.read_scalar(op)?.check_init()?)) . } -- line 342 ---------------------------------------- -- line 345 ---------------------------------------- . pub fn read_str(&self, mplace: &MPlaceTy<'tcx, M::PointerTag>) -> InterpResult<'tcx, &str> { . let len = mplace.len(self)?; . let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len))?; . let str = std::str::from_utf8(bytes).map_err(|err| err_ub!(InvalidStr(err)))?; . Ok(str) . } . . /// Projection functions 51,730 ( 0.03%) pub fn operand_field( . &self, . op: &OpTy<'tcx, M::PointerTag>, . field: usize, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . let base = match op.try_as_mplace() { . Ok(ref mplace) => { . // We can reuse the mplace field computation logic for indirect operands. . let field = self.mplace_field(mplace, field)?; 56,903 ( 0.03%) return Ok(field.into()); . } . Err(value) => value, . }; . . let field_layout = op.layout.field(self, field); . if field_layout.is_zst() { . let immediate = Scalar::ZST.into(); . return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout }); -- line 370 ---------------------------------------- -- line 381 ---------------------------------------- . Immediate::Scalar(val) => span_bug!( . self.cur_span(), . "field access on non aggregate {:#?}, {:#?}", . val, . op.layout . ), . }; . Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout }) 46,557 ( 0.02%) } . . pub fn operand_index( . &self, . op: &OpTy<'tcx, M::PointerTag>, . index: u64, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . if let Ok(index) = usize::try_from(index) { . // We can just treat this as a field. -- line 397 ---------------------------------------- -- line 398 ---------------------------------------- . self.operand_field(op, index) . } else { . // Indexing into a big array. This must be an mplace. . let mplace = op.assert_mem_place(); . Ok(self.mplace_index(&mplace, index)?.into()) . } . } . 22 ( 0.00%) pub fn operand_downcast( . &self, . op: &OpTy<'tcx, M::PointerTag>, . variant: VariantIdx, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . // Downcasts only change the layout 34 ( 0.00%) Ok(match op.try_as_mplace() { 20 ( 0.00%) Ok(ref mplace) => self.mplace_downcast(mplace, variant)?.into(), . Err(..) => { . let layout = op.layout.for_variant(self, variant); . OpTy { layout, ..*op } . } . }) 18 ( 0.00%) } . 16 ( 0.00%) pub fn operand_projection( . &self, . base: &OpTy<'tcx, M::PointerTag>, . proj_elem: mir::PlaceElem<'tcx>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . use rustc_middle::mir::ProjectionElem::*; 64 ( 0.00%) Ok(match proj_elem { 6 ( 0.00%) Field(field, _) => self.operand_field(base, field.index())?, 6 ( 0.00%) Downcast(_, variant) => self.operand_downcast(base, variant)?, . Deref => self.deref_operand(base)?.into(), . Subslice { .. } | ConstantIndex { .. } | Index(_) => { . // The rest should only occur as mplace, we do not use Immediates for types . // allowing such operations. This matches place_projection forcing an allocation. . let mplace = base.assert_mem_place(); . self.mplace_projection(&mplace, proj_elem)?.into() . } . }) 16 ( 0.00%) } . . /// Converts a repr(simd) operand into an operand where `place_index` accesses the SIMD elements. . /// Also returns the number of elements. . pub fn operand_to_simd( . &self, . base: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, u64)> { . // Basically we just transmute this place into an array following simd_size_and_type. -- line 446 ---------------------------------------- -- line 449 ---------------------------------------- . self.mplace_to_simd(&base.assert_mem_place()) . } . . /// Read from a local. Will not actually access the local if reading from a ZST. . /// Will not access memory, instead an indirect `Operand` is returned. . /// . /// This is public because it is used by [priroda](https://github.com/oli-obk/priroda) to get an . /// OpTy from a local 6,747 ( 0.00%) pub fn access_local( . &self, . frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>, . local: mir::Local, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . let layout = self.layout_of_local(frame, local, layout)?; 647 ( 0.00%) let op = if layout.is_zst() { . // Do not read from ZST, they might not be initialized . Operand::Immediate(Scalar::ZST.into()) . } else { 213 ( 0.00%) M::access_local(&self, frame, local)? . }; 8,567 ( 0.00%) Ok(OpTy { op, layout }) 5,879 ( 0.00%) } . . /// Every place can be read from, so we can turn them into an operand. . /// This will definitely return `Indirect` if the place is a `Ptr`, i.e., this . /// will never actually read from memory. . #[inline(always)] . pub fn place_to_op( . &self, . place: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { 6 ( 0.00%) let op = match **place { . Place::Ptr(mplace) => Operand::Indirect(mplace), . Place::Local { frame, local } => { 27 ( 0.00%) *self.access_local(&self.stack()[frame], local, None)? . } . }; 14 ( 0.00%) Ok(OpTy { op, layout: place.layout }) . } . . // Evaluate a place with the goal of reading from it. This lets us sometimes . // avoid allocations. 5,736 ( 0.00%) pub fn eval_place_to_op( . &self, . place: mir::Place<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . // Do not use the layout passed in as argument if the base we are looking at . // here is not the entire place. 717 ( 0.00%) let layout = if place.projection.is_empty() { layout } else { None }; . 2,151 ( 0.00%) let base_op = self.access_local(self.frame(), place.local, layout)?; . . let op = place . .projection . .iter() 36 ( 0.00%) .try_fold(base_op, |op, elem| self.operand_projection(&op, elem))?; . . trace!("eval_place_to_op: got {:?}", *op); . // Sanity-check the type we ended up with. . debug_assert!(mir_assign_valid_types( . *self.tcx, . self.param_env, . self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions( . place.ty(&self.frame().body.local_decls, *self.tcx).ty . )?)?, . op.layout, . )); 1,953 ( 0.00%) Ok(op) 6,453 ( 0.00%) } . . /// Evaluate the operand, returning a place where you can then find the data. . /// If you already know the layout, you can save two table lookups . /// by passing it in here. . #[inline] 29,142 ( 0.01%) pub fn eval_operand( . &self, . mir_op: &mir::Operand<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . use rustc_middle::mir::Operand::*; 6,621 ( 0.00%) let op = match *mir_op { . // FIXME: do some more logic on `move` to invalidate the old location 3,493 ( 0.00%) Copy(place) | Move(place) => self.eval_place_to_op(place, layout)?, . . Constant(ref constant) => { . let val = 38,984 ( 0.02%) self.subst_from_current_frame_and_normalize_erasing_regions(constant.literal)?; . // This can still fail: . // * During ConstProp, with `TooGeneric` or since the `requried_consts` were not all . // checked yet. . // * During CTFE, since promoteds in `const`/`static` initializer bodies can fail. . 25 ( 0.00%) self.mir_const_to_op(&val, layout)? . } . }; . trace!("{:?}: {:?}", mir_op, *op); 42,164 ( 0.02%) Ok(op) 19,428 ( 0.01%) } . . /// Evaluate a bunch of operands at once . pub(super) fn eval_operands( . &self, . ops: &[mir::Operand<'tcx>], . ) -> InterpResult<'tcx, Vec>> { . ops.iter().map(|op| self.eval_operand(op, None)).collect() . } . . // Used when the miri-engine runs into a constant and for extracting information from constants . // in patterns via the `const_eval` module . /// The `val` and `layout` are assumed to already be in our interpreter . /// "universe" (param_env). 31,092 ( 0.02%) pub fn const_to_op( . &self, . val: &ty::Const<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { 13,150 ( 0.01%) match val.val { . ty::ConstKind::Param(_) | ty::ConstKind::Bound(..) => throw_inval!(TooGeneric), . ty::ConstKind::Error(_) => throw_inval!(AlreadyReported(ErrorReported)), 4 ( 0.00%) ty::ConstKind::Unevaluated(uv) => { . let instance = self.resolve(uv.def, uv.substs)?; 11 ( 0.00%) Ok(self.eval_to_allocation(GlobalId { instance, promoted: uv.promoted })?.into()) . } . ty::ConstKind::Infer(..) | ty::ConstKind::Placeholder(..) => { . span_bug!(self.cur_span(), "const_to_op: Unexpected ConstKind {:?}", val) . } 26,138 ( 0.01%) ty::ConstKind::Value(val_val) => self.const_val_to_op(val_val, val.ty, layout), . } 23,319 ( 0.01%) } . 429 ( 0.00%) pub fn mir_const_to_op( . &self, . val: &mir::ConstantKind<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { 5,260 ( 0.00%) match val { 10,442 ( 0.01%) mir::ConstantKind::Ty(ct) => self.const_to_op(ct, layout), . mir::ConstantKind::Val(val, ty) => self.const_val_to_op(*val, ty, layout), . } 351 ( 0.00%) } . 26,290 ( 0.01%) crate fn const_val_to_op( . &self, . val_val: ConstValue<'tcx>, . ty: Ty<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . // Other cases need layout. . let tag_scalar = |scalar| -> InterpResult<'tcx, _> { 15,774 ( 0.01%) Ok(match scalar { . Scalar::Ptr(ptr, size) => Scalar::Ptr(self.global_base_pointer(ptr)?, size), 7,884 ( 0.00%) Scalar::Int(int) => Scalar::Int(int), . }) . }; 102 ( 0.00%) let layout = from_known_layout(self.tcx, self.param_env, layout, || self.layout_of(ty))?; 7,887 ( 0.00%) let op = match val_val { . ConstValue::ByRef { alloc, offset } => { . let id = self.tcx.create_memory_alloc(alloc); . // We rely on mutability being set correctly in that allocation to prevent writes . // where none should happen. . let ptr = self.global_base_pointer(Pointer::new(id, offset))?; . Operand::Indirect(MemPlace::from_ptr(ptr.into(), layout.align.abi)) . } 23,699 ( 0.01%) ConstValue::Scalar(x) => Operand::Immediate(tag_scalar(x)?.into()), . ConstValue::Slice { data, start, end } => { . // We rely on mutability being set correctly in `data` to prevent writes . // where none should happen. . let ptr = Pointer::new( . self.tcx.create_memory_alloc(data), . Size::from_bytes(start), // offset: `start` . ); . Operand::Immediate(Immediate::new_slice( . Scalar::from_pointer(self.global_base_pointer(ptr)?, &*self.tcx), . u64::try_from(end.checked_sub(start).unwrap()).unwrap(), // len: `end - start` . self, . )) . } . }; 55,209 ( 0.03%) Ok(OpTy { op, layout }) 21,032 ( 0.01%) } . . /// Read discriminant, return the runtime value as well as the variant index. . /// Can also legally be called on non-enums (e.g. through the discriminant_value intrinsic)! . pub fn read_discriminant( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, (Scalar, VariantIdx)> { . trace!("read_discriminant_value {:#?}", op.layout); -- line 638 ---------------------------------------- 170,865 ( 0.09%) -------------------------------------------------------------------------------- -- 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 { 256,816 ( 0.13%) Vec { buf: RawVec::NEW, len: 0 } 28 ( 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 { 51,681 ( 0.03%) 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,487 ( 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 { 79,163 ( 0.04%) 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) { 23,730 ( 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) { 465 ( 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. 2,620 ( 0.00%) if self.capacity() > self.len { 405 ( 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(); 764 ( 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")] 36,162 ( 0.02%) 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. 38,233 ( 0.02%) 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); 25,289 ( 0.01%) self.len = len; 112 ( 0.00%) ptr::drop_in_place(s); . } 43,392 ( 0.02%) } . . /// 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. 257,001 ( 0.13%) 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. 464,056 ( 0.24%) 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()); . 93,875 ( 0.05%) self.len = new_len; 230 ( 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 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")] 105 ( 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); . } . 15 ( 0.00%) let len = self.len(); 30 ( 0.00%) if index > len { . assert_failed(index, len); . } . . // space for the new element 70 ( 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.) 105 ( 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); . } 70 ( 0.00%) self.set_len(len + 1); . } 90 ( 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); . } . 34 ( 0.00%) let len = self.len(); 133 ( 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. 48 ( 0.00%) ret = ptr::read(ptr); . . // Shift everything down to fill in that spot. 114 ( 0.00%) ptr::copy(ptr.offset(1), ptr, len - index - 1); . } 34 ( 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,311 ( 0.00%) pub fn retain(&mut self, mut f: F) . where . F: FnMut(&T) -> bool, . { 195 ( 0.00%) self.retain_mut(|elem| f(elem)); 5,216 ( 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, . { 658 ( 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) { 404 ( 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), 259 ( 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, . { 21,135 ( 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) }; 6,958 ( 0.00%) if !f(cur) { . // Advance early to avoid double drop if `drop_in_place` panicked. 3,939 ( 0.00%) g.processed_len += 1; 3,900 ( 0.00%) g.deleted_cnt += 1; . // SAFETY: We never touch this element again after dropped. 3,879 ( 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 { 102 ( 0.00%) let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt); . ptr::copy_nonoverlapping(cur, hole_slot, 1); . } . } 96 ( 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")] 14 ( 0.00%) pub fn dedup_by(&mut self, mut same_bucket: F) . where . F: FnMut(&mut T, &mut T) -> bool, . { 16 ( 0.00%) let len = self.len(); 118 ( 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 { 90 ( 0.00%) while gap.read < len { . let read_ptr = ptr.add(gap.read); . let prev_ptr = ptr.add(gap.write.wrapping_sub(1)); . . 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); -- line 1686 ---------------------------------------- -- line 1688 ---------------------------------------- . 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 */ 54 ( 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); . } 16 ( 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")] 5 ( 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. 1,113,814 ( 0.56%) if self.len == self.buf.capacity() { 20,928 ( 0.01%) self.buf.reserve_for_push(self.len); . } . unsafe { 8,978 ( 0.00%) let end = self.as_mut_ptr().add(self.len); . ptr::write(end, value); 1,325,755 ( 0.67%) self.len += 1; . } 4 ( 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 { 81,553 ( 0.04%) if self.len == 0 { 3 ( 0.00%) None . } else { . unsafe { 81,603 ( 0.04%) self.len -= 1; 2,587 ( 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")] 21 ( 0.00%) pub fn append(&mut self, other: &mut Self) { . unsafe { . self.append_elements(other.as_slice() as _); . other.set_len(0); . } 18 ( 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); 8,290 ( 0.00%) let len = self.len(); . unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; 57,154 ( 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. . // 885 ( 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). 1,972 ( 0.00%) let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); 67 ( 0.00%) Drain { . tail_start: end, 1,322 ( 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) { 64,935 ( 0.03%) 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 { 45,621 ( 0.02%) 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); . } . 38 ( 0.00%) if at > self.len() { . assert_failed(at, self.len()); . } . 34 ( 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")] 432 ( 0.00%) pub fn resize_with(&mut self, new_len: usize, f: F) . where . F: FnMut() -> T, . { 58 ( 0.00%) let len = self.len(); 116 ( 0.00%) if new_len > len { 764 ( 0.00%) self.extend_with(new_len - len, ExtendFunc(f)); . } else { . self.truncate(new_len); . } 374 ( 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( 2 ( 0.00%) self.as_mut_ptr().add(self.len) as *mut MaybeUninit, 23 ( 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")] 520 ( 0.00%) pub fn resize(&mut self, new_len: usize, value: T) { 52 ( 0.00%) let len = self.len(); . 156 ( 0.00%) if new_len > len { 207 ( 0.00%) self.extend_with(new_len - len, ExtendElement(value)) . } else { . self.truncate(new_len); . } 92 ( 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 { 5,828 ( 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. 4,605 ( 0.00%) fn extend_with>(&mut self, n: usize, mut value: E) { . self.reserve(n); . . unsafe { 260 ( 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); . } . 5,844 ( 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,663 ( 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) { 3 ( 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")] 799 ( 0.00%) pub fn from_elem(elem: T, n: usize) -> Vec { 5,554 ( 0.00%) ::from_elem(elem, n, Global) 818 ( 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] { 383,259 ( 0.19%) unsafe { slice::from_raw_parts(self.as_ptr(), self.len) } 7 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::DerefMut for Vec { . fn deref_mut(&mut self) -> &mut [T] { 75,327 ( 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))] 8,850 ( 0.00%) fn clone(&self) -> Self { . let alloc = self.allocator().clone(); 2 ( 0.00%) <[T]>::to_vec_in(&**self, alloc) 10,599 ( 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,385 ( 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`" . )] -- line 2534 ---------------------------------------- -- line 2539 ---------------------------------------- . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl FromIterator for Vec { . #[inline] . fn from_iter>(iter: I) -> Vec { 84,039 ( 0.04%) >::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 { 58,433 ( 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(); 27,284 ( 0.01%) IntoIter { . buf: NonNull::new_unchecked(begin), . phantom: PhantomData, . cap, . alloc, . ptr: begin, . end, . } . } -- line 2589 ---------------------------------------- -- line 2601 ---------------------------------------- . } . . #[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> { 626 ( 0.00%) self.iter_mut() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend for Vec { . #[inline] 64 ( 0.00%) fn extend>(&mut self, iter: I) { 10,839 ( 0.01%) >::spec_extend(self, iter.into_iter()) 64 ( 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); . // } 1,734 ( 0.00%) while let Some(element) = iterator.next() { 200 ( 0.00%) let len = self.len(); 4,074 ( 0.00%) if len == self.capacity() { 38 ( 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 3,156 ( 0.00%) self.set_len(len + 1); . } . } 40 ( 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, . { 7,150 ( 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, . { 99 ( 0.00%) let old_len = self.len(); . . // Guard against us getting leaked (leak amplification) . unsafe { . self.set_len(0); . } . 296 ( 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. . /// -- line 2768 ---------------------------------------- -- 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 { 76,917 ( 0.04%) 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 22,511 ( 0.01%) ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len)) . } . // RawVec handles deallocation 90,610 ( 0.05%) } . } . . #[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 ---------------------------------------- 161,190 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/vec_deque/mod.rs -------------------------------------------------------------------------------- Ir -- line 126 ---------------------------------------- . self.extend(remainder.iter().cloned()); . } . } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl<#[may_dangle] T, A: Allocator> Drop for VecDeque { 294 ( 0.00%) fn drop(&mut self) { . /// Runs the destructor for all items in the slice when it gets dropped (normally or . /// during unwinding). . struct Dropper<'a, T>(&'a mut [T]); . . impl<'a, T> Drop for Dropper<'a, T> { . fn drop(&mut self) { . unsafe { . ptr::drop_in_place(self.0); -- line 142 ---------------------------------------- -- line 146 ---------------------------------------- . . let (front, back) = self.as_mut_slices(); . unsafe { . let _back_dropper = Dropper(back); . // use drop for [T] . ptr::drop_in_place(front); . } . // RawVec handles deallocation 336 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Default for VecDeque { . /// Creates an empty `VecDeque`. . #[inline] . fn default() -> VecDeque { . VecDeque::new() . } . } . . impl VecDeque { . /// Marginally more convenient . #[inline] . fn ptr(&self) -> *mut T { 33,754 ( 0.02%) self.buf.ptr() . } . . /// Marginally more convenient . #[inline] . fn cap(&self) -> usize { . if mem::size_of::() == 0 { . // For zero sized types, we are always at maximum capacity . MAXIMUM_ZST_CAPACITY . } else { 37,304 ( 0.02%) self.buf.capacity() . } . } . . /// Turn ptr into a slice . #[inline] . unsafe fn buffer_as_slice(&self) -> &[T] { . unsafe { slice::from_raw_parts(self.ptr(), self.cap()) } . } -- line 188 ---------------------------------------- -- line 191 ---------------------------------------- . #[inline] . unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] { . unsafe { slice::from_raw_parts_mut(self.ptr(), self.cap()) } . } . . /// Moves an element out of the buffer . #[inline] . unsafe fn buffer_read(&mut self, off: usize) -> T { 1,446 ( 0.00%) unsafe { ptr::read(self.ptr().add(off)) } . } . . /// Writes an element into the buffer, moving it. . #[inline] . unsafe fn buffer_write(&mut self, off: usize, value: T) { . unsafe { . ptr::write(self.ptr().add(off), value); . } . } . . /// Returns `true` if the buffer is at full capacity. . #[inline] . fn is_full(&self) -> bool { 82,965 ( 0.04%) self.cap() - self.len() == 1 . } . . /// Returns the index in the underlying buffer for a given logical element . /// index. . #[inline] . fn wrap_index(&self, idx: usize) -> usize { . wrap_index(idx, self.cap()) . } -- line 221 ---------------------------------------- -- line 452 ---------------------------------------- . // [o o . o o o o o ] . // T H . // B [. . . o o o o o o o . . . . . . ] . // H T . // [o o o o o . o o ] . // H T . // C [o o o o o . . . . . . . . . o o ] . 28 ( 0.00%) if self.tail <= self.head { . // A . // Nop . } else if self.head < old_capacity - self.tail { . // B . unsafe { . self.copy_nonoverlapping(old_capacity, 0, self.head); . } . self.head += old_capacity; -- line 468 ---------------------------------------- -- line 507 ---------------------------------------- . /// use std::collections::VecDeque; . /// . /// let vector: VecDeque = VecDeque::with_capacity(10); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] . pub fn with_capacity(capacity: usize) -> VecDeque { 110 ( 0.00%) Self::with_capacity_in(capacity, Global) . } . } . . impl VecDeque { . /// Creates an empty `VecDeque`. . /// . /// # Examples . /// -- line 523 ---------------------------------------- -- line 524 ---------------------------------------- . /// ``` . /// use std::collections::VecDeque; . /// . /// let vector: VecDeque = VecDeque::new(); . /// ``` . #[inline] . #[unstable(feature = "allocator_api", issue = "32838")] . pub fn new_in(alloc: A) -> VecDeque { 50 ( 0.00%) VecDeque::with_capacity_in(INITIAL_CAPACITY, alloc) . } . . /// Creates an empty `VecDeque` with space for at least `capacity` elements. . /// . /// # Examples . /// . /// ``` . /// use std::collections::VecDeque; . /// . /// let vector: VecDeque = VecDeque::with_capacity(10); . /// ``` . #[unstable(feature = "allocator_api", issue = "32838")] 320 ( 0.00%) pub fn with_capacity_in(capacity: usize, alloc: A) -> VecDeque { 232 ( 0.00%) assert!(capacity < 1_usize << usize::BITS - 1, "capacity overflow"); . // +1 since the ringbuffer always leaves one space empty . let cap = cmp::max(capacity + 1, MINIMUM_CAPACITY + 1).next_power_of_two(); . 516 ( 0.00%) VecDeque { tail: 0, head: 0, buf: RawVec::with_capacity_in(cap, alloc) } 480 ( 0.00%) } . . /// Provides a reference to the element at the given index. . /// . /// Element at index 0 is the front of the queue. . /// . /// # Examples . /// . /// ``` -- line 559 ---------------------------------------- -- line 562 ---------------------------------------- . /// let mut buf = VecDeque::new(); . /// buf.push_back(3); . /// buf.push_back(4); . /// buf.push_back(5); . /// assert_eq!(buf.get(1), Some(&4)); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn get(&self, index: usize) -> Option<&T> { 126,801 ( 0.06%) if index < self.len() { . let idx = self.wrap_add(self.tail, index); . unsafe { Some(&*self.ptr().add(idx)) } . } else { . None . } . } . . /// Provides a mutable reference to the element at the given index. -- line 578 ---------------------------------------- -- line 591 ---------------------------------------- . /// if let Some(elem) = buf.get_mut(1) { . /// *elem = 7; . /// } . /// . /// assert_eq!(buf[1], 7); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn get_mut(&mut self, index: usize) -> Option<&mut T> { 65,366 ( 0.03%) if index < self.len() { . let idx = self.wrap_add(self.tail, index); . unsafe { Some(&mut *self.ptr().add(idx)) } . } else { . None . } . } . . /// Swaps elements at indices `i` and `j`. -- line 607 ---------------------------------------- -- line 924 ---------------------------------------- . /// buf.push_back(5); . /// buf.push_back(10); . /// buf.push_back(15); . /// assert_eq!(buf, [5, 10, 15]); . /// buf.truncate(1); . /// assert_eq!(buf, [5]); . /// ``` . #[stable(feature = "deque_extras", since = "1.16.0")] 16 ( 0.00%) pub fn truncate(&mut self, len: usize) { . /// Runs the destructor for all items in the slice when it gets dropped (normally or . /// during unwinding). . struct Dropper<'a, T>(&'a mut [T]); . . impl<'a, T> Drop for Dropper<'a, T> { . fn drop(&mut self) { . unsafe { . ptr::drop_in_place(self.0); -- line 940 ---------------------------------------- -- line 945 ---------------------------------------- . // Safe because: . // . // * Any slice passed to `drop_in_place` is valid; the second case has . // `len <= front.len()` and returning on `len > self.len()` ensures . // `begin <= back.len()` in the first case . // * The head of the VecDeque is moved before calling `drop_in_place`, . // so no value is dropped twice if `drop_in_place` panics . unsafe { 4 ( 0.00%) if len > self.len() { . return; . } . let num_dropped = self.len() - len; . let (front, back) = self.as_mut_slices(); 4 ( 0.00%) if len > front.len() { . let begin = len - front.len(); . let drop_back = back.get_unchecked_mut(begin..) as *mut _; . self.head = self.wrap_sub(self.head, num_dropped); . ptr::drop_in_place(drop_back); . } else { . let drop_back = back as *mut _; . let drop_front = front.get_unchecked_mut(len..) as *mut _; 2 ( 0.00%) self.head = self.wrap_sub(self.head, num_dropped); . . // Make sure the second half is dropped even when a destructor . // in the first one panics. . let _back_dropper = Dropper(&mut *drop_back); . ptr::drop_in_place(drop_front); . } . } 16 ( 0.00%) } . . /// Returns a reference to the underlying allocator. . #[unstable(feature = "allocator_api", issue = "32838")] . #[inline] . pub fn allocator(&self) -> &A { . self.buf.allocator() . } . -- line 982 ---------------------------------------- -- line 1085 ---------------------------------------- . /// vector.as_mut_slices().0[0] = 42; . /// vector.as_mut_slices().1[0] = 24; . /// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..])); . /// ``` . #[inline] . #[stable(feature = "deque_extras_15", since = "1.5.0")] . pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) { . unsafe { 175 ( 0.00%) let head = self.head; 175 ( 0.00%) let tail = self.tail; 201 ( 0.00%) let buf = self.buffer_as_mut_slice(); . RingSlices::ring_slices(buf, head, tail) . } . } . . /// Returns the number of elements in the `VecDeque`. . /// . /// # Examples . /// -- line 1103 ---------------------------------------- -- line 1106 ---------------------------------------- . /// . /// let mut v = VecDeque::new(); . /// assert_eq!(v.len(), 0); . /// v.push_back(1); . /// assert_eq!(v.len(), 1); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn len(&self) -> usize { 57,592 ( 0.03%) count(self.tail, self.head, self.cap()) . } . . /// Returns `true` if the `VecDeque` is empty. . /// . /// # Examples . /// . /// ``` . /// use std::collections::VecDeque; -- line 1122 ---------------------------------------- -- line 1123 ---------------------------------------- . /// . /// let mut v = VecDeque::new(); . /// assert!(v.is_empty()); . /// v.push_front(1); . /// assert!(!v.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn is_empty(&self) -> bool { 113,381 ( 0.06%) self.tail == self.head . } . . fn range_tail_head(&self, range: R) -> (usize, usize) . where . R: RangeBounds, . { . let Range { start, end } = slice::range(range, ..self.len()); . let tail = self.wrap_add(self.tail, start); -- line 1139 ---------------------------------------- -- line 1307 ---------------------------------------- . /// let mut v = VecDeque::new(); . /// v.push_back(1); . /// v.clear(); . /// assert!(v.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn clear(&mut self) { 4 ( 0.00%) self.truncate(0); . } . . /// Returns `true` if the `VecDeque` contains an element equal to the . /// given value. . /// . /// # Examples . /// . /// ``` -- line 1323 ---------------------------------------- -- line 1396 ---------------------------------------- . /// assert_eq!(d.back(), None); . /// . /// d.push_back(1); . /// d.push_back(2); . /// assert_eq!(d.back(), Some(&2)); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn back(&self) -> Option<&T> { 2,587 ( 0.00%) self.get(self.len().wrapping_sub(1)) . } . . /// Provides a mutable reference to the back element, or `None` if the . /// `VecDeque` is empty. . /// . /// # Examples . /// . /// ``` -- line 1412 ---------------------------------------- -- line 1441 ---------------------------------------- . /// d.push_back(2); . /// . /// assert_eq!(d.pop_front(), Some(1)); . /// assert_eq!(d.pop_front(), Some(2)); . /// assert_eq!(d.pop_front(), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn pop_front(&mut self) -> Option { 18,426 ( 0.01%) if self.is_empty() { . None . } else { . let tail = self.tail; 35,016 ( 0.02%) self.tail = self.wrap_add(self.tail, 1); 499 ( 0.00%) unsafe { Some(self.buffer_read(tail)) } . } . } . . /// Removes the last element from the `VecDeque` and returns it, or `None` if . /// it is empty. . /// . /// # Examples . /// -- line 1462 ---------------------------------------- -- line 1466 ---------------------------------------- . /// let mut buf = VecDeque::new(); . /// assert_eq!(buf.pop_back(), None); . /// buf.push_back(1); . /// buf.push_back(3); . /// assert_eq!(buf.pop_back(), Some(3)); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn pop_back(&mut self) -> Option { 10,029 ( 0.01%) if self.is_empty() { . None . } else { 16,173 ( 0.01%) self.head = self.wrap_sub(self.head, 1); . let head = self.head; . unsafe { Some(self.buffer_read(head)) } . } . } . . /// Prepends an element to the `VecDeque`. . /// . /// # Examples -- line 1485 ---------------------------------------- -- line 1513 ---------------------------------------- . /// use std::collections::VecDeque; . /// . /// let mut buf = VecDeque::new(); . /// buf.push_back(1); . /// buf.push_back(3); . /// assert_eq!(3, *buf.back().unwrap()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 67,296 ( 0.03%) pub fn push_back(&mut self, value: T) { 82,963 ( 0.04%) if self.is_full() { 13 ( 0.00%) self.grow(); . } . 7 ( 0.00%) let head = self.head; 27,661 ( 0.01%) self.head = self.wrap_add(self.head, 1); 10,830 ( 0.01%) unsafe { self.buffer_write(head, value) } 67,296 ( 0.03%) } . . #[inline] . fn is_contiguous(&self) -> bool { . // FIXME: Should we consider `head == 0` to mean . // that `self` is contiguous? . self.tail <= self.head . } . -- line 1537 ---------------------------------------- -- line 2209 ---------------------------------------- . self.truncate(idx); . } . } . . // Double the buffer size. This method is inline(never), so we expect it to only . // be called in cold paths. . // This may panic or abort . #[inline(never)] 42 ( 0.00%) fn grow(&mut self) { . // Extend or possibly remove this assertion when valid use-cases for growing the . // buffer without it being full emerge . debug_assert!(self.is_full()); . let old_cap = self.cap(); 21 ( 0.00%) self.buf.reserve_exact(old_cap, old_cap); 35 ( 0.00%) assert!(self.cap() == old_cap * 2); . unsafe { . self.handle_capacity_increase(old_cap); . } . debug_assert!(!self.is_full()); 42 ( 0.00%) } . . /// Modifies the `VecDeque` in-place so that `len()` is equal to `new_len`, . /// either by removing excess elements from the back or by appending . /// elements generated by calling `generator` to the back. . /// . /// # Examples . /// . /// ``` -- line 2236 ---------------------------------------- -- line 2751 ---------------------------------------- . } . } . . /// Returns the index in the underlying buffer for a given logical element index. . #[inline] . fn wrap_index(index: usize, size: usize) -> usize { . // size is always a power of 2 . debug_assert!(size.is_power_of_two()); 145,504 ( 0.07%) index & (size - 1) . } . . /// Calculate the number of elements left to be read in the buffer . #[inline] . fn count(tail: usize, head: usize, size: usize) -> usize { . // size is always a power of 2 241,335 ( 0.12%) (head.wrapping_sub(tail)) & (size - 1) . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq for VecDeque { . fn eq(&self, other: &Self) -> bool { . if self.len() != other.len() { . return false; . } -- line 2774 ---------------------------------------- -- line 2902 ---------------------------------------- . . fn into_iter(self) -> IterMut<'a, T> { . self.iter_mut() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend for VecDeque { 168 ( 0.00%) fn extend>(&mut self, iter: I) { . // This function should be the moral equivalent of: . // . // for item in iter.into_iter() { . // self.push_back(item); . // } . let mut iter = iter.into_iter(); . while let Some(element) = iter.next() { 129 ( 0.00%) if self.len() == self.capacity() { . let (lower, _) = iter.size_hint(); . self.reserve(lower.saturating_add(1)); . } . . let head = self.head; 26 ( 0.00%) self.head = self.wrap_add(self.head, 1); . unsafe { 16 ( 0.00%) self.buffer_write(head, element); . } . } 192 ( 0.00%) } . . #[inline] . fn extend_one(&mut self, elem: T) { . self.push_back(elem); . } . . #[inline] . fn extend_reserve(&mut self, additional: usize) { -- line 2937 ---------------------------------------- 40,262 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/encoder.rs -------------------------------------------------------------------------------- Ir -- line 83 ---------------------------------------- . if $self.is_proc_macro { . return Lazy::empty(); . } . }; . } . . macro_rules! encoder_methods { . ($($name:ident($ty:ty);)*) => { 1,050 ( 0.00%) $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> { . self.opaque.$name(value) 1,260 ( 0.00%) })* . } . } . . impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> { . type Error = ::Error; . . #[inline] . fn emit_unit(&mut self) -> Result<(), Self::Error> { -- line 101 ---------------------------------------- -- line 125 ---------------------------------------- . emit_raw_bytes(&[u8]); . } . } . . impl<'a, 'tcx, T: Encodable>> Encodable> . for Lazy . { . fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 102 ( 0.00%) e.emit_lazy_distance(*self) . } . } . . impl<'a, 'tcx, T: Encodable>> Encodable> . for Lazy<[T]> . { 15 ( 0.00%) fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . e.emit_usize(self.meta)?; 56 ( 0.00%) if self.meta == 0 { . return Ok(()); . } 106 ( 0.00%) e.emit_lazy_distance(*self) 6 ( 0.00%) } . } . . impl<'a, 'tcx, I: Idx, T: Encodable>> Encodable> . for Lazy> . where . Option: FixedSizeEncoding, . { . fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . e.emit_usize(self.meta)?; 144 ( 0.00%) e.emit_lazy_distance(*self) . } . } . . impl<'a, 'tcx> Encodable> for CrateNum { 420 ( 0.00%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 588 ( 0.00%) if *self != LOCAL_CRATE && s.is_proc_macro { . panic!("Attempted to encode non-local CrateNum {:?} for proc-macro crate", self); . } . s.emit_u32(self.as_u32()) 360 ( 0.00%) } . } . . impl<'a, 'tcx> Encodable> for DefIndex { 310 ( 0.00%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . s.emit_u32(self.as_u32()) 372 ( 0.00%) } . } . . impl<'a, 'tcx> Encodable> for ExpnIndex { . fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . s.emit_u32(self.as_u32()) . } . } . . impl<'a, 'tcx> Encodable> for SyntaxContext { 35,995 ( 0.02%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 21,597 ( 0.01%) rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s) 43,194 ( 0.02%) } . } . . impl<'a, 'tcx> Encodable> for ExpnId { . fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 54 ( 0.00%) if self.krate == LOCAL_CRATE { . // We will only write details for local expansions. Non-local expansions will fetch . // data from the corresponding crate's metadata. . // FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external . // metadata from proc-macro crates. 184 ( 0.00%) s.hygiene_ctxt.schedule_expn_data_for_encoding(*self); . } 126 ( 0.00%) self.krate.encode(s)?; . self.local_id.encode(s) . } . } . . impl<'a, 'tcx> Encodable> for Span { 57,472 ( 0.03%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 43,104 ( 0.02%) let span = self.data(); . . // Don't serialize any `SyntaxContext`s from a proc-macro crate, . // since we don't load proc-macro dependencies during serialization. . // This means that any hygiene information from macros used *within* . // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro . // definition) will be lost. . // . // This can show up in two ways: -- line 211 ---------------------------------------- -- line 228 ---------------------------------------- . // None of these user-visible effects should result in any . // cross-crate inconsistencies (getting one behavior in the same . // crate, and a different behavior in another crate) due to the . // limited surface that proc-macros can expose. . // . // IMPORTANT: If this is ever changed, be sure to update . // `rustc_span::hygiene::raw_encode_expn_id` to handle . // encoding `ExpnData` for proc-macro crates. 14,368 ( 0.01%) if s.is_proc_macro { . SyntaxContext::root().encode(s)?; . } else { 7,184 ( 0.00%) span.ctxt.encode(s)?; . } . 7,184 ( 0.00%) if self.is_dummy() { . return TAG_PARTIAL_SPAN.encode(s); . } . . // The Span infrastructure should make sure that this invariant holds: . debug_assert!(span.lo <= span.hi); . 35,789 ( 0.02%) if !s.source_file_cache.0.contains(span.lo) { 14 ( 0.00%) let source_map = s.tcx.sess.source_map(); 28 ( 0.00%) let source_file_index = source_map.lookup_source_file_idx(span.lo); 14 ( 0.00%) s.source_file_cache = 28 ( 0.00%) (source_map.files()[source_file_index].clone(), source_file_index); . } . 21,505 ( 0.01%) if !s.source_file_cache.0.contains(span.hi) { . // Unfortunately, macro expansion still sometimes generates Spans . // that malformed in this way. . return TAG_PARTIAL_SPAN.encode(s); . } . . let source_files = s.required_source_files.as_mut().expect("Already encoded SourceMap!"); . // Record the fact that we need to encode the data for this `SourceFile` 7,159 ( 0.00%) source_files.insert(s.source_file_cache.1); . . // There are two possible cases here: . // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the . // crate we are writing metadata for. When the metadata for *this* crate gets . // deserialized, the deserializer will need to know which crate it originally came . // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should . // be deserialized after the rest of the span data, which tells the deserializer . // which crate contains the source map information. -- line 272 ---------------------------------------- -- line 274 ---------------------------------------- . // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use . // our own source map information. . // . // If we're a proc-macro crate, we always treat this as a local `Span`. . // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata . // if we're a proc-macro crate. . // This allows us to avoid loading the dependencies of proc-macro crates: all of . // the information we need to decode `Span`s is stored in the proc-macro crate. 42,954 ( 0.02%) let (tag, lo, hi) = if s.source_file_cache.0.is_imported() && !s.is_proc_macro { . // To simplify deserialization, we 'rebase' this span onto the crate it originally came from . // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values . // are relative to the source map information for the 'foreign' crate whose CrateNum . // we write into the metadata. This allows `imported_source_files` to binary . // search through the 'foreign' crate's source map information, using the . // deserialized 'lo' and 'hi' values directly. . // . // All of this logic ensures that the final result of deserialization is a 'normal' -- line 290 ---------------------------------------- -- line 296 ---------------------------------------- . src => panic!("Unexpected external source {:?}", src), . } . }; . let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos; . let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos; . . (TAG_VALID_SPAN_FOREIGN, lo, hi) . } else { 21,477 ( 0.01%) (TAG_VALID_SPAN_LOCAL, span.lo, span.hi) . }; . . tag.encode(s)?; . lo.encode(s)?; . . // Encode length which is usually less than span.hi and profits more . // from the variable-length integer encoding that we use. . let len = hi - lo; . len.encode(s)?; . 14,318 ( 0.01%) if tag == TAG_VALID_SPAN_FOREIGN { . // This needs to be two lines to avoid holding the `s.source_file_cache` . // while calling `cnum.encode(s)` . let cnum = s.source_file_cache.0.cnum; . cnum.encode(s)?; . } . . Ok(()) 57,472 ( 0.03%) } . } . . impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> { . const CLEAR_CROSS_CRATE: bool = true; . . fn position(&self) -> usize { . self.opaque.position() . } -- line 331 ---------------------------------------- -- line 361 ---------------------------------------- . } . . /// Helper trait to allow overloading `EncodeContext::lazy` for iterators. . trait EncodeContentsForLazy<'a, 'tcx, T: ?Sized + LazyMeta> { . fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> T::Meta; . } . . impl<'a, 'tcx, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, T> for &T { 273 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { 225 ( 0.00%) self.encode(ecx).unwrap() 6 ( 0.00%) } . } . . impl<'a, 'tcx, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, T> for T { 804 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { 407 ( 0.00%) self.encode(ecx).unwrap() 495 ( 0.00%) } . } . . impl<'a, 'tcx, I, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, [T]> for I . where . I: IntoIterator, . I::Item: EncodeContentsForLazy<'a, 'tcx, T>, . { 35 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize { 356 ( 0.00%) self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count() 45 ( 0.00%) } . } . . // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would . // normally need extra variables to avoid errors about multiple mutable borrows. . macro_rules! record { . ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{ . { . let value = $value; . let lazy = $self.lazy(value); . $self.$tables.$table.set($def_id.index, lazy); . } . }}; . } . . impl<'a, 'tcx> EncodeContext<'a, 'tcx> { 350 ( 0.00%) fn emit_lazy_distance( . &mut self, . lazy: Lazy, . ) -> Result<(), ::Error> { . let pos = lazy.position.get(); 290 ( 0.00%) let distance = match self.lazy_state { . LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"), 30 ( 0.00%) LazyState::NodeStart(start) => { . let start = start.get(); 60 ( 0.00%) assert!(pos <= start); . start - pos . } 40 ( 0.00%) LazyState::Previous(last_pos) => { 40 ( 0.00%) assert!( . last_pos <= lazy.position, . "make sure that the calls to `lazy*` \ . are in the same order as the metadata fields", . ); 120 ( 0.00%) lazy.position.get() - last_pos.get() . } . }; 140 ( 0.00%) self.lazy_state = LazyState::Previous(NonZeroUsize::new(pos).unwrap()); . self.emit_usize(distance) 350 ( 0.00%) } . 405 ( 0.00%) fn lazy( . &mut self, . value: impl EncodeContentsForLazy<'a, 'tcx, T>, . ) -> Lazy { . let pos = NonZeroUsize::new(self.position()).unwrap(); . 510 ( 0.00%) assert_eq!(self.lazy_state, LazyState::NoNode); 1,529 ( 0.00%) self.lazy_state = LazyState::NodeStart(pos); 902 ( 0.00%) let meta = value.encode_contents_for_lazy(self); 635 ( 0.00%) self.lazy_state = LazyState::NoNode; . 1,101 ( 0.00%) assert!(pos.get() <= self.position()); . . Lazy::from_position_and_meta(pos, meta) 597 ( 0.00%) } . . fn encode_info_for_items(&mut self) { 9 ( 0.00%) self.encode_info_for_mod(CRATE_DEF_ID, self.tcx.hir().root_module()); . . // Proc-macro crates only export proc-macro items, which are looked . // up using `proc_macro_data` 2 ( 0.00%) if self.is_proc_macro { . return; . } . 6 ( 0.00%) self.tcx.hir().visit_all_item_likes(&mut self.as_deep_visitor()); . } . . fn encode_def_path_table(&mut self) { 4 ( 0.00%) let table = self.tcx.resolutions(()).definitions.def_path_table(); 2 ( 0.00%) if self.is_proc_macro { . for def_index in std::iter::once(CRATE_DEF_INDEX) . .chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index)) . { . let def_key = self.lazy(table.def_key(def_index)); . let def_path_hash = self.lazy(table.def_path_hash(def_index)); . self.tables.def_keys.set(def_index, def_key); . self.tables.def_path_hashes.set(def_index, def_path_hash); . } . } else { 5 ( 0.00%) for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() { . let def_key = self.lazy(def_key); . let def_path_hash = self.lazy(def_path_hash); 252 ( 0.00%) self.tables.def_keys.set(def_index, def_key); 252 ( 0.00%) self.tables.def_path_hashes.set(def_index, def_path_hash); . } . } . } . . fn encode_def_path_hash_map(&mut self) -> Lazy> { . self.lazy(DefPathHashMapRef::BorrowedFromTcx( 2 ( 0.00%) self.tcx.resolutions(()).definitions.def_path_hash_to_def_index_map(), . )) . } . . fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> { 2 ( 0.00%) let source_map = self.tcx.sess.source_map(); 3 ( 0.00%) let all_source_files = source_map.files(); . . // By replacing the `Option` with `None`, we ensure that we can't . // accidentally serialize any more `Span`s after the source map encoding . // is done. . let required_source_files = self.required_source_files.take().unwrap(); . . let adapted = all_source_files . .iter() . .enumerate() . .filter(|(idx, source_file)| { . // Only serialize `SourceFile`s that were used . // during the encoding of a `Span` 629 ( 0.00%) required_source_files.contains(*idx) && . // Don't serialize imported `SourceFile`s, unless . // we're in a proc-macro crate. 9 ( 0.00%) (!source_file.is_imported() || self.is_proc_macro) . }) . .map(|(_, source_file)| { 6 ( 0.00%) let mut adapted = match source_file.name { . FileName::Real(ref realname) => { 4 ( 0.00%) let mut adapted = (**source_file).clone(); 32 ( 0.00%) adapted.name = FileName::Real(match realname { . RealFileName::LocalPath(path_to_file) => { . // Prepend path of working directory onto potentially . // relative paths, because they could become relative . // to a wrong directory. . // We include `working_dir` as part of the crate hash, . // so it's okay for us to use it as part of the encoded . // metadata. 4 ( 0.00%) let working_dir = &self.tcx.sess.opts.working_dir; 4 ( 0.00%) match working_dir { . RealFileName::LocalPath(absolute) => { . // Although neither working_dir or the file name were subject . // to path remapping, the concatenation between the two may . // be. Hence we need to do a remapping here. . let joined = Path::new(absolute).join(path_to_file); 14 ( 0.00%) let (joined, remapped) = 22 ( 0.00%) source_map.path_mapping().map_prefix(joined); 4 ( 0.00%) if remapped { . RealFileName::Remapped { . local_path: None, . virtual_name: joined, . } . } else { . RealFileName::LocalPath(joined) . } . } -- line 532 ---------------------------------------- -- line 544 ---------------------------------------- . RealFileName::Remapped { local_path: _, virtual_name } => { . RealFileName::Remapped { . // We do not want any local path to be exported into metadata . local_path: None, . virtual_name: virtual_name.clone(), . } . } . }); 4 ( 0.00%) adapted.name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 2 ( 0.00%) adapted.name.hash(&mut hasher); . hasher.finish::() . }; 2 ( 0.00%) Lrc::new(adapted) . } . . // expanded code, not from a file . _ => source_file.clone(), . }; . . // We're serializing this `SourceFile` into our crate metadata, . // so mark it as coming from this crate. . // This also ensures that we don't try to deserialize the . // `CrateNum` for a proc-macro dependency - since proc macro . // dependencies aren't loaded when we deserialize a proc-macro, . // trying to remap the `CrateNum` would fail. 4 ( 0.00%) if self.is_proc_macro { . Lrc::make_mut(&mut adapted).cnum = LOCAL_CRATE; . } . adapted . }) . .collect::>(); . . self.lazy(adapted.iter().map(|rc| &**rc)) . } . 8 ( 0.00%) fn encode_crate_root(&mut self) -> Lazy> { . let mut i = self.position(); . . // Encode the crate deps . let crate_deps = self.encode_crate_deps(); . let dylib_dependency_formats = self.encode_dylib_dependency_formats(); 5 ( 0.00%) let dep_bytes = self.position() - i; . . // Encode the lib features. . i = self.position(); . let lib_features = self.encode_lib_features(); 7 ( 0.00%) let lib_feature_bytes = self.position() - i; . . // Encode the language items. . i = self.position(); . let lang_items = self.encode_lang_items(); . let lang_items_missing = self.encode_lang_items_missing(); 5 ( 0.00%) let lang_item_bytes = self.position() - i; . . // Encode the diagnostic items. . i = self.position(); . let diagnostic_items = self.encode_diagnostic_items(); 5 ( 0.00%) let diagnostic_item_bytes = self.position() - i; . . // Encode the native libraries used . i = self.position(); . let native_libraries = self.encode_native_libraries(); 4 ( 0.00%) let native_lib_bytes = self.position() - i; . . let foreign_modules = self.encode_foreign_modules(); . . // Encode DefPathTable . i = self.position(); . self.encode_def_path_table(); 5 ( 0.00%) let def_path_table_bytes = self.position() - i; . . // Encode the def IDs of traits, for rustdoc and diagnostics. . i = self.position(); . let traits = self.encode_traits(); 5 ( 0.00%) let traits_bytes = self.position() - i; . . // Encode the def IDs of impls, for coherence checking. . i = self.position(); . let impls = self.encode_impls(); 5 ( 0.00%) let impls_bytes = self.position() - i; . 3 ( 0.00%) let tcx = self.tcx; . . // Encode MIR. . i = self.position(); . self.encode_mir(); 5 ( 0.00%) let mir_bytes = self.position() - i; . . // Encode the items. . i = self.position(); . self.encode_def_ids(); . self.encode_info_for_items(); 4 ( 0.00%) let item_bytes = self.position() - i; . . // Encode the allocation index . let interpret_alloc_index = { . let mut interpret_alloc_index = Vec::new(); . let mut n = 0; . trace!("beginning to encode alloc ids"); . loop { . let new_n = self.interpret_allocs.len(); . // if we have found new ids, serialize those, too 2 ( 0.00%) if n == new_n { . // otherwise, abort . break; . } . trace!("encoding {} further alloc ids", new_n - n); . for idx in n..new_n { . let id = self.interpret_allocs[idx]; . let pos = self.position() as u32; . interpret_alloc_index.push(pos); . interpret::specialized_encode_alloc_id(self, tcx, id).unwrap(); . } . n = new_n; . } 6 ( 0.00%) self.lazy(interpret_alloc_index) . }; . . // Encode the proc macro data. This affects 'tables', . // so we need to do this before we encode the tables . i = self.position(); . let proc_macro_data = self.encode_proc_macros(); 4 ( 0.00%) let proc_macro_data_bytes = self.position() - i; . . i = self.position(); 4 ( 0.00%) let tables = self.tables.encode(&mut self.opaque); 4 ( 0.00%) let tables_bytes = self.position() - i; . . // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode . // this as late as possible to give the prefetching as much time as possible to complete. . i = self.position(); . let exported_symbols = tcx.exported_symbols(LOCAL_CRATE); . let exported_symbols = self.encode_exported_symbols(&exported_symbols); 4 ( 0.00%) let exported_symbols_bytes = self.position() - i; . . // Encode the hygiene data, . // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process . // of encoding other items (e.g. `optimized_mir`) may cause us to load . // data from the incremental cache. If this causes us to deserialize a `Span`, . // then we may load additional `SyntaxContext`s into the global `HygieneData`. . // Therefore, we need to encode the hygiene data last to ensure that we encode . // any `SyntaxContext`s that might be used. . i = self.position(); . let (syntax_contexts, expn_data, expn_hashes) = self.encode_hygiene(); 5 ( 0.00%) let hygiene_bytes = self.position() - i; . . i = self.position(); . let def_path_hash_map = self.encode_def_path_hash_map(); 1 ( 0.00%) let def_path_hash_map_bytes = self.position() - i; . . // Encode source_map. This needs to be done last, . // since encoding `Span`s tells us which `SourceFiles` we actually . // need to encode. . i = self.position(); . let source_map = self.encode_source_map(); 4 ( 0.00%) let source_map_bytes = self.position() - i; . 3 ( 0.00%) let attrs = tcx.hir().krate_attrs(); 7 ( 0.00%) let has_default_lib_allocator = tcx.sess.contains_name(&attrs, sym::default_lib_allocator); . 118 ( 0.00%) let root = self.lazy(CrateRoot { . name: tcx.crate_name(LOCAL_CRATE), 3 ( 0.00%) extra_filename: tcx.sess.opts.cg.extra_filename.clone(), 1 ( 0.00%) triple: tcx.sess.opts.target_triple.clone(), . hash: tcx.crate_hash(LOCAL_CRATE), . stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(), 3 ( 0.00%) panic_strategy: tcx.sess.panic_strategy(), 3 ( 0.00%) panic_in_drop_strategy: tcx.sess.opts.debugging_opts.panic_in_drop, 2 ( 0.00%) edition: tcx.sess.edition(), . has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE), . has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE), . has_default_lib_allocator, . proc_macro_data, 6 ( 0.00%) compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins), 6 ( 0.00%) needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator), 6 ( 0.00%) needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime), 6 ( 0.00%) no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins), 5 ( 0.00%) panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime), 5 ( 0.00%) profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime), 2 ( 0.00%) symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(), . . crate_deps, . dylib_dependency_formats, . lib_features, . lang_items, . diagnostic_items, . lang_items_missing, . native_libraries, . foreign_modules, . source_map, . traits, . impls, . exported_symbols, . interpret_alloc_index, 2 ( 0.00%) tables, . syntax_contexts, . expn_data, . expn_hashes, . def_path_hash_map, . }); . 1 ( 0.00%) let total_bytes = self.position(); . 4 ( 0.00%) if tcx.sess.meta_stats() { . let mut zero_bytes = 0; . for e in self.opaque.data.iter() { . if *e == 0 { . zero_bytes += 1; . } . } . . eprintln!("metadata stats:"); -- line 756 ---------------------------------------- -- line 770 ---------------------------------------- . eprintln!(" item bytes: {}", item_bytes); . eprintln!(" table bytes: {}", tables_bytes); . eprintln!(" hygiene bytes: {}", hygiene_bytes); . eprintln!(" zero bytes: {}", zero_bytes); . eprintln!(" total bytes: {}", total_bytes); . } . . root 9 ( 0.00%) } . } . . fn should_encode_visibility(def_kind: DefKind) -> bool { . match def_kind { . DefKind::Mod . | DefKind::Struct . | DefKind::Union . | DefKind::Enum -- line 786 ---------------------------------------- -- line 853 ---------------------------------------- . /// Whether we should encode MIR. . /// . /// Computing, optimizing and encoding the MIR is a relatively expensive operation. . /// We want to avoid this work when not required. Therefore: . /// - we only compute `mir_for_ctfe` on items with const-eval semantics; . /// - we skip `optimized_mir` for check runs. . /// . /// Return a pair, resp. for CTFE and for LLVM. 99 ( 0.00%) fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) { 55 ( 0.00%) match tcx.def_kind(def_id) { . // Constructors . DefKind::Ctor(_, _) => { . let mir_opt_base = tcx.sess.opts.output_types.should_codegen() . || tcx.sess.opts.debugging_opts.always_encode_mir; . (true, mir_opt_base) . } . // Constants . DefKind::AnonConst . | DefKind::InlineConst . | DefKind::AssocConst . | DefKind::Static . | DefKind::Const => (true, false), . // Full-fledged functions . DefKind::AssocFn | DefKind::Fn => { . let generics = tcx.generics_of(def_id); 36 ( 0.00%) let needs_inline = (generics.requires_monomorphization(tcx) 12 ( 0.00%) || tcx.codegen_fn_attrs(def_id).requests_inline()) 18 ( 0.00%) && tcx.sess.opts.output_types.should_codegen(); . // The function has a `const` modifier or is annotated with `default_method_body_is_const`. 6 ( 0.00%) let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id()) 30 ( 0.00%) || tcx.has_attr(def_id.to_def_id(), sym::default_method_body_is_const); . let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir; 12 ( 0.00%) (is_const_fn, needs_inline || always_encode_mir) . } . // Closures can't be const fn. . DefKind::Closure => { . let generics = tcx.generics_of(def_id); 12 ( 0.00%) let needs_inline = (generics.requires_monomorphization(tcx) . || tcx.codegen_fn_attrs(def_id).requests_inline()) 6 ( 0.00%) && tcx.sess.opts.output_types.should_codegen(); . let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir; 6 ( 0.00%) (false, needs_inline || always_encode_mir) . } . // Generators require optimized MIR to compute layout. . DefKind::Generator => (false, true), . // The others don't have MIR. . _ => (false, false), . } 99 ( 0.00%) } . . fn should_encode_variances(def_kind: DefKind) -> bool { . match def_kind { . DefKind::Struct . | DefKind::Union . | DefKind::Enum . | DefKind::Variant . | DefKind::Fn -- line 909 ---------------------------------------- -- line 969 ---------------------------------------- . | DefKind::LifetimeParam . | DefKind::GlobalAsm . | DefKind::ExternCrate => false, . } . } . . impl<'a, 'tcx> EncodeContext<'a, 'tcx> { . fn encode_def_ids(&mut self) { 2 ( 0.00%) if self.is_proc_macro { . return; . } 1 ( 0.00%) let tcx = self.tcx; 3 ( 0.00%) let hir = tcx.hir(); 45 ( 0.00%) for local_id in hir.iter_local_def_id() { . let def_id = local_id.to_def_id(); . let def_kind = tcx.opt_def_kind(local_id); 378 ( 0.00%) let def_kind = if let Some(def_kind) = def_kind { def_kind } else { continue }; 768 ( 0.00%) record!(self.tables.def_kind[def_id] <- match def_kind { . // Replace Ctor by the enclosing object to avoid leaking details in children crates. . DefKind::Ctor(CtorOf::Struct, _) => DefKind::Struct, . DefKind::Ctor(CtorOf::Variant, _) => DefKind::Variant, . def_kind => def_kind, . }); 144 ( 0.00%) record!(self.tables.span[def_id] <- tcx.def_span(def_id)); 576 ( 0.00%) record!(self.tables.attributes[def_id] <- tcx.get_attrs(def_id)); 384 ( 0.00%) record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id)); . if should_encode_visibility(def_kind) { 246 ( 0.00%) record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id)); . } . if should_encode_stability(def_kind) { . self.encode_stability(def_id); . self.encode_const_stability(def_id); 114 ( 0.00%) self.encode_deprecation(def_id); . } . if should_encode_variances(def_kind) { 20 ( 0.00%) let v = self.tcx.variances_of(def_id); 70 ( 0.00%) record!(self.tables.variances[def_id] <- v); . } . if should_encode_generics(def_kind) { . let g = tcx.generics_of(def_id); 76 ( 0.00%) record!(self.tables.generics[def_id] <- g); 228 ( 0.00%) record!(self.tables.explicit_predicates[def_id] <- self.tcx.explicit_predicates_of(def_id)); 19 ( 0.00%) let inferred_outlives = self.tcx.inferred_outlives_of(def_id); 19 ( 0.00%) if !inferred_outlives.is_empty() { . record!(self.tables.inferred_outlives[def_id] <- inferred_outlives); . } . } 336 ( 0.00%) if let DefKind::Trait | DefKind::TraitAlias = def_kind { 28 ( 0.00%) record!(self.tables.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id)); . } . } . let inherent_impls = tcx.crate_inherent_impls(()); . for (def_id, implementations) in inherent_impls.inherent_impls.iter() { . if implementations.is_empty() { . continue; . } . record!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| { . assert!(def_id.is_local()); . def_id.index . })); . } . } . 119 ( 0.00%) fn encode_item_type(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_item_type({:?})", def_id); 102 ( 0.00%) record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id)); 136 ( 0.00%) } . . fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) { . let tcx = self.tcx; . let variant = &def.variants[index]; . let def_id = variant.def_id; . debug!("EncodeContext::encode_enum_variant_info({:?})", def_id); . . let data = VariantData { -- line 1043 ---------------------------------------- -- line 1078 ---------------------------------------- . . record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data))); . self.encode_item_type(def_id); . if variant.ctor_kind == CtorKind::Fn { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . 30 ( 0.00%) fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) { 6 ( 0.00%) let tcx = self.tcx; . let def_id = local_def_id.to_def_id(); . debug!("EncodeContext::encode_info_for_mod({:?})", def_id); . . // If we are encoding a proc-macro crates, `encode_info_for_mod` will . // only ever get called for the crate root. We still want to encode . // the crate root for consistency with other crates (some of the resolver . // code uses it). However, we skip encoding anything relating to child . // items - we encode information about proc-macros later on. 9 ( 0.00%) let reexports = if !self.is_proc_macro { 6 ( 0.00%) match tcx.module_reexports(local_def_id) { . Some(exports) => self.lazy(exports), . _ => Lazy::empty(), . } . } else { . Lazy::empty() . }; . 12 ( 0.00%) record!(self.tables.kind[def_id] <- EntryKind::Mod(reexports)); 6 ( 0.00%) if self.is_proc_macro { . // Encode this here because we don't do it in encode_def_ids. . record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id)); . } else { . let direct_children = md.item_ids.iter().map(|item_id| item_id.def_id.local_def_index); . // Foreign items are planted into their parent modules from name resolution point of view. 6 ( 0.00%) let tcx = self.tcx; . let foreign_item_children = md . .item_ids . .iter() 135 ( 0.00%) .filter_map(|item_id| match tcx.hir().item(*item_id).kind { . hir::ItemKind::ForeignMod { items, .. } => { . Some(items.iter().map(|fi_ref| fi_ref.id.def_id.local_def_index)) . } . _ => None, . }) . .flatten(); . 21 ( 0.00%) record!(self.tables.children[def_id] <- direct_children.chain(foreign_item_children)); . } 24 ( 0.00%) } . . fn encode_field( . &mut self, . adt_def: &ty::AdtDef, . variant_index: VariantIdx, . field_index: usize, . ) { . let variant = &adt_def.variants[variant_index]; -- line 1134 ---------------------------------------- -- line 1166 ---------------------------------------- . let bounds = self.tcx.explicit_item_bounds(def_id); . if !bounds.is_empty() { . record!(self.tables.explicit_item_bounds[def_id] <- bounds); . } . } . . fn encode_info_for_trait_item(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id); 4 ( 0.00%) let tcx = self.tcx; . 28 ( 0.00%) let ast_item = tcx.hir().expect_trait_item(def_id.expect_local()); . let trait_item = tcx.associated_item(def_id); . 20 ( 0.00%) let container = match trait_item.defaultness { . hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault, . hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired, . hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"), . }; . 24 ( 0.00%) match trait_item.kind { . ty::AssocKind::Const => { . let rendered = rustc_hir_pretty::to_string( . &(&self.tcx.hir() as &dyn intravisit::Map<'_>), . |s| s.print_trait_item(ast_item), . ); . let rendered_const = self.lazy(RenderedConst(rendered)); . . record!(self.tables.kind[def_id] <- EntryKind::AssocConst( . container, . Default::default(), . rendered_const, . )); . } . ty::AssocKind::Fn => { 8 ( 0.00%) let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind { 8 ( 0.00%) let param_names = match *m { . hir::TraitFn::Required(ref names) => self.encode_fn_param_names(names), . hir::TraitFn::Provided(body) => self.encode_fn_param_names_for_body(body), . }; . FnData { . asyncness: m_sig.header.asyncness, . constness: hir::Constness::NotConst, . param_names, . } -- line 1209 ---------------------------------------- -- line 1217 ---------------------------------------- . }))); . } . ty::AssocKind::Type => { . self.encode_explicit_item_bounds(def_id); . record!(self.tables.kind[def_id] <- EntryKind::AssocType(container)); . } . } . self.encode_ident_span(def_id, ast_item.ident); 12 ( 0.00%) match trait_item.kind { . ty::AssocKind::Const | ty::AssocKind::Fn => { . self.encode_item_type(def_id); . } . ty::AssocKind::Type => { . if trait_item.defaultness.has_value() { . self.encode_item_type(def_id); . } . } . } 4 ( 0.00%) if trait_item.kind == ty::AssocKind::Fn { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . . fn encode_info_for_impl_item(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id); 8 ( 0.00%) let tcx = self.tcx; . 24 ( 0.00%) let ast_item = self.tcx.hir().expect_impl_item(def_id.expect_local()); 4 ( 0.00%) let impl_item = self.tcx.associated_item(def_id); . 16 ( 0.00%) let container = match impl_item.defaultness { . hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault, . hir::Defaultness::Final => AssocContainer::ImplFinal, . hir::Defaultness::Default { has_value: false } => { . span_bug!(ast_item.span, "impl items always have values (currently)") . } . }; . 24 ( 0.00%) match impl_item.kind { . ty::AssocKind::Const => { . if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind { . let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id); . . record!(self.tables.kind[def_id] <- EntryKind::AssocConst( . container, . qualifs, . self.encode_rendered_const_for_body(body_id)) . ); . } else { . bug!() . } . } . ty::AssocKind::Fn => { 8 ( 0.00%) let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind { . FnData { . asyncness: sig.header.asyncness, . // Can be inside `impl const Trait`, so using sig.header.constness is not reliable 4 ( 0.00%) constness: if self.tcx.is_const_fn_raw(def_id) { . hir::Constness::Const . } else { . hir::Constness::NotConst . }, . param_names: self.encode_fn_param_names_for_body(body), . } . } else { . bug!() -- line 1282 ---------------------------------------- -- line 1286 ---------------------------------------- . container, . has_self: impl_item.fn_has_self_parameter, . }))); . } . ty::AssocKind::Type => { . record!(self.tables.kind[def_id] <- EntryKind::AssocType(container)); . } . } 12 ( 0.00%) self.encode_ident_span(def_id, impl_item.ident(self.tcx)); 20 ( 0.00%) self.encode_item_type(def_id); 16 ( 0.00%) if let Some(trait_item_def_id) = impl_item.trait_item_def_id { . record!(self.tables.trait_item_def_id[def_id] <- trait_item_def_id); . } 4 ( 0.00%) if impl_item.kind == ty::AssocKind::Fn { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . 16 ( 0.00%) fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> { 38 ( 0.00%) self.lazy(self.tcx.hir().body_param_names(body_id)) 16 ( 0.00%) } . . fn encode_fn_param_names(&mut self, param_names: &[Ident]) -> Lazy<[Ident]> { . self.lazy(param_names.iter()) . } . . fn encode_mir(&mut self) { 3 ( 0.00%) if self.is_proc_macro { . return; . } . . let keys_and_jobs = self . .tcx . .mir_keys(()) . .iter() . .filter_map(|&def_id| { 55 ( 0.00%) let (encode_const, encode_opt) = should_encode_mir(self.tcx, def_id); 66 ( 0.00%) if encode_const || encode_opt { 22 ( 0.00%) Some((def_id, encode_const, encode_opt)) . } else { . None . } 22 ( 0.00%) }) . .collect::>(); 60 ( 0.00%) for (def_id, encode_const, encode_opt) in keys_and_jobs.into_iter() { . debug_assert!(encode_const || encode_opt); . . debug!("EntryBuilder::encode_mir({:?})", def_id); 11 ( 0.00%) if encode_opt { 36 ( 0.00%) record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id)); . } 11 ( 0.00%) if encode_const { 8 ( 0.00%) record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- self.tcx.mir_for_ctfe(def_id)); . . // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir` 2 ( 0.00%) let abstract_const = self.tcx.thir_abstract_const(def_id); 8 ( 0.00%) if let Ok(Some(abstract_const)) = abstract_const { . record!(self.tables.thir_abstract_consts[def_id.to_def_id()] <- abstract_const); . } . } 44 ( 0.00%) record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id)); . . let instance = . ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id())); 11 ( 0.00%) let unused = self.tcx.unused_generic_params(instance); 11 ( 0.00%) if !unused.is_empty() { . record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused); . } . } . } . . fn encode_stability(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_stability({:?})", def_id); . . // The query lookup can take a measurable amount of time in crates with many items. Check if . // the stability attributes are even enabled before using their queries. 152 ( 0.00%) if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked { . if let Some(stab) = self.tcx.lookup_stability(def_id) { . record!(self.tables.stability[def_id] <- stab) . } . } . } . . fn encode_const_stability(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_const_stability({:?})", def_id); . . // The query lookup can take a measurable amount of time in crates with many items. Check if . // the stability attributes are even enabled before using their queries. 133 ( 0.00%) if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked { . if let Some(stab) = self.tcx.lookup_const_stability(def_id) { . record!(self.tables.const_stability[def_id] <- stab) . } . } . } . 114 ( 0.00%) fn encode_deprecation(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_deprecation({:?})", def_id); 95 ( 0.00%) if let Some(depr) = self.tcx.lookup_deprecation(def_id) { . record!(self.tables.deprecation[def_id] <- depr); . } 95 ( 0.00%) } . 12 ( 0.00%) fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy { 6 ( 0.00%) let hir = self.tcx.hir(); 4 ( 0.00%) let body = hir.body(body_id); 16 ( 0.00%) let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| { 6 ( 0.00%) s.print_expr(&body.value) . }); 4 ( 0.00%) let rendered_const = &RenderedConst(rendered); . self.lazy(rendered_const) 14 ( 0.00%) } . 90 ( 0.00%) fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) { . let tcx = self.tcx; . . debug!("EncodeContext::encode_info_for_item({:?})", def_id); . . self.encode_ident_span(def_id, item.ident); . 60 ( 0.00%) let entry_kind = match item.kind { . hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic, . hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic, 6 ( 0.00%) hir::ItemKind::Const(_, body_id) => { 6 ( 0.00%) let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id); 14 ( 0.00%) EntryKind::Const(qualifs, self.encode_rendered_const_for_body(body_id)) . } 4 ( 0.00%) hir::ItemKind::Fn(ref sig, .., body) => { . let data = FnData { 2 ( 0.00%) asyncness: sig.header.asyncness, 2 ( 0.00%) constness: sig.header.constness, 4 ( 0.00%) param_names: self.encode_fn_param_names_for_body(body), . }; . . EntryKind::Fn(self.lazy(data)) . } . hir::ItemKind::Macro(ref macro_def) => { . EntryKind::MacroDef(self.lazy(macro_def.clone())) . } . hir::ItemKind::Mod(ref m) => { 24 ( 0.00%) return self.encode_info_for_mod(item.def_id, m); . } . hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod, . hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm, . hir::ItemKind::TyAlias(..) => EntryKind::Type, . hir::ItemKind::OpaqueTy(..) => { . self.encode_explicit_item_bounds(def_id); . EntryKind::OpaqueTy . } -- line 1433 ---------------------------------------- -- line 1462 ---------------------------------------- . ctor_kind: variant.ctor_kind, . discr: variant.discr, . ctor: None, . is_non_exhaustive: variant.is_field_list_non_exhaustive(), . }), . adt_def.repr, . ) . } 8 ( 0.00%) hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => { 8 ( 0.00%) let trait_ref = self.tcx.impl_trait_ref(def_id); 4 ( 0.00%) let polarity = self.tcx.impl_polarity(def_id); 4 ( 0.00%) let parent = if let Some(trait_ref) = trait_ref { 2 ( 0.00%) let trait_def = self.tcx.trait_def(trait_ref.def_id); 12 ( 0.00%) trait_def.ancestors(self.tcx, def_id).ok().and_then(|mut an| { 12 ( 0.00%) an.nth(1).and_then(|node| match node { . specialization_graph::Node::Impl(parent) => Some(parent), . _ => None, . }) . }) . } else { . None . }; . . // if this is an impl of `CoerceUnsized`, create its . // "unsized info", else just store None . let coerce_unsized_info = trait_ref.and_then(|t| { 12 ( 0.00%) if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() { . Some(self.tcx.at(item.span).coerce_unsized_info(def_id)) . } else { . None . } . }); . . let data = ImplData { . polarity, -- line 1496 ---------------------------------------- -- line 1498 ---------------------------------------- . constness, . parent_impl: parent, . coerce_unsized_info, . }; . . EntryKind::Impl(self.lazy(data)) . } . hir::ItemKind::Trait(..) => { 4 ( 0.00%) let trait_def = self.tcx.trait_def(def_id); . let data = TraitData { 2 ( 0.00%) unsafety: trait_def.unsafety, 4 ( 0.00%) paren_sugar: trait_def.paren_sugar, 10 ( 0.00%) has_auto_impl: self.tcx.trait_is_auto(def_id), 2 ( 0.00%) is_marker: trait_def.is_marker, 2 ( 0.00%) skip_array_during_method_dispatch: trait_def.skip_array_during_method_dispatch, 2 ( 0.00%) specialization_kind: trait_def.specialization_kind, . must_implement_one_of: trait_def.must_implement_one_of.clone(), . }; . . EntryKind::Trait(self.lazy(data)) . } . hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias, . hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => { . bug!("cannot encode info for item {:?}", item) . } . }; . record!(self.tables.kind[def_id] <- entry_kind); . // FIXME(eddyb) there should be a nicer way to do this. 40 ( 0.00%) match item.kind { . hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <- . self.tcx.adt_def(def_id).variants.iter().map(|v| { . assert!(v.def_id.is_local()); . v.def_id.index . }) . ), . hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => { . record!(self.tables.children[def_id] <- . self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| { . assert!(f.did.is_local()); . f.did.index . }) . ) . } . hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => { 8 ( 0.00%) let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id); . record!(self.tables.children[def_id] <- . associated_item_def_ids.iter().map(|&def_id| { 8 ( 0.00%) assert!(def_id.is_local()); . def_id.index . }) . ); . } . _ => {} . } 20 ( 0.00%) match item.kind { . hir::ItemKind::Static(..) . | hir::ItemKind::Const(..) . | hir::ItemKind::Fn(..) . | hir::ItemKind::TyAlias(..) . | hir::ItemKind::OpaqueTy(..) . | hir::ItemKind::Enum(..) . | hir::ItemKind::Struct(..) . | hir::ItemKind::Union(..) 24 ( 0.00%) | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id), . _ => {} . } 22 ( 0.00%) if let hir::ItemKind::Fn(..) = item.kind { 8 ( 0.00%) record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } 18 ( 0.00%) if let hir::ItemKind::Impl { .. } = item.kind { 10 ( 0.00%) if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) { 10 ( 0.00%) record!(self.tables.impl_trait_ref[def_id] <- trait_ref); . } . } 64 ( 0.00%) } . . fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) { . record!(self.tables.kind[def_id] <- kind); . if encode_type { . self.encode_item_type(def_id); . } . } . . fn encode_info_for_closure(&mut self, hir_id: hir::HirId) { 18 ( 0.00%) let def_id = self.tcx.hir().local_def_id(hir_id); . debug!("EncodeContext::encode_info_for_closure({:?})", def_id); . . // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic, . // including on the signature, which is inferred in `typeck. 9 ( 0.00%) let ty = self.tcx.typeck(def_id).node_type(hir_id); . 9 ( 0.00%) match ty.kind() { . ty::Generator(..) => { . let data = self.tcx.generator_kind(def_id).unwrap(); . record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Generator(data)); . } . . ty::Closure(..) => { . record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Closure); . } . . _ => bug!("closure that is neither generator nor closure"), . } 12 ( 0.00%) self.encode_item_type(def_id.to_def_id()); 12 ( 0.00%) if let ty::Closure(def_id, substs) = *ty.kind() { 27 ( 0.00%) record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig()); . } . } . . fn encode_info_for_anon_const(&mut self, id: hir::HirId) { . let def_id = self.tcx.hir().local_def_id(id); . debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id); . let body_id = self.tcx.hir().body_owned_by(id); . let const_data = self.encode_rendered_const_for_body(body_id); . let qualifs = self.tcx.mir_const_qualif(def_id); . . record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst(qualifs, const_data)); . self.encode_item_type(def_id.to_def_id()); . } . . fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> { 2 ( 0.00%) empty_proc_macro!(self); 2 ( 0.00%) let used_libraries = self.tcx.native_libraries(LOCAL_CRATE); . self.lazy(used_libraries.iter()) . } . . fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> { 5 ( 0.00%) empty_proc_macro!(self); 2 ( 0.00%) let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE); . self.lazy(foreign_modules.iter().map(|(_, m)| m).cloned()) . } . . fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) { . let mut syntax_contexts: TableBuilder<_, _> = Default::default(); . let mut expn_data_table: TableBuilder<_, _> = Default::default(); . let mut expn_hash_table: TableBuilder<_, _> = Default::default(); . 2 ( 0.00%) let _: Result<(), !> = self.hygiene_ctxt.encode( 8 ( 0.00%) &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table), . |(this, syntax_contexts, _, _), index, ctxt_data| { . syntax_contexts.set(index, this.lazy(ctxt_data)); . Ok(()) . }, . |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| { . if let Some(index) = index.as_local() { 10 ( 0.00%) expn_data_table.set(index.as_raw(), this.lazy(expn_data)); 10 ( 0.00%) expn_hash_table.set(index.as_raw(), this.lazy(hash)); . } . Ok(()) . }, . ); . . ( . syntax_contexts.encode(&mut self.opaque), . expn_data_table.encode(&mut self.opaque), . expn_hash_table.encode(&mut self.opaque), . ) . } . . fn encode_proc_macros(&mut self) -> Option { 6 ( 0.00%) let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro); . if is_proc_macro { . let tcx = self.tcx; . let hir = tcx.hir(); . . let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index; . let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied(); . let macros = . self.lazy(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index)); -- line 1666 ---------------------------------------- -- line 1725 ---------------------------------------- . . Some(ProcMacroData { proc_macro_decls_static, stability, macros }) . } else { . None . } . } . . fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> { 7 ( 0.00%) empty_proc_macro!(self); . 1 ( 0.00%) let deps = self . .tcx . .crates(()) . .iter() . .map(|&cnum| { . let dep = CrateDep { 3 ( 0.00%) name: self.tcx.crate_name(cnum), 3 ( 0.00%) hash: self.tcx.crate_hash(cnum), 3 ( 0.00%) host_hash: self.tcx.crate_host_hash(cnum), 3 ( 0.00%) kind: self.tcx.dep_kind(cnum), 3 ( 0.00%) extra_filename: self.tcx.extra_filename(cnum), . }; 15 ( 0.00%) (cnum, dep) . }) . .collect::>(); . . { . // Sanity-check the crate numbers . let mut expected_cnum = 1; 6 ( 0.00%) for &(n, _) in &deps { 8 ( 0.00%) assert_eq!(n, CrateNum::new(expected_cnum)); . expected_cnum += 1; . } . } . . // We're just going to write a list of crate 'name-hash-version's, with . // the assumption that they are numbered 1 to n. . // FIXME (#2166): This is not nearly enough to support correct versioning . // but is enough to get transitive crate dependencies working. . self.lazy(deps.iter().map(|&(_, ref dep)| dep)) . } . . fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option)]> { 2 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) let tcx = self.tcx; . let lib_features = tcx.lib_features(()); 2 ( 0.00%) self.lazy(lib_features.to_vec()) . } . . fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> { 3 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) let tcx = self.tcx; . let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id; . self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index))) . } . . fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> { 4 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) let tcx = self.tcx; 1 ( 0.00%) let lang_items = tcx.lang_items(); 2 ( 0.00%) let lang_items = lang_items.items().iter(); . self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| { 568 ( 0.00%) if let Some(def_id) = opt_def_id { . if def_id.is_local() { . return Some((def_id.index, i)); . } . } . None . })) . } . . fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> { 2 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) let tcx = self.tcx; 1 ( 0.00%) self.lazy(&tcx.lang_items().missing) . } . . fn encode_traits(&mut self) -> Lazy<[DefIndex]> { 3 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) self.lazy(self.tcx.traits_in_crate(LOCAL_CRATE).iter().map(|def_id| def_id.index)) . } . . /// Encodes an index, mapping each trait to its (local) implementations. . fn encode_impls(&mut self) -> Lazy<[TraitImpls]> { . debug!("EncodeContext::encode_traits_and_impls()"); 2 ( 0.00%) empty_proc_macro!(self); 2 ( 0.00%) let tcx = self.tcx; 5 ( 0.00%) let mut visitor = ImplsVisitor { tcx, impls: FxHashMap::default() }; 4 ( 0.00%) tcx.hir().visit_all_item_likes(&mut visitor); . . let mut all_impls: Vec<_> = visitor.impls.into_iter().collect(); . . // Bring everything into deterministic order for hashing 2 ( 0.00%) all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id)); . . let all_impls: Vec<_> = all_impls . .into_iter() 30 ( 0.00%) .map(|(trait_def_id, mut impls)| { . // Bring everything into deterministic order for hashing . impls.sort_by_cached_key(|&(index, _)| { . tcx.hir().def_path_hash(LocalDefId { local_def_index: index }) . }); . 8 ( 0.00%) TraitImpls { . trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index), 6 ( 0.00%) impls: self.lazy(&impls), . } 16 ( 0.00%) }) . .collect(); . . self.lazy(&all_impls) . } . . // Encodes all symbols exported from this crate into the metadata. . // . // This pass is seeded off the reachability list calculated in the . // middle::reachable module but filters out items that either don't have a . // symbol associated with them (they weren't translated) or if they're an FFI . // definition (as that's not defined in this crate). . fn encode_exported_symbols( . &mut self, . exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)], . ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> { 2 ( 0.00%) empty_proc_macro!(self); . // The metadata symbol name is special. It should not show up in . // downstream crates. 9 ( 0.00%) let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx)); . . self.lazy( . exported_symbols . .iter() . .filter(|&&(ref exported_symbol, _)| match *exported_symbol { . ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name, . _ => true, . }) . .cloned(), . ) . } . . fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option]> { 2 ( 0.00%) empty_proc_macro!(self); 2 ( 0.00%) let formats = self.tcx.dependency_formats(()); 4 ( 0.00%) for (ty, arr) in formats.iter() { 2 ( 0.00%) if *ty != CrateType::Dylib { . continue; . } . return self.lazy(arr.iter().map(|slot| match *slot { . Linkage::NotLinked | Linkage::IncludedFromDylib => None, . . Linkage::Dynamic => Some(LinkagePreference::RequireDynamic), . Linkage::Static => Some(LinkagePreference::RequireStatic), . })); -- line 1876 ---------------------------------------- -- line 1914 ---------------------------------------- . } . } . . // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR. . impl<'a, 'tcx> Visitor<'tcx> for EncodeContext<'a, 'tcx> { . type NestedFilter = nested_filter::OnlyBodies; . . fn nested_visit_map(&mut self) -> Self::Map { 11 ( 0.00%) self.tcx.hir() . } 30,078 ( 0.02%) fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) { 3,342 ( 0.00%) intravisit::walk_expr(self, ex); . self.encode_info_for_expr(ex); 26,736 ( 0.01%) } . fn visit_anon_const(&mut self, c: &'tcx AnonConst) { . intravisit::walk_anon_const(self, c); . self.encode_info_for_anon_const(c.hir_id); . } . fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { 102 ( 0.00%) intravisit::walk_item(self, item); 68 ( 0.00%) match item.kind { . hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these 40 ( 0.00%) _ => self.encode_info_for_item(item.def_id.to_def_id(), item), . } 136 ( 0.00%) self.encode_addl_info_for_item(item); . } . fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) { . intravisit::walk_foreign_item(self, ni); . self.encode_info_for_foreign_item(ni.def_id.to_def_id(), ni); . } 126 ( 0.00%) fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) { . intravisit::walk_generics(self, generics); . self.encode_info_for_generics(generics); 112 ( 0.00%) } . } . . impl<'a, 'tcx> EncodeContext<'a, 'tcx> { . fn encode_fields(&mut self, adt_def: &ty::AdtDef) { . for (variant_index, variant) in adt_def.variants.iter_enumerated() { . for (field_index, _field) in variant.fields.iter().enumerate() { . self.encode_field(adt_def, variant_index, field_index); . } . } . } . . fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) { . for param in generics.params { 12 ( 0.00%) let def_id = self.tcx.hir().local_def_id(param.hir_id); 14 ( 0.00%) match param.kind { . GenericParamKind::Lifetime { .. } => continue, . GenericParamKind::Type { default, .. } => { . self.encode_info_for_generic_param( . def_id.to_def_id(), . EntryKind::TypeParam, . default.is_some(), . ); . } -- line 1970 ---------------------------------------- -- line 1975 ---------------------------------------- . record!(self.tables.const_defaults[def_id] <- self.tcx.const_param_default(def_id)) . } . } . } . } . } . . fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) { 6,684 ( 0.00%) if let hir::ExprKind::Closure(..) = expr.kind { . self.encode_info_for_closure(expr.hir_id); . } . } . . fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) { . record!(self.tables.ident_span[def_id] <- ident.span); . } . . /// In some cases, along with the item itself, we also . /// encode some sub-items. Usually we want some info from the item . /// so it's easier to do that here then to wait until we would encounter . /// normally in the visitor walk. 306 ( 0.00%) fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) { 170 ( 0.00%) match item.kind { . hir::ItemKind::Static(..) . | hir::ItemKind::Const(..) . | hir::ItemKind::Fn(..) . | hir::ItemKind::Macro(..) . | hir::ItemKind::Mod(..) . | hir::ItemKind::ForeignMod { .. } . | hir::ItemKind::GlobalAsm(..) . | hir::ItemKind::ExternCrate(..) -- line 2005 ---------------------------------------- -- line 2031 ---------------------------------------- . self.encode_struct_ctor(def, ctor_def_id.to_def_id()); . } . } . hir::ItemKind::Union(..) => { . let def = self.tcx.adt_def(item.def_id.to_def_id()); . self.encode_fields(def); . } . hir::ItemKind::Impl { .. } => { 16 ( 0.00%) for &trait_item_def_id in 2 ( 0.00%) self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter() . { . self.encode_info_for_impl_item(trait_item_def_id); . } . } . hir::ItemKind::Trait(..) => { 14 ( 0.00%) for &item_def_id in self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter() . { . self.encode_info_for_trait_item(item_def_id); . } . } . } 272 ( 0.00%) } . } . . struct ImplsVisitor<'tcx> { . tcx: TyCtxt<'tcx>, . impls: FxHashMap)>>, . } . . impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplsVisitor<'tcx> { 238 ( 0.00%) fn visit_item(&mut self, item: &hir::Item<'_>) { 68 ( 0.00%) match item.kind { . hir::ItemKind::Impl(..) => { 8 ( 0.00%) if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id.to_def_id()) { 12 ( 0.00%) let simplified_self_ty = fast_reject::simplify_type( . self.tcx, . trait_ref.self_ty(), . SimplifyParams::No, . StripReferences::No, . ); . . self.impls . .entry(trait_ref.def_id) . .or_default() . .push((item.def_id.local_def_index, simplified_self_ty)); . } . } . _ => {} . } 272 ( 0.00%) } . . fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {} . . fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) { . // handled in `visit_item` above . } . . fn visit_foreign_item(&mut self, _foreign_item: &'v hir::ForeignItem<'v>) {} -- line 2088 ---------------------------------------- -- line 2146 ---------------------------------------- . } . . #[inline] . pub fn raw_data(&self) -> &[u8] { . &self.raw_data . } . } . 10 ( 0.00%) pub fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata { 5 ( 0.00%) let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata"); . . // Since encoding metadata is not in a query, and nothing is cached, . // there's no need to do dep-graph tracking for any of it. . tcx.dep_graph.assert_ignored(); . 7 ( 0.00%) join( 3 ( 0.00%) || encode_metadata_impl(tcx), . || { 5 ( 0.00%) if tcx.sess.threads() == 1 { . return; . } . // Prefetch some queries used by metadata encoding. . // This is not necessary for correctness, but is only done for performance reasons. . // It can be removed if it turns out to cause trouble or be detrimental to performance. . join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE)); . }, . ) . .0 9 ( 0.00%) } . 9 ( 0.00%) fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata { 1 ( 0.00%) let mut encoder = opaque::Encoder::new(vec![]); . encoder.emit_raw_bytes(METADATA_HEADER).unwrap(); . . // Will be filled with the root position after encoding everything. . encoder.emit_raw_bytes(&[0, 0, 0, 0]).unwrap(); . 2 ( 0.00%) let source_map_files = tcx.sess.source_map().files(); 3 ( 0.00%) let source_file_cache = (source_map_files[0].clone(), 0); 2 ( 0.00%) let required_source_files = Some(GrowableBitSet::with_capacity(source_map_files.len())); . drop(source_map_files); . . let hygiene_ctxt = HygieneEncodeContext::default(); . 35 ( 0.00%) let mut ecx = EncodeContext { 4 ( 0.00%) opaque: encoder, . tcx, 2 ( 0.00%) feat: tcx.features(), . tables: Default::default(), . lazy_state: LazyState::NoNode, . type_shorthands: Default::default(), . predicate_shorthands: Default::default(), 4 ( 0.00%) source_file_cache, . interpret_allocs: Default::default(), 4 ( 0.00%) required_source_files, 2 ( 0.00%) is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro), . hygiene_ctxt: &hygiene_ctxt, . }; . . // Encode the rustc version string in a predictable location. . rustc_version().encode(&mut ecx).unwrap(); . . // Encode all the entries and extra information in the crate, . // culminating in the `CrateRoot` which points to all of it. 1 ( 0.00%) let root = ecx.encode_crate_root(); . 7 ( 0.00%) let mut result = ecx.opaque.into_inner(); . . // Encode the root position. . let header = METADATA_HEADER.len(); . let pos = root.position.get(); 3 ( 0.00%) result[header + 0] = (pos >> 24) as u8; 3 ( 0.00%) result[header + 1] = (pos >> 16) as u8; 1 ( 0.00%) result[header + 2] = (pos >> 8) as u8; 5 ( 0.00%) result[header + 3] = (pos >> 0) as u8; . . // Record metadata size for self-profiling . tcx.prof.artifact_size("crate_metadata", "crate_metadata", result.len() as u64); . 5 ( 0.00%) EncodedMetadata { raw_data: result } 12 ( 0.00%) } . . pub fn provide(providers: &mut Providers) { 2 ( 0.00%) *providers = Providers { . traits_in_crate: |tcx, cnum| { 1 ( 0.00%) assert_eq!(cnum, LOCAL_CRATE); . 1 ( 0.00%) #[derive(Default)] . struct TraitsVisitor { . traits: Vec, . } . impl ItemLikeVisitor<'_> for TraitsVisitor { . fn visit_item(&mut self, item: &hir::Item<'_>) { 136 ( 0.00%) if let hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) = item.kind { 2 ( 0.00%) self.traits.push(item.def_id.to_def_id()); . } . } . fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {} . fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {} . fn visit_foreign_item(&mut self, _foreign_item: &hir::ForeignItem<'_>) {} . } . . let mut visitor = TraitsVisitor::default(); 4 ( 0.00%) tcx.hir().visit_all_item_likes(&mut visitor); . // Bring everything into deterministic order. 2 ( 0.00%) visitor.traits.sort_by_cached_key(|&def_id| tcx.def_path_hash(def_id)); . tcx.arena.alloc_slice(&visitor.traits) . }, . . ..*providers . }; . } 16,582 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs -------------------------------------------------------------------------------- Ir -- line 36 ---------------------------------------- . use rustc_session::parse::ParseSess; . use rustc_span::source_map::{MultiSpan, Span, DUMMY_SP}; . use rustc_span::symbol::{kw, sym, Ident, Symbol}; . use tracing::debug; . . use std::ops::Range; . use std::{cmp, mem, slice}; . 9,900 ( 0.01%) bitflags::bitflags! { . struct Restrictions: u8 { . const STMT_EXPR = 1 << 0; . const NO_STRUCT_LITERAL = 1 << 1; . const CONST_EXPR = 1 << 2; . } . } . . #[derive(Clone, Copy, PartialEq, Debug)] -- line 52 ---------------------------------------- -- line 104 ---------------------------------------- . $self.bump(); . return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty); . } . } . } . }; . } . 202 ( 0.00%) #[derive(Clone)] . pub struct Parser<'a> { 4 ( 0.00%) pub sess: &'a ParseSess, . /// The current token. 2 ( 0.00%) pub token: Token, . /// The spacing for the current token 3 ( 0.00%) pub token_spacing: Spacing, . /// The previous token. 3 ( 0.00%) pub prev_token: Token, 5 ( 0.00%) pub capture_cfg: bool, 12 ( 0.00%) restrictions: Restrictions, 6 ( 0.00%) expected_tokens: Vec, . // Important: This must only be advanced from `next_tok` . // to ensure that `token_cursor.num_next_calls` is updated properly . token_cursor: TokenCursor, 6 ( 0.00%) desugar_doc_comments: bool, . /// This field is used to keep track of how many left angle brackets we have seen. This is . /// required in order to detect extra leading left angle brackets (`<` characters) and error . /// appropriately. . /// . /// See the comments in the `parse_path_segment` function for more details. 6 ( 0.00%) unmatched_angle_bracket_count: u32, 9 ( 0.00%) max_angle_bracket_count: u32, . /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery . /// it gets removed from here. Every entry left at the end gets emitted as an independent . /// error. 3 ( 0.00%) pub(super) unclosed_delims: Vec, . last_unexpected_token_span: Option, . /// Span pointing at the `:` for the last type ascription the parser has seen, and whether it . /// looked like it could have been a mistyped path or literal `Option:Some(42)`). . pub last_type_ascription: Option<(Span, bool /* likely path typo */)>, . /// If present, this `Parser` is not parsing Rust code but rather a macro call. . subparser_name: Option<&'static str>, . capture_state: CaptureState, . /// This allows us to recover when the user forget to add braces around -- line 146 ---------------------------------------- -- line 173 ---------------------------------------- . /// the first macro inner attribute to invoke a proc-macro). . /// When create a `TokenStream`, the inner attributes get inserted . /// into the proper place in the token stream. . pub type ReplaceRange = (Range, Vec<(FlatToken, Spacing)>); . . /// Controls how we capture tokens. Capturing can be expensive, . /// so we try to avoid performing capturing in cases where . /// we will never need an `AttrAnnotatedTokenStream` 3 ( 0.00%) #[derive(Copy, Clone)] . pub enum Capturing { . /// We aren't performing any capturing - this is the default mode. . No, . /// We are capturing tokens . Yes, . } . 12 ( 0.00%) #[derive(Clone)] . struct CaptureState { 12 ( 0.00%) capturing: Capturing, 3 ( 0.00%) replace_ranges: Vec, . inner_attr_ranges: FxHashMap, . } . . impl<'a> Drop for Parser<'a> { . fn drop(&mut self) { 56 ( 0.00%) emit_unclosed_delims(&mut self.unclosed_delims, &self.sess); . } . } . 1,302 ( 0.00%) #[derive(Clone)] . struct TokenCursor { . frame: TokenCursorFrame, 295 ( 0.00%) stack: Vec, . desugar_doc_comments: bool, . // Counts the number of calls to `next` or `next_desugared`, . // depending on whether `desugar_doc_comments` is set. 95 ( 0.00%) num_next_calls: usize, . // During parsing, we may sometimes need to 'unglue' a . // glued token into two component tokens . // (e.g. '>>' into '>' and '>), so that the parser . // can consume them one at a time. This process . // bypasses the normal capturing mechanism . // (e.g. `num_next_calls` will not be incremented), . // since the 'unglued' tokens due not exist in . // the original `TokenStream`. -- line 217 ---------------------------------------- -- line 226 ---------------------------------------- . // in `Option>` requires us to unglue . // the trailing `>>` token. The `break_last_token` . // field is used to track this token - it gets . // appended to the captured stream when . // we evaluate a `LazyTokenStream` . break_last_token: bool, . } . 610 ( 0.00%) #[derive(Clone)] . struct TokenCursorFrame { 173 ( 0.00%) delim: token::DelimToken, . span: DelimSpan, . open_delim: bool, 346 ( 0.00%) tree_cursor: tokenstream::Cursor, . close_delim: bool, . } . . impl TokenCursorFrame { . fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self { 60 ( 0.00%) TokenCursorFrame { . delim, . span, . open_delim: false, 763 ( 0.00%) tree_cursor: tts.into_trees(), . close_delim: false, . } . } . } . . impl TokenCursor { 86,904 ( 0.04%) fn next(&mut self) -> (Token, Spacing) { . loop { 41,377 ( 0.02%) let (tree, spacing) = if !self.frame.open_delim { 739 ( 0.00%) self.frame.open_delim = true; 3,695 ( 0.00%) TokenTree::open_tt(self.frame.span, self.frame.delim).into() 85,320 ( 0.04%) } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() { . tree 2,976 ( 0.00%) } else if !self.frame.close_delim { 736 ( 0.00%) self.frame.close_delim = true; 3,680 ( 0.00%) TokenTree::close_tt(self.frame.span, self.frame.delim).into() 1,472 ( 0.00%) } else if let Some(frame) = self.stack.pop() { 9,568 ( 0.00%) self.frame = frame; . continue; . } else { 288 ( 0.00%) (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone) . }; . 15,962 ( 0.01%) match tree { . TokenTree::Token(token) => { 57,936 ( 0.03%) return (token, spacing); . } . TokenTree::Delimited(sp, delim, tts) => { . let frame = TokenCursorFrame::new(sp, delim, tts); . self.stack.push(mem::replace(&mut self.frame, frame)); . } . } . } 57,936 ( 0.03%) } . 150 ( 0.00%) fn next_desugared(&mut self) -> (Token, Spacing) { 45 ( 0.00%) let (data, attr_style, sp) = match self.next() { . (Token { kind: token::DocComment(_, attr_style, data), span }, _) => { . (data, attr_style, span) . } 75 ( 0.00%) tok => return tok, . }; . . // Searches for the occurrences of `"#*` and returns the minimum number of `#`s . // required to wrap the text. . let mut num_of_hashes = 0; . let mut count = 0; . for ch in data.as_str().chars() { . count = match ch { -- line 298 ---------------------------------------- -- line 332 ---------------------------------------- . .iter() . .cloned() . .collect::() . }, . ), . )); . . self.next() 135 ( 0.00%) } . } . 360 ( 0.00%) #[derive(Debug, Clone, PartialEq)] . enum TokenType { 288 ( 0.00%) Token(TokenKind), . Keyword(Symbol), . Operator, . Lifetime, . Ident, . Path, . Type, . Const, . } -- line 353 ---------------------------------------- -- line 378 ---------------------------------------- . /// The separator token. . sep: Option, . /// `true` if a trailing separator is allowed. . trailing_sep_allowed: bool, . } . . impl SeqSep { . fn trailing_allowed(t: TokenKind) -> SeqSep { 9 ( 0.00%) SeqSep { sep: Some(t), trailing_sep_allowed: true } . } . . fn none() -> SeqSep { . SeqSep { sep: None, trailing_sep_allowed: false } . } . } . . pub enum FollowedByType { . Yes, . No, . } . . fn token_descr_opt(token: &Token) -> Option<&'static str> { 20 ( 0.00%) Some(match token.kind { 40 ( 0.00%) _ if token.is_special_ident() => "reserved identifier", 40 ( 0.00%) _ if token.is_used_keyword() => "keyword", 40 ( 0.00%) _ if token.is_unused_keyword() => "reserved keyword", . token::DocComment(..) => "doc comment", . _ => return None, . }) . } . 70 ( 0.00%) pub(super) fn token_descr(token: &Token) -> String { 20 ( 0.00%) let token_str = pprust::token_to_string(token); . match token_descr_opt(token) { . Some(prefix) => format!("{} `{}`", prefix, token_str), 70 ( 0.00%) _ => format!("`{}`", token_str), . } 50 ( 0.00%) } . . impl<'a> Parser<'a> { 168 ( 0.00%) pub fn new( . sess: &'a ParseSess, . tokens: TokenStream, . desugar_doc_comments: bool, . subparser_name: Option<&'static str>, . ) -> Self { 12 ( 0.00%) let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens); 24 ( 0.00%) start_frame.open_delim = true; . start_frame.close_delim = true; . 372 ( 0.00%) let mut parser = Parser { . sess, 12 ( 0.00%) token: Token::dummy(), . token_spacing: Spacing::Alone, 12 ( 0.00%) prev_token: Token::dummy(), . capture_cfg: false, . restrictions: Restrictions::empty(), . expected_tokens: Vec::new(), . token_cursor: TokenCursor { 72 ( 0.00%) frame: start_frame, . stack: Vec::new(), . num_next_calls: 0, . desugar_doc_comments, . break_last_token: false, . }, . desugar_doc_comments, . unmatched_angle_bracket_count: 0, . max_angle_bracket_count: 0, -- line 445 ---------------------------------------- -- line 451 ---------------------------------------- . capturing: Capturing::No, . replace_ranges: Vec::new(), . inner_attr_ranges: Default::default(), . }, . current_closure: None, . }; . . // Make parser point to the first token. 24 ( 0.00%) parser.bump(); . . parser 108 ( 0.00%) } . . fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) { . loop { 43,266 ( 0.02%) let (mut next, spacing) = if self.desugar_doc_comments { 60 ( 0.00%) self.token_cursor.next_desugared() . } else { 21,588 ( 0.01%) self.token_cursor.next() . }; 28,844 ( 0.01%) self.token_cursor.num_next_calls += 1; . // We've retrieved an token from the underlying . // cursor, so we no longer need to worry about . // an unglued token. See `break_and_eat` for more details 7,211 ( 0.00%) self.token_cursor.break_last_token = false; 28,844 ( 0.01%) if next.span.is_dummy() { . // Tweak the location for better diagnostics, but keep syntactic context intact. 56 ( 0.00%) next.span = fallback_span.with_ctxt(next.span.ctxt()); . } 23,841 ( 0.01%) if matches!( 14,422 ( 0.01%) next.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 28,844 ( 0.01%) return (next, spacing); . } . } . . pub fn unexpected(&mut self) -> PResult<'a, T> { . match self.expect_one_of(&[], &[]) { . Err(e) => Err(e), . // We can get `Ok(true)` from `recover_closing_delimiter` . // which is called in `expected_one_of_not_found`. . Ok(_) => FatalError.raise(), . } . } . . /// Expects and consumes the token `t`. Signals an error if the next token is not `t`. 30,150 ( 0.02%) pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { 3,350 ( 0.00%) if self.expected_tokens.is_empty() { 114 ( 0.00%) if self.token == *t { 95 ( 0.00%) self.bump(); . Ok(false) . } else { . self.unexpected_try_recover(t) . } . } else { 39,972 ( 0.02%) self.expect_one_of(slice::from_ref(t), &[]) . } 50,250 ( 0.03%) } . . /// Expect next token to be edible or inedible token. If edible, . /// then consume it; if inedible, then return without consuming . /// anything. Signal a fatal error if next token is unexpected. 40,128 ( 0.02%) pub fn expect_one_of( . &mut self, . edible: &[TokenKind], . inedible: &[TokenKind], . ) -> PResult<'a, bool /* recovered */> { 6,688 ( 0.00%) if edible.contains(&self.token.kind) { 10,005 ( 0.01%) self.bump(); . Ok(false) . } else if inedible.contains(&self.token.kind) { . // leave it in the input . Ok(false) . } else if self.last_unexpected_token_span == Some(self.token.span) { . FatalError.raise(); . } else { . self.expected_one_of_not_found(edible, inedible) . } 50,160 ( 0.03%) } . . // Public for rustfmt usage. . pub fn parse_ident(&mut self) -> PResult<'a, Ident> { 712 ( 0.00%) self.parse_ident_common(true) . } . . fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> { 534 ( 0.00%) self.token.ident().ok_or_else(|| match self.prev_token.kind { . TokenKind::DocComment(..) => { . self.span_err(self.prev_token.span, Error::UselessDocComment) . } . _ => self.expected_ident_found(), . }) . } . 1,246 ( 0.00%) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { 178 ( 0.00%) let (ident, is_raw) = self.ident_or_err()?; 1,068 ( 0.00%) if !is_raw && ident.is_reserved() { . let mut err = self.expected_ident_found(); . if recover { . err.emit(); . } else { . return Err(err); . } . } 712 ( 0.00%) self.bump(); . Ok(ident) 1,780 ( 0.00%) } . . /// Checks if the next token is `tok`, and returns `true` if so. . /// . /// This method will automatically add `tok` to `expected_tokens` if `tok` is not . /// encountered. 142,345 ( 0.07%) fn check(&mut self, tok: &TokenKind) -> bool { 61,097 ( 0.03%) let is_present = self.token == *tok; 40,788 ( 0.02%) if !is_present { 90,732 ( 0.05%) self.expected_tokens.push(TokenType::Token(tok.clone())); . } . is_present 142,345 ( 0.07%) } . . /// Consumes a token 'tok' if it exists. Returns whether the given token was present. . pub fn eat(&mut self, tok: &TokenKind) -> bool { 24,508 ( 0.01%) let is_present = self.check(tok); 16,276 ( 0.01%) if is_present { 1,680 ( 0.00%) self.bump() . } . is_present . } . . /// If the next token is the given keyword, returns `true` without eating it. . /// An expectation is also added for diagnostics purposes. 555 ( 0.00%) fn check_keyword(&mut self, kw: Symbol) -> bool { 153 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw)); 4,204 ( 0.00%) self.token.is_keyword(kw) . } . . /// If the next token is the given keyword, eats it and returns `true`. . /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes. . // Public for rustfmt usage. 1,190 ( 0.00%) pub fn eat_keyword(&mut self, kw: Symbol) -> bool { 932 ( 0.00%) if self.check_keyword(kw) { 119 ( 0.00%) self.bump(); . true . } else { . false . } 1,190 ( 0.00%) } . . fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { 156 ( 0.00%) if self.token.is_keyword(kw) { 36 ( 0.00%) self.bump(); . true . } else { . false . } . } . . /// If the given word is not a keyword, signals an error. . /// If the next token is not the given word, signals an error. . /// Otherwise, eats it. 35 ( 0.00%) fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { . if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } 28 ( 0.00%) } . . /// Is the given keyword `kw` followed by a non-reserved identifier? 464 ( 0.00%) fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { 232 ( 0.00%) self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) 522 ( 0.00%) } . 864 ( 0.00%) fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { 316 ( 0.00%) if ok { . true . } else { 208 ( 0.00%) self.expected_tokens.push(typ); . false . } 864 ( 0.00%) } . . fn check_ident(&mut self) -> bool { 171 ( 0.00%) self.check_or_expected(self.token.is_ident(), TokenType::Ident) . } . 312 ( 0.00%) fn check_path(&mut self) -> bool { 668 ( 0.00%) self.check_or_expected(self.token.is_path_start(), TokenType::Path) 390 ( 0.00%) } . . fn check_type(&mut self) -> bool { 40 ( 0.00%) self.check_or_expected(self.token.can_begin_type(), TokenType::Type) . } . . fn check_const_arg(&mut self) -> bool { 40 ( 0.00%) self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) . } . 207 ( 0.00%) fn check_inline_const(&self, dist: usize) -> bool { 115 ( 0.00%) self.is_keyword_ahead(dist, &[kw::Const]) . && self.look_ahead(dist + 1, |t| match t.kind { . token::Interpolated(ref nt) => matches!(**nt, token::NtBlock(..)), . token::OpenDelim(DelimToken::Brace) => true, . _ => false, . }) 207 ( 0.00%) } . . /// Checks to see if the next token is either `+` or `+=`. . /// Otherwise returns `false`. . fn check_plus(&mut self) -> bool { 136 ( 0.00%) self.check_or_expected( 68 ( 0.00%) self.token.is_like_plus(), 68 ( 0.00%) TokenType::Token(token::BinOp(token::Plus)), . ) . } . . /// Eats the expected token if it's present possibly breaking . /// compound tokens like multi-character operators in process. . /// Returns `true` if the token was eaten. 1,200 ( 0.00%) fn break_and_eat(&mut self, expected: TokenKind) -> bool { 700 ( 0.00%) if self.token.kind == expected { 42 ( 0.00%) self.bump(); . return true; . } 395 ( 0.00%) match self.token.kind.break_two_token_op() { . Some((first, second)) if first == expected => { . let first_span = self.sess.source_map().start_point(self.token.span); . let second_span = self.token.span.with_lo(first_span.hi()); . self.token = Token::new(first, first_span); . // Keep track of this token - if we end token capturing now, . // we'll want to append this token to the captured stream. . // . // If we consume any additional tokens, then this token -- line 682 ---------------------------------------- -- line 684 ---------------------------------------- . // and `next_tok` will set this field to `None` . self.token_cursor.break_last_token = true; . // Use the spacing of the glued token as the spacing . // of the unglued second token. . self.bump_with((Token::new(second, second_span), self.token_spacing)); . true . } . _ => { 237 ( 0.00%) self.expected_tokens.push(TokenType::Token(expected)); . false . } . } 1,216 ( 0.00%) } . . /// Eats `+` possibly breaking tokens like `+=` in process. . fn eat_plus(&mut self) -> bool { . self.break_and_eat(token::BinOp(token::Plus)) . } . . /// Eats `&` possibly breaking tokens like `&&` in process. . /// Signals an error if `&` is not eaten. . fn expect_and(&mut self) -> PResult<'a, ()> { 24 ( 0.00%) if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `|` possibly breaking tokens like `||` in process. . /// Signals an error if `|` was not eaten. . fn expect_or(&mut self) -> PResult<'a, ()> { 18 ( 0.00%) if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `<` possibly breaking tokens like `<<` in process. 76 ( 0.00%) fn eat_lt(&mut self) -> bool { 275 ( 0.00%) let ate = self.break_and_eat(token::Lt); 177 ( 0.00%) if ate { . // See doc comment for `unmatched_angle_bracket_count`. 28 ( 0.00%) self.unmatched_angle_bracket_count += 1; 30 ( 0.00%) self.max_angle_bracket_count += 1; . debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); . } . ate 76 ( 0.00%) } . . /// Eats `<` possibly breaking tokens like `<<` in process. . /// Signals an error if `<` was not eaten. . fn expect_lt(&mut self) -> PResult<'a, ()> { . if self.eat_lt() { Ok(()) } else { self.unexpected() } . } . . /// Eats `>` possibly breaking tokens like `>>` in process. . /// Signals an error if `>` was not eaten. . fn expect_gt(&mut self) -> PResult<'a, ()> { 42 ( 0.00%) if self.break_and_eat(token::Gt) { . // See doc comment for `unmatched_angle_bracket_count`. 21 ( 0.00%) if self.unmatched_angle_bracket_count > 0 { 14 ( 0.00%) self.unmatched_angle_bracket_count -= 1; . debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count); . } . Ok(()) . } else { . self.unexpected() . } . } . . fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool { . kets.iter().any(|k| match expect { 21,717 ( 0.01%) TokenExpectType::Expect => self.check(k), 45 ( 0.00%) TokenExpectType::NoExpect => self.token == **k, . }) . } . . fn parse_seq_to_before_tokens( . &mut self, . kets: &[&TokenKind], . sep: SeqSep, . expect: TokenExpectType, -- line 759 ---------------------------------------- -- line 761 ---------------------------------------- . ) -> PResult<'a, (Vec, bool /* trailing */, bool /* recovered */)> { . let mut first = true; . let mut recovered = false; . let mut trailing = false; . let mut v = vec![]; . let unclosed_delims = !self.unclosed_delims.is_empty(); . . while !self.expect_any_with_type(kets, expect) { 17,197 ( 0.01%) if let token::CloseDelim(..) | token::Eof = self.token.kind { . break; . } 9,296 ( 0.00%) if let Some(ref t) = sep.sep { 8,699 ( 0.00%) if first { . first = false; . } else { 18,942 ( 0.01%) match self.expect(t) { . Ok(false) => { . self.current_closure.take(); . } . Ok(true) => { . self.current_closure.take(); . recovered = true; . break; . } -- line 784 ---------------------------------------- -- line 857 ---------------------------------------- . e.cancel(); . break; . } . } . } . } . } . } 6,600 ( 0.00%) if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) { . trailing = true; . break; . } . 3,327 ( 0.00%) let t = f(self)?; 104 ( 0.00%) v.push(t); . } . 2,752 ( 0.00%) Ok((v, trailing, recovered)) . } . . fn recover_missing_braces_around_closure_body( . &mut self, . closure_spans: ClosureSpans, . mut expect_err: DiagnosticBuilder<'_>, . ) -> PResult<'a, ()> { . let initial_semicolon = self.token.span; -- line 882 ---------------------------------------- -- line 937 ---------------------------------------- . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. . fn parse_seq_to_before_end( . &mut self, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool, bool)> { 2,112 ( 0.00%) self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f) . } . . /// Parses a sequence, including the closing delimiter. The function . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. 170 ( 0.00%) fn parse_seq_to_end( . &mut self, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool /* trailing */)> { 1,390 ( 0.00%) let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; 1,350 ( 0.00%) if !recovered { . self.eat(ket); . } 1,522 ( 0.00%) Ok((val, trailing)) 136 ( 0.00%) } . . /// Parses a sequence, including the closing delimiter. The function . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. . fn parse_unspanned_seq( . &mut self, . bra: &TokenKind, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { 81 ( 0.00%) self.expect(bra)?; 136 ( 0.00%) self.parse_seq_to_end(ket, sep, f) . } . . fn parse_delim_comma_seq( . &mut self, . delim: DelimToken, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { . self.parse_unspanned_seq( 37 ( 0.00%) &token::OpenDelim(delim), 57 ( 0.00%) &token::CloseDelim(delim), . SeqSep::trailing_allowed(token::Comma), . f, . ) . } . . fn parse_paren_comma_seq( . &mut self, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { . self.parse_delim_comma_seq(token::Paren, f) . } . . /// Advance the parser by one token using provided token as the next one. 93,743 ( 0.05%) fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) { . // Bumping after EOF is a bad sign, usually an infinite loop. 43,266 ( 0.02%) if self.prev_token.kind == TokenKind::Eof { . let msg = "attempted to bump the parser past EOF (may be stuck in a loop)"; . self.span_bug(self.token.span, msg); . } . . // Update the current and previous tokens. 28,844 ( 0.01%) self.prev_token = mem::replace(&mut self.token, next_token); 7,211 ( 0.00%) self.token_spacing = next_spacing; . . // Diagnostics. 7,211 ( 0.00%) self.expected_tokens.clear(); . } . . /// Advance the parser by one token. 57,688 ( 0.03%) pub fn bump(&mut self) { 28,844 ( 0.01%) let next_token = self.next_tok(self.token.span); 43,266 ( 0.02%) self.bump_with(next_token); 57,688 ( 0.03%) } . . /// Look-ahead `dist` tokens of `self.token` and get access to that token there. . /// When `dist == 0` then the current token is looked at. . pub fn look_ahead(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R { 84 ( 0.00%) if dist == 0 { 34 ( 0.00%) return looker(&self.token); . } . 3,505 ( 0.00%) let frame = &self.token_cursor.frame; 3,530 ( 0.00%) if frame.delim != DelimToken::NoDelim { . let all_normal = (0..dist).all(|i| { 10,536 ( 0.01%) let token = frame.tree_cursor.look_ahead(i); 12,728 ( 0.01%) !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _))) . }); . if all_normal { 17,512 ( 0.01%) return match frame.tree_cursor.look_ahead(dist - 1) { 5,613 ( 0.00%) Some(tree) => match tree { 2,779 ( 0.00%) TokenTree::Token(token) => looker(token), . TokenTree::Delimited(dspan, delim, _) => { 227 ( 0.00%) looker(&Token::new(token::OpenDelim(*delim), dspan.open)) . } . }, 4,882 ( 0.00%) None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)), . }; . } . } . . let mut cursor = self.token_cursor.clone(); . let mut i = 0; 49 ( 0.00%) let mut token = Token::dummy(); . while i < dist { 217 ( 0.00%) token = cursor.next().0; 99 ( 0.00%) if matches!( 62 ( 0.00%) token.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } . i += 1; . } . return looker(&token); . } . . /// Returns whether any of the given keywords are `dist` tokens ahead of the current one. 360 ( 0.00%) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool { 95 ( 0.00%) self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw))) 360 ( 0.00%) } . . /// Parses asyncness: `async` or nothing. . fn parse_asyncness(&mut self) -> Async { . if self.eat_keyword(kw::Async) { . let span = self.prev_token.uninterpolated_span(); . Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID } . } else { . Async::No . } . } . . /// Parses unsafety: `unsafe` or nothing. 34 ( 0.00%) fn parse_unsafety(&mut self) -> Unsafe { . if self.eat_keyword(kw::Unsafe) { . Unsafe::Yes(self.prev_token.uninterpolated_span()) . } else { . Unsafe::No . } 136 ( 0.00%) } . . /// Parses constness: `const` or nothing. 224 ( 0.00%) fn parse_constness(&mut self) -> Const { . // Avoid const blocks to be parsed as const items 68 ( 0.00%) if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace)) . && self.eat_keyword(kw::Const) . { 10 ( 0.00%) Const::Yes(self.prev_token.uninterpolated_span()) . } else { . Const::No . } 392 ( 0.00%) } . . /// Parses inline const expressions. . fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P> { . if pat { . self.sess.gated_spans.gate(sym::inline_const_pat, span); . } else { . self.sess.gated_spans.gate(sym::inline_const, span); . } -- line 1104 ---------------------------------------- -- line 1110 ---------------------------------------- . }; . let blk_span = anon_const.value.span; . Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::new())) . } . . /// Parses mutability (`mut` or nothing). . fn parse_mutability(&mut self) -> Mutability { . if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not } 6 ( 0.00%) } . . /// Possibly parses mutability (`const` or `mut`). . fn parse_const_or_mut(&mut self) -> Option { . if self.eat_keyword(kw::Mut) { . Some(Mutability::Mut) . } else if self.eat_keyword(kw::Const) { . Some(Mutability::Not) . } else { -- line 1126 ---------------------------------------- -- line 1139 ---------------------------------------- . } . } . . fn parse_mac_args(&mut self) -> PResult<'a, P> { . self.parse_mac_args_common(true).map(P) . } . . fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> { 51 ( 0.00%) self.parse_mac_args_common(false) . } . 153 ( 0.00%) fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> { 136 ( 0.00%) Ok( 117 ( 0.00%) if self.check(&token::OpenDelim(DelimToken::Paren)) 24 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Bracket)) 24 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Brace)) . { 36 ( 0.00%) match self.parse_token_tree() { 45 ( 0.00%) TokenTree::Delimited(dspan, delim, tokens) => . // We've confirmed above that there is a delimiter so unwrapping is OK. . { 18 ( 0.00%) MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens) . } . _ => unreachable!(), . } 16 ( 0.00%) } else if !delimited_only { . if self.eat(&token::Eq) { . let eq_span = self.prev_token.span; . . // Collect tokens because they are used during lowering to HIR. . let expr = self.parse_expr_force_collect()?; . let span = expr.span; . . let token_kind = token::Interpolated(Lrc::new(token::NtExpr(expr))); -- line 1172 ---------------------------------------- -- line 1173 ---------------------------------------- . MacArgs::Eq(eq_span, Token::new(token_kind, span)) . } else { . MacArgs::Empty . } . } else { . return self.unexpected(); . }, . ) 119 ( 0.00%) } . . fn parse_or_use_outer_attributes( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, AttrWrapper> { 9,882 ( 0.01%) if let Some(attrs) = already_parsed_attrs { . Ok(attrs) . } else { 6,572 ( 0.00%) self.parse_outer_attributes() . } . } . . /// Parses a single token tree from the input. 88 ( 0.00%) pub(crate) fn parse_token_tree(&mut self) -> TokenTree { 33 ( 0.00%) match self.token.kind { . token::OpenDelim(..) => { . let depth = self.token_cursor.stack.len(); . . // We keep advancing the token cursor until we hit . // the matching `CloseDelim` token. 200 ( 0.00%) while !(depth == self.token_cursor.stack.len() . && matches!(self.token.kind, token::CloseDelim(_))) . { . // Advance one token at a time, so `TokenCursor::next()` . // can capture these tokens if necessary. 98 ( 0.00%) self.bump(); . } . // We are still inside the frame corresponding . // to the delimited stream we captured, so grab . // the tokens from this frame. . let frame = &self.token_cursor.frame; 22 ( 0.00%) let stream = frame.tree_cursor.stream.clone(); 22 ( 0.00%) let span = frame.span; 11 ( 0.00%) let delim = frame.delim; . // Consume close delimiter 22 ( 0.00%) self.bump(); 55 ( 0.00%) TokenTree::Delimited(span, delim, stream) . } . token::CloseDelim(_) | token::Eof => unreachable!(), . _ => { . self.bump(); . TokenTree::Token(self.prev_token.clone()) . } . } 77 ( 0.00%) } . . /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF. . pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec> { . let mut tts = Vec::new(); . while self.token != token::Eof { . tts.push(self.parse_token_tree()); . } . Ok(tts) -- line 1234 ---------------------------------------- -- line 1244 ---------------------------------------- . } . TokenStream::new(result) . } . . /// Evaluates the closure with restrictions in place. . /// . /// Afters the closure is evaluated, restrictions are reset. . fn with_res(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T { 3,304 ( 0.00%) let old = self.restrictions; 3,327 ( 0.00%) self.restrictions = res; . let res = f(self); 3,319 ( 0.00%) self.restrictions = old; . res . } . 344 ( 0.00%) fn is_crate_vis(&self) -> bool { 215 ( 0.00%) self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep) 387 ( 0.00%) } . . /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`, . /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`. . /// If the following element can't be a tuple (i.e., it's a function definition), then . /// it's not a tuple struct field), and the contents within the parentheses aren't valid, . /// so emit a proper diagnostic. . // Public for rustfmt usage. 340 ( 0.00%) pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> { 68 ( 0.00%) maybe_whole!(self, NtVis, |x| x); . 34 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw::Crate)); 136 ( 0.00%) if self.is_crate_vis() { . self.bump(); // `crate` . self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span); . return Ok(Visibility { . span: self.prev_token.span, . kind: VisibilityKind::Crate(CrateSugar::JustCrate), . tokens: None, . }); . } . . if !self.eat_keyword(kw::Pub) { . // We need a span for our `Spanned`, but there's inherently no . // keyword to grab a span from for inherited visibility; an empty span at the . // beginning of the current token would seem to be the "Schelling span". 28 ( 0.00%) return Ok(Visibility { 84 ( 0.00%) span: self.token.span.shrink_to_lo(), . kind: VisibilityKind::Inherited, . tokens: None, . }); . } 6 ( 0.00%) let lo = self.prev_token.span; . 30 ( 0.00%) if self.check(&token::OpenDelim(token::Paren)) { . // We don't `self.bump()` the `(` yet because this might be a struct definition where . // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`. . // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so . // by the following tokens. . if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep) . // account for `pub(crate::foo)` . { . // Parse `pub(crate)`. -- line 1303 ---------------------------------------- -- line 1338 ---------------------------------------- . } else if let FollowedByType::No = fbt { . // Provide this diagnostic if a type cannot follow; . // in particular, if this is not a tuple struct. . self.recover_incorrect_vis_restriction()?; . // Emit diagnostic, but continue with public visibility. . } . } . 18 ( 0.00%) Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None }) 306 ( 0.00%) } . . /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }` . fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> { . self.bump(); // `(` . let path = self.parse_path(PathStyle::Mod)?; . self.expect(&token::CloseDelim(token::Paren))?; // `)` . . let msg = "incorrect visibility restriction"; -- line 1355 ---------------------------------------- -- line 1370 ---------------------------------------- . ) . .emit(); . . Ok(()) . } . . /// Parses `extern string_literal?`. . fn parse_extern(&mut self) -> Extern { 10 ( 0.00%) if self.eat_keyword(kw::Extern) { Extern::from_abi(self.parse_abi()) } else { Extern::None } . } . . /// Parses a string literal as an ABI spec. . fn parse_abi(&mut self) -> Option { . match self.parse_str_lit() { . Ok(str_lit) => Some(str_lit), . Err(Some(lit)) => match lit.kind { . ast::LitKind::Err(_) => None, -- line 1386 ---------------------------------------- -- line 1409 ---------------------------------------- . self.collect_tokens_trailing_token( . AttrWrapper::empty(), . ForceCollect::Yes, . |this, _attrs| Ok((f(this)?, TrailingToken::None)), . ) . } . . /// `::{` or `::*` 1,216 ( 0.00%) fn is_import_coupler(&mut self) -> bool { 608 ( 0.00%) self.check(&token::ModSep) . && self.look_ahead(1, |t| { 239 ( 0.00%) *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star) . }) 1,260 ( 0.00%) } . . pub fn clear_expected_tokens(&mut self) { . self.expected_tokens.clear(); . } . } . . crate fn make_unclosed_delims_error( . unmatched: UnmatchedBrace, -- line 1430 ---------------------------------------- -- line 1450 ---------------------------------------- . err.span_label(sp, "closing delimiter possibly meant for this"); . } . if let Some(sp) = unmatched.unclosed_span { . err.span_label(sp, "unclosed delimiter"); . } . Some(err) . } . 120 ( 0.00%) pub fn emit_unclosed_delims(unclosed_delims: &mut Vec, sess: &ParseSess) { 60 ( 0.00%) *sess.reached_eof.borrow_mut() |= . unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()); 60 ( 0.00%) for unmatched in unclosed_delims.drain(..) { . if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) { . e.emit(); . } . } 120 ( 0.00%) } . . /// A helper struct used when building an `AttrAnnotatedTokenStream` from . /// a `LazyTokenStream`. Both delimiter and non-delimited tokens . /// are stored as `FlatToken::Token`. A vector of `FlatToken`s . /// is then 'parsed' to build up an `AttrAnnotatedTokenStream` with nested . /// `AttrAnnotatedTokenTree::Delimited` tokens . #[derive(Debug, Clone)] . pub enum FlatToken { -- line 1474 ---------------------------------------- 46,211 ( 0.02%) -------------------------------------------------------------------------------- The following files chosen for auto-annotation could not be found: -------------------------------------------------------------------------------- ./elf/../sysdeps/x86_64/dl-machine.h ./elf/dl-lookup.c ./elf/do-rel.h ./malloc/malloc.c ./stdlib/cxa_finalize.c ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S ./string/../sysdeps/x86_64/strcmp.S -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 77,623,481 (39.33%) events annotated