-------------------------------------------------------------------------------- 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 idna --edition=2018 src/lib.rs --error-format=json --json=diagnostic-rendered-ansi,artifacts,future-incompat --crate-type lib --emit=dep-info,metadata -C embed-bitcode=no -C debuginfo=2 -C metadata=29482b3a0968d793 -C extra-filename=-29482b3a0968d793 --out-dir /usr/home/liquid/tmp/.tmpBlZw3D/target/debug/deps -L dependency=/usr/home/liquid/tmp/.tmpBlZw3D/target/debug/deps --extern matches=/usr/home/liquid/tmp/.tmpBlZw3D/target/debug/deps/libmatches-23150ca1b1f9b6a3.rmeta --extern unicode_bidi=/usr/home/liquid/tmp/.tmpBlZw3D/target/debug/deps/libunicode_bidi-9eea0b99a75e96d1.rmeta --extern unicode_normalization=/usr/home/liquid/tmp/.tmpBlZw3D/target/debug/deps/libunicode_normalization-78130aad39d59688.rmeta -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-idna-0.2.3-Check-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 2,527,726,067 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 69,842,033 ( 2.76%) ./malloc/malloc.c:_int_malloc 69,401,787 ( 2.75%) ./malloc/malloc.c:_int_free 47,403,531 ( 1.88%) ./malloc/malloc.c:malloc 38,696,717 ( 1.53%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 21,030,058 ( 0.83%) ./malloc/malloc.c:free 16,507,874 ( 0.65%) ./malloc/malloc.c:malloc_consolidate 12,438,699 ( 0.49%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 12,131,858 ( 0.48%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/mod.rs:::next_token 11,350,076 ( 0.45%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 10,305,124 ( 0.41%) ./elf/dl-lookup.c:_dl_lookup_symbol_x 9,560,206 ( 0.38%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs:::span_data_to_lines_and_cols 8,982,737 ( 0.36%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs:::advance_token 8,938,459 ( 0.35%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::check 8,842,753 ( 0.35%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::parse_token_tree 8,453,257 ( 0.33%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs:>::try_read_immediate 8,435,807 ( 0.33%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::get:: 8,343,972 ( 0.33%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::short_write_process_buffer:: 7,977,105 ( 0.32%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 7,938,034 ( 0.31%) /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::> 7,844,922 ( 0.31%) ./malloc/malloc.c:unlink_chunk.constprop.0 7,368,827 ( 0.29%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::hash_stable 6,866,562 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 6,785,095 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 6,649,206 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 6,370,064 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_target/src/abi/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 6,253,863 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 6,141,344 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/hir/map/mod.rs:::attrs 5,845,902 ( 0.23%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 5,804,771 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_target/src/abi/mod.rs:::scalar::> 5,416,714 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs:::lookup_source_file_idx 5,374,468 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/coercion.rs:::coerce 5,358,873 ( 0.21%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::reserve_rehash::>::{closure#0}> 5,245,313 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs:rustc_mir_dataflow::drop_flag_effects::on_all_children_bits::is_terminal_path 5,244,013 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::eq 5,220,409 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/middle/region.rs:::temporary_scope 5,119,989 ( 0.20%) /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 5,103,929 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:>::hash_stable 4,835,679 ( 0.19%) ./elf/dl-lookup.c:do_lookup_x 4,773,428 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next_with_spacing 4,771,925 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::shallow_resolve_ty 4,752,698 ( 0.19%) /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}> 4,634,100 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs:> as rustc_trait_selection::traits::query::type_op::TypeOp>::fully_perform 4,618,163 ( 0.18%) /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::> 4,558,588 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/hir/map/mod.rs:::find_parent_node 4,500,404 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs:::read_scalar:: 4,483,680 ( 0.18%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:::node_type_opt 4,411,991 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/undo_log.rs:::rollback_to 4,282,846 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::maybe_lint_level_root_bounded 4,266,795 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/cx/expr.rs:::mirror_expr_inner 4,260,539 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/encoder.rs:>::encode 4,238,768 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::lang_items 4,187,372 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/freshen.rs:::fold_ty 4,181,524 ( 0.17%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>>::from_key_hashed_nocheck:: 4,154,495 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/validity.rs:>::try_visit_primitive 4,141,271 ( 0.16%) ./elf/../sysdeps/x86_64/dl-machine.h:_dl_relocate_object 4,017,198 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs:::get_bytes_internal:: 3,972,178 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::ident 3,956,950 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::force_allocation_maybe_sized 3,919,125 ( 0.16%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/md-5-0.9.1/src/utils.rs:md5::utils::compress 3,895,547 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/middle/region.rs:>>::get:: 3,850,768 ( 0.15%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::insert 3,808,089 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::push 3,806,161 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/undo_log.rs:>::reverse 3,744,482 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/memory.rs:>::get 3,738,938 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/validity.rs: as rustc_const_eval::interpret::visitor::ValueVisitor>::visit_value 3,723,852 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/validity.rs:>::aggregate_field_path_elem 3,676,150 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:::to 3,666,951 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:>::truncate 3,612,043 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::insert::>::{closure#0}> 3,611,115 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::start_snapshot 3,581,724 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/regionck.rs:::visit_expr 3,559,454 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/memory.rs:>::get_global_alloc 3,546,249 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/cx/expr.rs:::make_mirror_unadjusted 3,542,372 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>, (), core::hash::BuildHasherDefault>>::from_hash::>>::{closure#0}> 3,516,178 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_borrowck/src/type_check/canonical.rs:::fully_perform_op::<&rustc_middle::ty::TyS, rustc_middle::ty::ParamEnvAnd>> 3,513,727 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::commit_from 3,461,329 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::reserve_rehash::>::{closure#0}> 3,454,506 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs:::attrs 3,439,724 ( 0.14%) ./malloc/malloc.c:realloc 3,427,928 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:md5::utils::compress 3,357,267 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs:>::read_discriminant 3,350,385 ( 0.13%) /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}> 3,343,440 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs:::get_relocations:: 3,340,957 ( 0.13%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, rustc_query_system::dep_graph::graph::DepNodeIndex), core::hash::BuildHasherDefault>>::from_key_hashed_nocheck:: 3,296,606 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/writeback.rs:::visit_node_id 3,292,412 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs:::parse_assoc_expr_with 3,273,946 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/leb128.rs:>::encode 3,254,544 ( 0.13%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:::opt_local_def_id 3,250,382 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/visitor.rs: as rustc_const_eval::interpret::visitor::ValueVisitor>::walk_value 3,248,088 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::_intern_substs 3,235,728 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/into_iter.rs:> as core::ops::drop::Drop>::drop 3,159,000 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump_with 3,149,018 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/opaque.rs:>::decode 3,144,575 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::_intern_substs 3,142,438 ( 0.12%) /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} 3,077,153 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs:::start_snapshot 3,069,017 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/util.rs:::checked_add 3,049,138 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::try_read_immediate 3,045,059 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/expr.rs:::check_expr_with_expectation_and_args 3,044,309 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/build/expr/as_operand.rs:::as_operand 2,988,337 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/../../stdarch/crates/core_arch/src/x86/sse2.rs:>>::from_key_hashed_nocheck:: 2,979,862 ( 0.12%) /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}> 2,965,100 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/sub.rs:::tys 2,947,363 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs:::fold_ty 2,934,148 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_target/src/abi/mod.rs:::hash:: 2,926,735 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs:>::operand_field 2,885,698 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_privacy/src/lib.rs: as rustc_middle::ty::fold::TypeVisitor>::visit_ty 2,881,030 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>, (), core::hash::BuildHasherDefault>>::from_hash::>>::{closure#0}> 2,876,720 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/stacker-0.1.14/src/lib.rs:stacker::remaining_stack 2,855,652 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_target/src/abi/mod.rs:::read_scalar:: 2,855,196 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:::check 2,829,726 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>::decode 2,828,393 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:::to 2,766,360 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/levels.rs:::push 2,751,804 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/type_variable.rs:::probe 2,706,857 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/hygiene.rs:>::hash_stable 2,703,522 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/unicode-xid-0.2.2/src/lib.rs:::eat_while:: 2,695,419 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/mod.rs:::next_token 2,675,403 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_borrowck/src/type_check/mod.rs:::check_rvalue 2,667,442 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 2,666,734 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::operand_field 2,637,247 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::decode 2,630,612 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_hir/src/intravisit.rs:rustc_hir::intravisit::walk_expr:: 2,619,568 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/select/mod.rs:::new 2,596,449 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::intern_ty 2,566,881 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::place_field 2,561,405 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/mem_categorization.rs:::cat_expr_unadjusted -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/mod.rs -------------------------------------------------------------------------------- Ir -- line 159 ---------------------------------------- . /// let s = "not empty"; . /// assert!(!s.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_str_is_empty", since = "1.39.0")] . #[must_use] . #[inline] . pub const fn is_empty(&self) -> bool { 318,085 ( 0.01%) self.len() == 0 . } . . /// Checks that `index`-th byte is the first byte in a UTF-8 code point . /// sequence or the end of the string. . /// . /// The start and end of the string (when `index == self.len()`) are . /// considered to be boundaries. . /// -- line 175 ---------------------------------------- -- line 193 ---------------------------------------- . #[must_use] . #[stable(feature = "is_char_boundary", since = "1.9.0")] . #[inline] . pub fn is_char_boundary(&self, index: usize) -> bool { . // 0 is always ok. . // Test for 0 explicitly so that it can optimize out the check . // easily and skip reading string data for that case. . // Note that optimizing `self.get(..index)` relies on this. 1,567,560 ( 0.06%) if index == 0 { . return true; . } . 807,550 ( 0.03%) match self.as_bytes().get(index) { . // For `None` we have two options: . // . // - index == self.len() . // Empty strings are valid, so return true . // - index > self.len() . // In this case return false . // . // The check is placed exactly here, because it improves generated . // code on higher opt-levels. See PR #84751 for more details. 313,506 ( 0.01%) None => index == self.len(), . . // This is bit magic equivalent to: b < 128 || b >= 192 559,919 ( 0.02%) Some(&b) => (b as i8) >= -0x40, . } . } . . /// Converts a string slice to a byte slice. To convert the byte slice back . /// into a string slice, use the [`from_utf8`] function. . /// . /// # Examples . /// -- line 226 ---------------------------------------- -- line 808 ---------------------------------------- . /// . /// assert_eq!(None, iter.next()); . /// ``` . #[must_use = "this returns the split string as an iterator, \ . without modifying the original"] . #[stable(feature = "split_whitespace", since = "1.1.0")] . #[inline] . pub fn split_whitespace(&self) -> SplitWhitespace<'_> { 9 ( 0.00%) SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) } . } . . /// Splits a string slice by ASCII whitespace. . /// . /// The iterator returned will return string slices that are sub-slices of . /// the original string slice, separated by any amount of ASCII whitespace. . /// . /// To split by Unicode `Whitespace` instead, use [`split_whitespace`]. -- line 824 ---------------------------------------- -- line 1056 ---------------------------------------- . /// ``` . /// let s = "Löwe 老虎 Léopard"; . /// let x: &[_] = &['1', '2']; . /// . /// assert_eq!(s.find(x), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 6 ( 0.00%) pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option { 1 ( 0.00%) pat.into_searcher(self).next_match().map(|(i, _)| i) 2 ( 0.00%) } . . /// Returns the byte index for the first character of the rightmost match of the pattern in . /// this string slice. . /// . /// Returns [`None`] if the pattern doesn't match. . /// . /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a . /// function or closure that determines if a character matches. -- line 1074 ---------------------------------------- -- line 1102 ---------------------------------------- . /// ``` . /// let s = "Löwe 老虎 Léopard"; . /// let x: &[_] = &['1', '2']; . /// . /// assert_eq!(s.rfind(x), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 1,056 ( 0.00%) pub fn rfind<'a, P>(&'a self, pat: P) -> Option . where . P: Pattern<'a, Searcher: ReverseSearcher<'a>>, . { . pat.into_searcher(self).next_match_back().map(|(i, _)| i) 1,056 ( 0.00%) } . . /// An iterator over substrings of this string slice, separated by . /// characters matched by a pattern. . /// . /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a . /// function or closure that determines if a character matches. . /// . /// [`char`]: prim@char -- line 1123 ---------------------------------------- -- line 1225 ---------------------------------------- . /// ``` . /// . /// Use [`split_whitespace`] for this behavior. . /// . /// [`split_whitespace`]: str::split_whitespace . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> { 444 ( 0.00%) Split(SplitInternal { . start: 0, . end: self.len(), . matcher: pat.into_searcher(self), . allow_trailing_empty: true, . finished: false, . }) . } . -- line 1241 ---------------------------------------- -- line 1472 ---------------------------------------- . /// . /// ``` . /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect(); . /// assert_eq!(v, ["abc", "defXghi"]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> { 210 ( 0.00%) SplitN(SplitNInternal { iter: self.split(pat).0, count: n }) . } . . /// An iterator over substrings of this string slice, separated by a . /// pattern, starting from the end of the string, restricted to returning . /// at most `n` items. . /// . /// If `n` substrings are returned, the last substring (the `n`th substring) . /// will contain the remainder of the string. -- line 1488 ---------------------------------------- -- line 1540 ---------------------------------------- . /// ``` . /// assert_eq!("cfg".split_once('='), None); . /// assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo"))); . /// assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar"))); . /// ``` . #[stable(feature = "str_split_once", since = "1.52.0")] . #[inline] . pub fn split_once<'a, P: Pattern<'a>>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)> { 50 ( 0.00%) let (start, end) = delimiter.into_searcher(self).next_match()?; . // SAFETY: `Searcher` is known to return valid indices. . unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) } . } . . /// Splits the string on the last occurrence of the specified delimiter and . /// returns prefix before delimiter and suffix after delimiter. . /// . /// # Examples -- line 1556 ---------------------------------------- -- line 1749 ---------------------------------------- . /// . /// assert_eq!("Hello\tworld", s.trim()); . /// ``` . #[inline] . #[must_use = "this returns the trimmed string as a slice, \ . without modifying the original"] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn trim(&self) -> &str { 8 ( 0.00%) self.trim_matches(|c: char| c.is_whitespace()) . } . . /// Returns a string slice with leading whitespace removed. . /// . /// 'Whitespace' is defined according to the terms of the Unicode Derived . /// Core Property `White_Space`. . /// . /// # Text directionality -- line 1765 ---------------------------------------- -- line 1825 ---------------------------------------- . /// let s = " עברית "; . /// assert!(Some('ת') == s.trim_end().chars().rev().next()); . /// ``` . #[inline] . #[must_use = "this returns the trimmed string as a new slice, \ . without modifying the original"] . #[stable(feature = "trim_direction", since = "1.30.0")] . pub fn trim_end(&self) -> &str { 37 ( 0.00%) self.trim_end_matches(|c: char| c.is_whitespace()) . } . . /// Returns a string slice with leading whitespace removed. . /// . /// 'Whitespace' is defined according to the terms of the Unicode Derived . /// Core Property `White_Space`. . /// . /// # Text directionality -- line 1841 ---------------------------------------- -- line 1945 ---------------------------------------- . /// A more complex pattern, using a closure: . /// . /// ``` . /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar"); . /// ``` . #[must_use = "this returns the trimmed string as a new slice, \ . without modifying the original"] . #[stable(feature = "rust1", since = "1.0.0")] 2,448 ( 0.00%) pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a str . where . P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>, . { . let mut i = 0; . let mut j = 0; . let mut matcher = pat.into_searcher(self); . if let Some((a, b)) = matcher.next_reject() { . i = a; -- line 1961 ---------------------------------------- -- line 1962 ---------------------------------------- . j = b; // Remember earliest known match, correct it below if . // last match is different . } . if let Some((_, b)) = matcher.next_reject_back() { . j = b; . } . // SAFETY: `Searcher` is known to return valid indices. . unsafe { self.get_unchecked(i..j) } 2,448 ( 0.00%) } . . /// Returns a string slice with all prefixes that match a pattern . /// repeatedly removed. . /// . /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a . /// function or closure that determines if a character matches. . /// . /// [`char`]: prim@char -- line 1978 ---------------------------------------- -- line 1994 ---------------------------------------- . /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123"); . /// . /// let x: &[_] = &['1', '2']; . /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12"); . /// ``` . #[must_use = "this returns the trimmed string as a new slice, \ . without modifying the original"] . #[stable(feature = "trim_direction", since = "1.30.0")] 1,830 ( 0.00%) pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str { . let mut i = self.len(); . let mut matcher = pat.into_searcher(self); . if let Some((a, _)) = matcher.next_reject() { . i = a; . } . // SAFETY: `Searcher` is known to return valid indices. . unsafe { self.get_unchecked(i..self.len()) } 1,830 ( 0.00%) } . . /// Returns a string slice with the prefix removed. . /// . /// If the string starts with the pattern `prefix`, returns substring after the prefix, wrapped . /// in `Some`. Unlike `trim_start_matches`, this method removes the prefix exactly once. . /// . /// If the string does not start with `prefix`, returns `None`. . /// -- line 2018 ---------------------------------------- -- line 2098 ---------------------------------------- . /// A more complex pattern, using a closure: . /// . /// ``` . /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo"); . /// ``` . #[must_use = "this returns the trimmed string as a new slice, \ . without modifying the original"] . #[stable(feature = "trim_direction", since = "1.30.0")] 333 ( 0.00%) pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a str . where . P: Pattern<'a, Searcher: ReverseSearcher<'a>>, . { . let mut j = 0; . let mut matcher = pat.into_searcher(self); . if let Some((_, b)) = matcher.next_reject_back() { . j = b; . } . // SAFETY: `Searcher` is known to return valid indices. . unsafe { self.get_unchecked(0..j) } 370 ( 0.00%) } . . /// Returns a string slice with all prefixes that match a pattern . /// repeatedly removed. . /// . /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a . /// function or closure that determines if a character matches. . /// . /// [`char`]: prim@char -- line 2125 ---------------------------------------- -- line 2240 ---------------------------------------- . /// ``` . /// let nope = "j".parse::(); . /// . /// assert!(nope.is_err()); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn parse(&self) -> Result { 21 ( 0.00%) FromStr::from_str(self) . } . . /// Checks if all characters in this string are within the ASCII range. . /// . /// # Examples . /// . /// ``` . /// let ascii = "hello!\n"; -- line 2256 ---------------------------------------- -- line 2420 ---------------------------------------- . /// Using `to_string`: . /// . /// ``` . /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!"); . /// ``` . #[must_use = "this returns the escaped string as an iterator, \ . without modifying the original"] . #[stable(feature = "str_escape", since = "1.34.0")] 13 ( 0.00%) pub fn escape_default(&self) -> EscapeDefault<'_> { 52 ( 0.00%) EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) } 13 ( 0.00%) } . . /// Return an iterator that escapes each char in `self` with [`char::escape_unicode`]. . /// . /// # Examples . /// . /// As an iterator: . /// . /// ``` -- line 2438 ---------------------------------------- 377 ( 0.00%) -------------------------------------------------------------------------------- -- 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, . ) { 11,633 ( 0.00%) if let Some((file, file_idx)) = new_file_and_idx { 884 ( 0.00%) self.file = file; 1,066 ( 0.00%) self.file_index = file_idx; . } . 10,801 ( 0.00%) let line_index = self.file.lookup_line(pos).unwrap(); . let line_bounds = self.file.line_bounds(line_index); 22,902 ( 0.00%) self.line_number = line_index + 1; 34,379 ( 0.00%) self.line = line_bounds; . self.touch(time_stamp); . } . . #[inline] . fn touch(&mut self, time_stamp: usize) { 261,515 ( 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> { 518 ( 0.00%) pub fn new(source_map: &'sm SourceMap) -> CachingSourceMapView<'sm> { . let files = source_map.files(); 259 ( 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, . }; . 1,295 ( 0.00%) CachingSourceMapView { . source_map, 1,813 ( 0.00%) line_cache: [entry.clone(), entry.clone(), entry], . time_stamp: 0, . } 1,036 ( 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)) . } . 954,562 ( 0.04%) pub fn span_data_to_lines_and_cols( . &mut self, . span_data: &SpanData, . ) -> Option<(Lrc, usize, BytePos, usize, BytePos)> { 545,464 ( 0.02%) self.time_stamp += 1; . . // Check if lo and hi are in the cached lines. 136,366 ( 0.01%) let lo_cache_idx = self.cache_entry_index(span_data.lo); 136,366 ( 0.01%) let hi_cache_idx = self.cache_entry_index(span_data.hi); . 250,348 ( 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 = { 250,298 ( 0.01%) let lo = &self.line_cache[lo_cache_idx as usize]; . let hi = &self.line_cache[hi_cache_idx as usize]; . 750,894 ( 0.03%) if lo.file_index != hi.file_index { . return None; . } . . ( 250,298 ( 0.01%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 125,149 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . ) . }; . 125,149 ( 0.00%) self.line_cache[lo_cache_idx as usize].touch(self.time_stamp); 125,149 ( 0.00%) self.line_cache[hi_cache_idx as usize].touch(self.time_stamp); . 500,596 ( 0.02%) return Some(result); . } . . // No cache hit or cache hit for only one of span lo and hi. 22,384 ( 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. 89,700 ( 0.00%) let new_file_and_idx = if !file_contains(&self.line_cache[oldest].file, span_data.lo) { 2,080 ( 0.00%) let new_file_and_idx = self.file_for_position(span_data.lo)?; 2,496 ( 0.00%) if !file_contains(&new_file_and_idx.0, span_data.hi) { . return None; . } . 1,664 ( 0.00%) Some(new_file_and_idx) . } else { . let file = &self.line_cache[oldest].file; 32,403 ( 0.00%) if !file_contains(&file, span_data.hi) { . return None; . } . 32,403 ( 0.00%) None . }; . . // Update the cache entries. 56,085 ( 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); . 32,952 ( 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); 50 ( 0.00%) let hi = &mut self.line_cache[hi_cache_idx as usize]; 75 ( 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]; 208 ( 0.00%) hi.update(new_file_and_idx, span_data.hi, self.time_stamp); 416 ( 0.00%) let lo = &mut self.line_cache[lo_cache_idx as usize]; 832 ( 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. 22,434 ( 0.00%) assert!(span_data.lo >= lo.line.start); 11,217 ( 0.00%) assert!(span_data.lo <= lo.line.end); 22,434 ( 0.00%) assert!(span_data.hi >= hi.line.start); 11,217 ( 0.00%) assert!(span_data.hi <= hi.line.end); 56,085 ( 0.00%) assert!(lo.file.contains(span_data.lo)); 33,651 ( 0.00%) assert!(lo.file.contains(span_data.hi)); 33,651 ( 0.00%) assert_eq!(lo.file_index, hi.file_index); . 33,651 ( 0.00%) Some(( 11,217 ( 0.00%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 11,217 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . )) 1,227,294 ( 0.05%) } . . fn cache_entry_index(&self, pos: BytePos) -> isize { . for (idx, cache_entry) in self.line_cache.iter().enumerate() { 1,686,155 ( 0.07%) 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() { 65,904 ( 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() { 2,827 ( 0.00%) if idx != avoid_idx 1,603 ( 0.00%) && self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp . { . oldest = idx; . } . } . . oldest . } . 2,080 ( 0.00%) fn file_for_position(&self, pos: BytePos) -> Option<(Lrc, usize)> { 416 ( 0.00%) if !self.source_map.files().is_empty() { 832 ( 0.00%) let file_idx = self.source_map.lookup_source_file_idx(pos); . let file = &self.source_map.files()[file_idx]; . 3,328 ( 0.00%) if file_contains(file, pos) { . return Some((file.clone(), file_idx)); . } . } . . None 2,080 ( 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 ---------------------------------------- 1,562,914 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/select/mod.rs -------------------------------------------------------------------------------- Ir -- line 208 ---------------------------------------- . /// There is no built-in impl. There may be some other . /// candidate (a where-clause or user-defined impl). . None, . /// It is unknown whether there is an impl. . Ambiguous, . } . . impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { 561,336 ( 0.02%) pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> { 1,691,686 ( 0.07%) SelectionContext { . infcx, 148,542 ( 0.01%) freshener: infcx.freshener_keep_static(), . intercrate: false, . intercrate_ambiguity_causes: None, . allow_negative_impls: false, . query_mode: TraitQueryMode::Standard, . } 467,780 ( 0.02%) } . . pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> { 16 ( 0.00%) SelectionContext { . infcx, 2 ( 0.00%) freshener: infcx.freshener_keep_static(), . intercrate: true, . intercrate_ambiguity_causes: None, . allow_negative_impls: false, . query_mode: TraitQueryMode::Standard, . } . } . . pub fn with_negative( -- line 238 ---------------------------------------- -- line 245 ---------------------------------------- . freshener: infcx.freshener_keep_static(), . intercrate: false, . intercrate_ambiguity_causes: None, . allow_negative_impls, . query_mode: TraitQueryMode::Standard, . } . } . 3,536 ( 0.00%) pub fn with_query_mode( . infcx: &'cx InferCtxt<'cx, 'tcx>, . query_mode: TraitQueryMode, . ) -> SelectionContext<'cx, 'tcx> { . debug!(?query_mode, "with_query_mode"); 7,072 ( 0.00%) SelectionContext { . infcx, 442 ( 0.00%) freshener: infcx.freshener_keep_static(), . intercrate: false, . intercrate_ambiguity_causes: None, . allow_negative_impls: false, . query_mode, . } 2,652 ( 0.00%) } . . /// Enables tracking of intercrate ambiguity causes. These are . /// used in coherence to give improved diagnostics. We don't do . /// this until we detect a coherence error because it can lead to . /// false overflow results (#47139) and because it costs . /// computation time. . pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) { . assert!(self.intercrate); -- line 274 ---------------------------------------- -- line 281 ---------------------------------------- . /// was enabled and disables tracking at the same time. If . /// tracking is not enabled, just returns an empty vector. . pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec { . assert!(self.intercrate); . self.intercrate_ambiguity_causes.take().unwrap_or_default() . } . . pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> { 193,505 ( 0.01%) self.infcx 65,966 ( 0.00%) } . . pub fn tcx(&self) -> TyCtxt<'tcx> { 182,375 ( 0.01%) self.infcx.tcx . } . . pub fn is_intercrate(&self) -> bool { 3,425 ( 0.00%) self.intercrate . } . . /////////////////////////////////////////////////////////////////////////// . // Selection . // . // The selection phase tries to identify *how* an obligation will . // be resolved. For example, it will identify which impl or . // parameter bound is to be used. The process can be inconclusive -- line 305 ---------------------------------------- -- line 309 ---------------------------------------- . // 1. If no applicable impl or parameter bound can be found. . // 2. If the output type parameters in the obligation do not match . // those specified by the impl/bound. For example, if the obligation . // is `Vec: Iterable`, but the impl specifies . // `impl Iterable for Vec`, than an error would result. . . /// Attempts to satisfy the obligation. If successful, this will affect the surrounding . /// type environment by performing unification. 205,884 ( 0.01%) #[instrument(level = "debug", skip(self))] 264,708 ( 0.01%) pub fn select( . &mut self, . obligation: &TraitObligation<'tcx>, . ) -> SelectionResult<'tcx, Selection<'tcx>> { 261,390 ( 0.01%) let candidate = match self.select_from_obligation(obligation) { . Err(SelectionError::Overflow) => { . // In standard mode, overflow must have been caught and reported . // earlier. . assert!(self.query_mode == TraitQueryMode::Canonical); . return Err(SelectionError::Overflow); . } . Err(SelectionError::Ambiguous(_)) => { . return Ok(None); . } . Err(e) => { 385,910 ( 0.02%) return Err(e); . } . Ok(None) => { 1,740 ( 0.00%) return Ok(None); . } 6,474 ( 0.00%) Ok(Some(candidate)) => candidate, . }; . 10,860 ( 0.00%) match self.confirm_candidate(obligation, candidate) { . Err(SelectionError::Overflow) => { . assert!(self.query_mode == TraitQueryMode::Canonical); . Err(SelectionError::Overflow) . } 455 ( 0.00%) Err(e) => Err(e), . Ok(candidate) => { . debug!(?candidate, "confirmed"); 12,528 ( 0.00%) Ok(Some(candidate)) . } . } . } . 294,120 ( 0.01%) crate fn select_from_obligation( . &mut self, . obligation: &TraitObligation<'tcx>, . ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> { . debug_assert!(!obligation.predicate.has_escaping_bound_vars()); . . let pec = &ProvisionalEvaluationCache::default(); . let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation); . 58,824 ( 0.00%) self.candidate_from_obligation(&stack) 264,708 ( 0.01%) } . . /////////////////////////////////////////////////////////////////////////// . // EVALUATION . // . // Tests whether an obligation can be selected or whether an impl . // can be applied to particular types. It skips the "confirmation" . // step and hence completely ignores output type parameters. . // -- line 372 ---------------------------------------- -- line 384 ---------------------------------------- . self.evaluate_root_obligation(obligation) . .expect("Overflow should be caught earlier in standard query mode") . .may_apply() . } . . /// Evaluates whether the obligation `obligation` can be satisfied . /// and returns an `EvaluationResult`. This is meant for the . /// *initial* call. 884 ( 0.00%) pub fn evaluate_root_obligation( . &mut self, . obligation: &PredicateObligation<'tcx>, . ) -> Result { . self.evaluation_probe(|this| { 1,326 ( 0.00%) this.evaluate_predicate_recursively( . TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()), . obligation.clone(), . ) . }) 884 ( 0.00%) } . . fn evaluation_probe( . &mut self, . op: impl FnOnce(&mut Self) -> Result, . ) -> Result { 11,749 ( 0.00%) self.infcx.probe(|snapshot| -> Result { 884 ( 0.00%) let result = op(self)?; . 10,759 ( 0.00%) match self.infcx.leak_check(true, snapshot) { . Ok(()) => {} . Err(_) => return Ok(EvaluatedToErr), . } . 7,685 ( 0.00%) match self.infcx.region_constraints_added_in_snapshot(snapshot) { . None => Ok(result), . Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)), . } . }) . } . . /// Evaluates the predicates in `predicates` recursively. Note that . /// this applies projections in the predicates, and therefore . /// is run within an inference probe. 22,120 ( 0.00%) #[instrument(skip(self, stack), level = "debug")] . fn evaluate_predicates_recursively<'o, I>( . &mut self, . stack: TraitObligationStackList<'o, 'tcx>, . predicates: I, . ) -> Result . where . I: IntoIterator> + std::fmt::Debug, . { . let mut result = EvaluatedToOk; 7,237 ( 0.00%) for obligation in predicates { 1,040 ( 0.00%) let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?; 520 ( 0.00%) if let EvaluatedToErr = eval { . // fast-path - EvaluatedToErr is the top of the lattice, . // so we don't need to look on the other predicates. . return Ok(EvaluatedToErr); . } else { . result = cmp::max(result, eval); . } . } . Ok(result) . } . 7,020 ( 0.00%) #[instrument( . level = "debug", . skip(self, previous_stack), . fields(previous_stack = ?previous_stack.head()) 6,318 ( 0.00%) )] . fn evaluate_predicate_recursively<'o>( . &mut self, . previous_stack: TraitObligationStackList<'o, 'tcx>, . obligation: PredicateObligation<'tcx>, . ) -> Result { . // `previous_stack` stores a `TraitObligation`, while `obligation` is . // a `PredicateObligation`. These are distinct types, so we can't . // use any `Option` combinator method that would force them to be . // the same. 1,404 ( 0.00%) match previous_stack.head() { 510 ( 0.00%) Some(h) => self.check_recursion_limit(&obligation, h.obligation)?, 447 ( 0.00%) None => self.check_recursion_limit(&obligation, &obligation)?, . } . 4,212 ( 0.00%) let result = ensure_sufficient_stack(|| { 702 ( 0.00%) let bound_predicate = obligation.predicate.kind(); 7,020 ( 0.00%) match bound_predicate.skip_binder() { . ty::PredicateKind::Trait(t) => { . let t = bound_predicate.rebind(t); . debug_assert!(!t.has_escaping_bound_vars()); . let obligation = obligation.with(t); 9,750 ( 0.00%) self.evaluate_trait_predicate_recursively(previous_stack, obligation) . } . . ty::PredicateKind::Subtype(p) => { . let p = bound_predicate.rebind(p); . // Does this code ever run? . match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) { . Some(Ok(InferOk { mut obligations, .. })) => { . self.add_depth(obligations.iter_mut(), obligation.recursion_depth); -- line 483 ---------------------------------------- -- line 522 ---------------------------------------- . None => Ok(EvaluatedToAmbig), . }, . . ty::PredicateKind::TypeOutlives(pred) => { . // A global type with no late-bound regions can only . // contain the "'static" lifetime (any other lifetime . // would either be late-bound or local), so it is guaranteed . // to outlive any other lifetime 3 ( 0.00%) if pred.0.is_global() && !pred.0.has_late_bound_regions() { . Ok(EvaluatedToOk) . } else { . Ok(EvaluatedToOkModuloRegions) . } . } . . ty::PredicateKind::RegionOutlives(..) => { . // We do not consider region relationships when evaluating trait matches. -- line 538 ---------------------------------------- -- line 545 ---------------------------------------- . } else { . Ok(EvaluatedToErr) . } . } . . ty::PredicateKind::Projection(data) => { . let data = bound_predicate.rebind(data); . let project_obligation = obligation.with(data); 210 ( 0.00%) match project::poly_project_and_unify_type(self, &project_obligation) { 170 ( 0.00%) Ok(Ok(Some(mut subobligations))) => { . 'compute_res: { . // If we've previously marked this projection as 'complete', thne . // use the final cached result (either `EvaluatedToOk` or . // `EvaluatedToOkModuloRegions`), and skip re-evaluating the . // sub-obligations. 136 ( 0.00%) if let Some(key) = 306 ( 0.00%) ProjectionCacheKey::from_poly_projection_predicate(self, data) . { 256 ( 0.00%) if let Some(cached_res) = self . .infcx . .inner . .borrow_mut() . .projection_cache() . .is_complete(key) . { . break 'compute_res Ok(cached_res); . } . } . 68 ( 0.00%) self.add_depth( . subobligations.iter_mut(), 68 ( 0.00%) obligation.recursion_depth, . ); 68 ( 0.00%) let res = self.evaluate_predicates_recursively( 102 ( 0.00%) previous_stack, 170 ( 0.00%) subobligations, . ); 136 ( 0.00%) if let Ok(res) = res { 68 ( 0.00%) if res == EvaluatedToOk || res == EvaluatedToOkModuloRegions { 112 ( 0.00%) if let Some(key) = 28 ( 0.00%) ProjectionCacheKey::from_poly_projection_predicate( 196 ( 0.00%) self, data, . ) . { . // If the result is something that we can cache, then mark this . // entry as 'complete'. This will allow us to skip evaluating the . // suboligations at all the next time we evaluate the projection . // predicate. 182 ( 0.00%) self.infcx . .inner . .borrow_mut() . .projection_cache() . .complete(key, res); . } . } . } . res -- line 601 ---------------------------------------- -- line 603 ---------------------------------------- . } . Ok(Ok(None)) => Ok(EvaluatedToAmbig), . Ok(Err(project::InProgress)) => Ok(EvaluatedToRecur), . Err(_) => Ok(EvaluatedToErr), . } . } . . ty::PredicateKind::ClosureKind(_, closure_substs, kind) => { 75 ( 0.00%) match self.infcx.closure_kind(closure_substs) { . Some(closure_kind) => { 45 ( 0.00%) if closure_kind.extends(kind) { . Ok(EvaluatedToOk) . } else { . Ok(EvaluatedToErr) . } . } . None => Ok(EvaluatedToAmbig), . } . } -- line 621 ---------------------------------------- -- line 693 ---------------------------------------- . } . } . } . } . ty::PredicateKind::TypeWellFormedFromEnv(..) => { . bug!("TypeWellFormedFromEnv is only used for chalk") . } . } 702 ( 0.00%) }); . . debug!("finished: {:?} from {:?}", result, obligation); . . result . } . 13,650 ( 0.00%) #[instrument(skip(self, previous_stack), level = "debug")] . fn evaluate_trait_predicate_recursively<'o>( . &mut self, . previous_stack: TraitObligationStackList<'o, 'tcx>, . mut obligation: TraitObligation<'tcx>, . ) -> Result { 1,300 ( 0.00%) if !self.intercrate . && obligation.is_global() . && obligation.param_env.caller_bounds().iter().all(|bound| bound.needs_subst()) . { . // If a param env has no global bounds, global obligations do not . // depend on its particular value in order to work, so we can clear . // out the param env and get better caching. . debug!("in global"); 886 ( 0.00%) obligation.param_env = obligation.param_env.without_caller_bounds(); . } . . let stack = self.push_stack(previous_stack, &obligation); . let mut fresh_trait_pred = stack.fresh_trait_pred; 1,300 ( 0.00%) let mut param_env = obligation.param_env; . . fresh_trait_pred = fresh_trait_pred.map_bound(|mut pred| { 650 ( 0.00%) pred.remap_constness(self.tcx(), &mut param_env); 7,800 ( 0.00%) pred . }); . . debug!(?fresh_trait_pred); . 966 ( 0.00%) if let Some(result) = self.check_evaluation_cache(param_env, fresh_trait_pred) { . debug!(?result, "CACHE HIT"); . return Ok(result); . } . . if let Some(result) = stack.cache().get_provisional(fresh_trait_pred) { . debug!(?result, "PROVISIONAL CACHE HIT"); . stack.update_reached_depth(result.reached_depth); . return Ok(result.result); -- line 744 ---------------------------------------- -- line 748 ---------------------------------------- . // stack. If so, we don't want to insert the result into the . // main cache (it is cycle dependent) nor the provisional . // cache (which is meant for things that have completed but . // for a "backedge" -- this result *is* the backedge). . if let Some(cycle_result) = self.check_evaluation_cycle(&stack) { . return Ok(cycle_result); . } . 4,185 ( 0.00%) let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack)); 465 ( 0.00%) let result = result?; . 2,325 ( 0.00%) if !result.must_apply_modulo_regions() { . stack.cache().on_failure(stack.dfn); . } . 465 ( 0.00%) let reached_depth = stack.reached_depth.get(); 930 ( 0.00%) if reached_depth >= stack.depth { . debug!(?result, "CACHE MISS"); 8,835 ( 0.00%) self.insert_evaluation_cache(param_env, fresh_trait_pred, dep_node, result); . . stack.cache().on_completion( 930 ( 0.00%) stack.dfn, . |fresh_trait_pred, provisional_result, provisional_dep_node| { . // Create a new `DepNode` that has dependencies on: . // * The `DepNode` for the original evaluation that resulted in a provisional cache . // entry being crated . // * The `DepNode` for the *current* evaluation, which resulted in us completing . // provisional caches entries and inserting them into the evaluation cache . // . // This ensures that when a query reads this entry from the evaluation cache, -- line 777 ---------------------------------------- -- line 835 ---------------------------------------- . /// `self.freshener`, we can be sure that (a) this will not . /// affect the inferencer state and (b) that if we see two . /// fresh regions with the same index, they refer to the same . /// unbound type variable. . fn check_evaluation_cycle( . &mut self, . stack: &TraitObligationStack<'_, 'tcx>, . ) -> Option { 36 ( 0.00%) if let Some(cycle_depth) = stack . .iter() . .skip(1) // Skip top-most frame. . .find(|prev| { 216 ( 0.00%) stack.obligation.param_env == prev.obligation.param_env . && stack.fresh_trait_pred == prev.fresh_trait_pred . }) . .map(|stack| stack.depth) . { . debug!("evaluate_stack --> recursive at depth {}", cycle_depth); . . // If we have a stack like `A B C D E A`, where the top of . // the stack is the final `A`, then this will iterate over . // `A, E, D, C, B` -- i.e., all the participants apart . // from the cycle head. We mark them as participating in a . // cycle. This suppresses caching for those nodes. See . // `in_cycle` field for more details. 36 ( 0.00%) stack.update_reached_depth(cycle_depth); . . // Subtle: when checking for a coinductive cycle, we do . // not compare using the "freshened trait refs" (which . // have erased regions) but rather the fully explicit . // trait refs. This is important because it's only a cycle . // if the regions match exactly. 29 ( 0.00%) let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth); 18 ( 0.00%) let tcx = self.tcx(); 126 ( 0.00%) let cycle = cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx)); 198 ( 0.00%) if self.coinductive_match(cycle) { . debug!("evaluate_stack --> recursive, coinductive"); . Some(EvaluatedToOk) . } else { . debug!("evaluate_stack --> recursive, inductive"); . Some(EvaluatedToRecur) . } . } else { . None . } . } . 4,185 ( 0.00%) fn evaluate_stack<'o>( . &mut self, . stack: &TraitObligationStack<'o, 'tcx>, . ) -> Result { . // In intercrate mode, whenever any of the generics are unbound, . // there can always be an impl. Even if there are no impls in . // this crate, perhaps the type would be unified with . // something from another crate that does provide an impl. . // -- line 890 ---------------------------------------- -- line 903 ---------------------------------------- . // imagine, this is just where we started. To avoid that, we . // check for unbound variables and return an ambiguous (hence possible) . // match if we've seen this trait before. . // . // This suffices to allow chains like `FnMut` implemented in . // terms of `Fn` etc, but we could probably make this more . // precise still. . let unbound_input_types = 465 ( 0.00%) stack.fresh_trait_pred.skip_binder().trait_ref.substs.types().any(|ty| ty.is_fresh()); . 1,395 ( 0.00%) if stack.obligation.polarity() != ty::ImplPolarity::Negative { . // This check was an imperfect workaround for a bug in the old . // intercrate mode; it should be removed when that goes away. 2,325 ( 0.00%) if unbound_input_types && self.intercrate { . debug!("evaluate_stack --> unbound argument, intercrate --> ambiguous",); . // Heuristics: show the diagnostics when there are no candidates in crate. . if self.intercrate_ambiguity_causes.is_some() { . debug!("evaluate_stack: intercrate_ambiguity_causes is some"); . if let Ok(candidate_set) = self.assemble_candidates(stack) { . if !candidate_set.ambiguous && candidate_set.vec.is_empty() { . let trait_ref = stack.obligation.predicate.skip_binder().trait_ref; . let self_ty = trait_ref.self_ty(); -- line 924 ---------------------------------------- -- line 937 ---------------------------------------- . self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause); . } . } . } . return Ok(EvaluatedToAmbig); . } . } . 930 ( 0.00%) if unbound_input_types . && stack.iter().skip(1).any(|prev| { 30 ( 0.00%) stack.obligation.param_env == prev.obligation.param_env . && self.match_fresh_trait_refs( 40 ( 0.00%) stack.fresh_trait_pred, 40 ( 0.00%) prev.fresh_trait_pred, . prev.obligation.param_env, . ) . }) . { . debug!("evaluate_stack --> unbound argument, recursive --> giving up",); . return Ok(EvaluatedToUnknown); . } . 4,960 ( 0.00%) match self.candidate_from_obligation(stack) { 1,818 ( 0.00%) Ok(Some(c)) => self.evaluate_candidate(stack, &c), . Err(SelectionError::Ambiguous(_)) => Ok(EvaluatedToAmbig), . Ok(None) => Ok(EvaluatedToAmbig), . Err(Overflow) => Err(OverflowError::Canonical), . Err(ErrorReporting) => Err(OverflowError::ErrorReporting), . Err(..) => Ok(EvaluatedToErr), . } 4,650 ( 0.00%) } . . /// For defaulted traits, we use a co-inductive strategy to solve, so . /// that recursion is ok. This routine returns `true` if the top of the . /// stack (`cycle[0]`): . /// . /// - is a defaulted trait, . /// - it also appears in the backtrace at some position `X`, . /// - all the predicates at positions `X..` between `X` and the top are -- line 975 ---------------------------------------- -- line 977 ---------------------------------------- . pub fn coinductive_match(&mut self, mut cycle: I) -> bool . where . I: Iterator>, . { . cycle.all(|predicate| self.coinductive_predicate(predicate)) . } . . fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool { 36 ( 0.00%) let result = match predicate.kind().skip_binder() { 162 ( 0.00%) ty::PredicateKind::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()), . _ => false, . }; . debug!(?predicate, ?result, "coinductive_predicate"); . result . } . . /// Further evaluates `candidate` to decide whether all type parameters match and whether nested . /// obligations are met. Returns whether `candidate` remains viable after this further -- line 994 ---------------------------------------- -- line 998 ---------------------------------------- . skip(self, stack), . fields(depth = stack.obligation.recursion_depth) . )] . fn evaluate_candidate<'o>( . &mut self, . stack: &TraitObligationStack<'o, 'tcx>, . candidate: &SelectionCandidate<'tcx>, . ) -> Result { 2,114 ( 0.00%) let mut result = self.evaluation_probe(|this| { . let candidate = (*candidate).clone(); 16,921 ( 0.00%) match this.confirm_candidate(stack.obligation, candidate) { . Ok(selection) => { . debug!(?selection); 4,228 ( 0.00%) this.evaluate_predicates_recursively( . stack.list(), 13,741 ( 0.00%) selection.nested_obligations().into_iter(), . ) . } . Err(..) => Ok(EvaluatedToErr), . } . })?; . . // If we erased any lifetimes, then we want to use . // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk` -- line 1021 ---------------------------------------- -- line 1037 ---------------------------------------- . &self, . param_env: ty::ParamEnv<'tcx>, . trait_pred: ty::PolyTraitPredicate<'tcx>, . ) -> Option { . // Neither the global nor local cache is aware of intercrate . // mode, so don't do any caching. In particular, we might . // re-use the same `InferCtxt` with both an intercrate . // and non-intercrate `SelectionContext` 1,300 ( 0.00%) if self.intercrate { . return None; . } . . let tcx = self.tcx(); . if self.can_use_global_caches(param_env) { 4,522 ( 0.00%) if let Some(res) = tcx.evaluation_cache.get(¶m_env.and(trait_pred), tcx) { . return Some(res); . } . } 1,932 ( 0.00%) self.infcx.evaluation_cache.get(¶m_env.and(trait_pred), tcx) . } . 5,580 ( 0.00%) fn insert_evaluation_cache( . &mut self, . param_env: ty::ParamEnv<'tcx>, . trait_pred: ty::PolyTraitPredicate<'tcx>, . dep_node: DepNodeIndex, . result: EvaluationResult, . ) { . // Avoid caching results that depend on more than just the trait-ref . // - the stack can create recursion. 1,860 ( 0.00%) if result.is_stack_dependent() { . return; . } . . // Neither the global nor local cache is aware of intercrate . // mode, so don't do any caching. In particular, we might . // re-use the same `InferCtxt` with both an intercrate . // and non-intercrate `SelectionContext` 930 ( 0.00%) if self.intercrate { . return; . } . . if self.can_use_global_caches(param_env) { . if !trait_pred.needs_infer() { . debug!(?trait_pred, ?result, "insert_evaluation_cache global"); . // This may overwrite the cache with the same value . // FIXME: Due to #50507 this overwrites the different values . // This should be changed to use HashMapExt::insert_same . // when that is fixed 461 ( 0.00%) self.tcx().evaluation_cache.insert(param_env.and(trait_pred), dep_node, result); . return; . } . } . . debug!(?trait_pred, ?result, "insert_evaluation_cache"); 16 ( 0.00%) self.infcx.evaluation_cache.insert(param_env.and(trait_pred), dep_node, result); 3,720 ( 0.00%) } . . /// For various reasons, it's possible for a subobligation . /// to have a *lower* recursion_depth than the obligation used to create it. . /// Projection sub-obligations may be returned from the projection cache, . /// which results in obligations with an 'old' `recursion_depth`. . /// Additionally, methods like `InferCtxt.subtype_predicate` produce . /// subobligations without taking in a 'parent' depth, causing the . /// generated subobligations to have a `recursion_depth` of `0`. . /// . /// To ensure that obligation_depth never decreases, we force all subobligations . /// to have at least the depth of the original obligation. 34 ( 0.00%) fn add_depth>>( . &self, . it: I, . min_depth: usize, . ) { 64 ( 0.00%) it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1); 68 ( 0.00%) } . . fn check_recursion_depth>( . &self, . depth: usize, . error_obligation: &Obligation<'tcx, T>, . ) -> Result<(), OverflowError> { 122,316 ( 0.00%) if !self.infcx.tcx.recursion_limit().value_within_limit(depth) { . match self.query_mode { . TraitQueryMode::Standard => { . if self.infcx.is_tainted_by_errors() { . return Err(OverflowError::ErrorReporting); . } . self.infcx.report_overflow_error(error_obligation, true); . } . TraitQueryMode::Canonical => { -- line 1126 ---------------------------------------- -- line 1143 ---------------------------------------- . ) -> Result<(), OverflowError> { . self.check_recursion_depth(obligation.recursion_depth, error_obligation) . } . . fn in_task(&mut self, op: OP) -> (R, DepNodeIndex) . where . OP: FnOnce(&mut Self) -> R, . { 9,724 ( 0.00%) let (result, dep_node) = 8,208 ( 0.00%) self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self)); . self.tcx().dep_graph.read_index(dep_node); 8,976 ( 0.00%) (result, dep_node) . } . . /// filter_impls filters constant trait obligations and candidates that have a positive impl . /// for a negative goal and a negative impl for a positive goal . #[instrument(level = "debug", skip(self))] . fn filter_impls( . &mut self, . candidates: Vec>, . obligation: &TraitObligation<'tcx>, . ) -> Vec> { . let tcx = self.tcx(); . let mut result = Vec::with_capacity(candidates.len()); . 16,904 ( 0.00%) for candidate in candidates { . // Respect const trait obligations 3,657 ( 0.00%) if obligation.is_const() { . match candidate { . // const impl . ImplCandidate(def_id) . if tcx.impl_constness(def_id) == hir::Constness::Const => {} . // const param . ParamCandidate(trait_pred) . if trait_pred.skip_binder().constness . == ty::BoundConstness::ConstIfConst => {} -- line 1178 ---------------------------------------- -- line 1186 ---------------------------------------- . ConstDropCandidate(_) => {} . _ => { . // reject all other types of candidates . continue; . } . } . } . 2,438 ( 0.00%) if let ImplCandidate(def_id) = candidate { 1,992 ( 0.00%) if ty::ImplPolarity::Reservation == tcx.impl_polarity(def_id) 996 ( 0.00%) || obligation.polarity() == tcx.impl_polarity(def_id) . || self.allow_negative_impls . { . result.push(candidate); . } . } else { . result.push(candidate); . } . } . 2,796 ( 0.00%) result . } . . /// filter_reservation_impls filter reservation impl for any goal as ambiguous 8,041 ( 0.00%) #[instrument(level = "debug", skip(self))] . fn filter_reservation_impls( . &mut self, . candidate: SelectionCandidate<'tcx>, . obligation: &TraitObligation<'tcx>, . ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> { . let tcx = self.tcx(); . // Treat reservation impls as ambiguity. 1,446 ( 0.00%) if let ImplCandidate(def_id) = candidate { 500 ( 0.00%) if let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id) { . if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes { . let attrs = tcx.get_attrs(def_id); . let attr = tcx.sess.find_by_name(&attrs, sym::rustc_reservation_impl); . let value = attr.and_then(|a| a.value_str()); . if let Some(value) = value { . debug!( . "filter_reservation_impls: \ . reservation impl ambiguity on {:?}", -- line 1227 ---------------------------------------- -- line 1232 ---------------------------------------- . message: value.to_string(), . }, . ); . } . } . return Ok(None); . } . } 2,838 ( 0.00%) Ok(Some(candidate)) . } . . fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option { . debug!("is_knowable(intercrate={:?})", self.intercrate); . 2,244 ( 0.00%) if !self.intercrate || stack.obligation.polarity() == ty::ImplPolarity::Negative { . return None; . } . . let obligation = &stack.obligation; . let predicate = self.infcx().resolve_vars_if_possible(obligation.predicate); . . // Okay to skip binder because of the nature of the . // trait-ref-is-knowable check, which does not care about -- line 1254 ---------------------------------------- -- line 1286 ---------------------------------------- . &mut self, . mut param_env: ty::ParamEnv<'tcx>, . cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>, . ) -> Option>> { . // Neither the global nor local cache is aware of intercrate . // mode, so don't do any caching. In particular, we might . // re-use the same `InferCtxt` with both an intercrate . // and non-intercrate `SelectionContext` 59,754 ( 0.00%) if self.intercrate { . return None; . } . let tcx = self.tcx(); . let mut pred = cache_fresh_trait_pred.skip_binder(); 59,754 ( 0.00%) pred.remap_constness(tcx, &mut param_env); . 29,877 ( 0.00%) if self.can_use_global_caches(param_env) { 298,710 ( 0.01%) if let Some(res) = tcx.selection_cache.get(¶m_env.and(pred), tcx) { 378,664 ( 0.01%) return Some(res); . } . } 8,233 ( 0.00%) self.infcx.selection_cache.get(¶m_env.and(pred), tcx) . } . . /// Determines whether can we safely cache the result . /// of selecting an obligation. This is almost always `true`, . /// except when dealing with certain `ParamCandidate`s. . /// . /// Ordinarily, a `ParamCandidate` will contain no inference variables, . /// since it was usually produced directly from a `DefId`. However, -- line 1314 ---------------------------------------- -- line 1325 ---------------------------------------- . fn can_cache_candidate( . &self, . result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>, . ) -> bool { . // Neither the global nor local cache is aware of intercrate . // mode, so don't do any caching. In particular, we might . // re-use the same `InferCtxt` with both an intercrate . // and non-intercrate `SelectionContext` 1,496 ( 0.00%) if self.intercrate { . return false; . } 2,244 ( 0.00%) match result { . Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(), . _ => true, . } . } . . fn insert_candidate_cache( . &mut self, . mut param_env: ty::ParamEnv<'tcx>, . cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>, . dep_node: DepNodeIndex, . candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>, . ) { . let tcx = self.tcx(); . let mut pred = cache_fresh_trait_pred.skip_binder(); . 1,496 ( 0.00%) pred.remap_constness(tcx, &mut param_env); . . if !self.can_cache_candidate(&candidate) { . debug!(?pred, ?candidate, "insert_candidate_cache - candidate is not cacheable"); . return; . } . 747 ( 0.00%) if self.can_use_global_caches(param_env) { 1,930 ( 0.00%) if let Err(Overflow) = candidate { . // Don't cache overflow globally; we only produce this in certain modes. . } else if !pred.needs_infer() { 2,972 ( 0.00%) if !candidate.needs_infer() { . debug!(?pred, ?candidate, "insert_candidate_cache global"); . // This may overwrite the cache with the same value. 20,061 ( 0.00%) tcx.selection_cache.insert(param_env.and(pred), dep_node, candidate); . return; . } . } . } . . debug!(?pred, ?candidate, "insert_candidate_cache local"); 92 ( 0.00%) self.infcx.selection_cache.insert(param_env.and(pred), dep_node, candidate); . } . . /// Matches a predicate against the bounds of its self type. . /// . /// Given an obligation like `::Bar: Baz` where the self type is . /// a projection, look at the bounds of `T::Bar`, see if we can find a . /// `Baz` bound. We return indexes into the list returned by . /// `tcx.item_bounds` for any applicable bounds. 9 ( 0.00%) fn match_projection_obligation_against_definition_bounds( . &mut self, . obligation: &TraitObligation<'tcx>, . ) -> smallvec::SmallVec<[usize; 2]> { 13 ( 0.00%) let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate); . let placeholder_trait_predicate = 17 ( 0.00%) self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate); . debug!( . ?placeholder_trait_predicate, . "match_projection_obligation_against_definition_bounds" . ); . 1 ( 0.00%) let tcx = self.infcx.tcx; 6 ( 0.00%) let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() { 3 ( 0.00%) ty::Projection(ref data) => (data.item_def_id, data.substs), . ty::Opaque(def_id, substs) => (def_id, substs), . _ => { . span_bug!( . obligation.cause.span, . "match_projection_obligation_against_definition_bounds() called \ . but self-ty is not a projection: {:?}", . placeholder_trait_predicate.trait_ref.self_ty() . ); -- line 1404 ---------------------------------------- -- line 1411 ---------------------------------------- . // unnecessary ambiguity. . let mut distinct_normalized_bounds = FxHashSet::default(); . . let matching_bounds = bounds . .iter() . .enumerate() . .filter_map(|(idx, bound)| { . let bound_predicate = bound.kind(); 6 ( 0.00%) if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() { . let bound = bound_predicate.rebind(pred.trait_ref); 30 ( 0.00%) if self.infcx.probe(|_| { 12 ( 0.00%) match self.match_normalize_trait_ref( . obligation, 8 ( 0.00%) bound, 8 ( 0.00%) placeholder_trait_predicate.trait_ref, . ) { . Ok(None) => true, . Ok(Some(normalized_trait)) . if distinct_normalized_bounds.insert(normalized_trait) => . { . true . } . _ => false, -- line 1433 ---------------------------------------- -- line 1437 ---------------------------------------- . } . } . None . }) . .collect(); . . debug!(?matching_bounds, "match_projection_obligation_against_definition_bounds"); . matching_bounds 9 ( 0.00%) } . . /// Equates the trait in `obligation` with trait bound. If the two traits . /// can be equated and the normalized trait bound doesn't contain inference . /// variables or placeholders, the normalized bound is returned. 26 ( 0.00%) fn match_normalize_trait_ref( . &mut self, . obligation: &TraitObligation<'tcx>, . trait_bound: ty::PolyTraitRef<'tcx>, . placeholder_trait_ref: ty::TraitRef<'tcx>, . ) -> Result>, ()> { . debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars()); 6 ( 0.00%) if placeholder_trait_ref.def_id != trait_bound.def_id() { . // Avoid unnecessary normalization 4 ( 0.00%) return Err(()); . } . . let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| { . project::normalize_with_depth( . self, . obligation.param_env, . obligation.cause.clone(), . obligation.recursion_depth + 1, -- line 1467 ---------------------------------------- -- line 1476 ---------------------------------------- . // inference variables and placeholders escape. . if !trait_bound.needs_infer() && !trait_bound.has_placeholders() { . Some(trait_bound) . } else { . None . } . }) . .map_err(|_| ()) 18 ( 0.00%) } . . fn evaluate_where_clause<'o>( . &mut self, . stack: &TraitObligationStack<'o, 'tcx>, . where_clause_trait_ref: ty::PolyTraitRef<'tcx>, . ) -> Result { . self.evaluation_probe(|this| { 418 ( 0.00%) match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) { 120 ( 0.00%) Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations), . Err(()) => Ok(EvaluatedToErr), . } . }) . } . 180 ( 0.00%) pub(super) fn match_projection_projections( . &mut self, . obligation: &ProjectionTyObligation<'tcx>, . env_predicate: PolyProjectionPredicate<'tcx>, . potentially_unnormalized_candidates: bool, . ) -> bool { . let mut nested_obligations = Vec::new(); 100 ( 0.00%) let (infer_predicate, _) = self.infcx.replace_bound_vars_with_fresh_vars( 60 ( 0.00%) obligation.cause.span, . LateBoundRegionConversionTime::HigherRankedType, . env_predicate, . ); 40 ( 0.00%) let infer_projection = if potentially_unnormalized_candidates { . ensure_sufficient_stack(|| { . project::normalize_with_depth_to( . self, . obligation.param_env, . obligation.cause.clone(), . obligation.recursion_depth + 1, . infer_predicate.projection_ty, . &mut nested_obligations, . ) . }) . } else { 40 ( 0.00%) infer_predicate.projection_ty . }; . 20 ( 0.00%) self.infcx 40 ( 0.00%) .at(&obligation.cause, obligation.param_env) 40 ( 0.00%) .sup(obligation.predicate, infer_projection) 139 ( 0.00%) .map_or(false, |InferOk { obligations, value: () }| { . self.evaluate_predicates_recursively( . TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()), . nested_obligations.into_iter().chain(obligations), . ) 26 ( 0.00%) .map_or(false, |res| res.may_apply()) . }) 180 ( 0.00%) } . . /////////////////////////////////////////////////////////////////////////// . // WINNOW . // . // Winnowing is the process of attempting to resolve ambiguity by . // probing further. During the winnowing process, we unify all . // type variables and then we also attempt to evaluate recursive . // bounds to see if they are satisfied. -- line 1544 ---------------------------------------- -- line 1550 ---------------------------------------- . /// See the comment for "SelectionCandidate" for more details. . fn candidate_should_be_dropped_in_favor_of( . &mut self, . sized_predicate: bool, . victim: &EvaluatedCandidate<'tcx>, . other: &EvaluatedCandidate<'tcx>, . needs_infer: bool, . ) -> bool { 1,388 ( 0.00%) if victim.candidate == other.candidate { . return true; . } . . // Check if a bound would previously have been removed when normalizing . // the param_env so that it can be given the lowest priority. See . // #50825 for the motivation for this. . let is_global = |cand: &ty::PolyTraitPredicate<'tcx>| { . cand.is_global() && !cand.has_late_bound_regions() . }; . . // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`, . // `DiscriminantKindCandidate`, and `ConstDropCandidate` to anything else. . // . // This is a fix for #53123 and prevents winnowing from accidentally extending the . // lifetime of a variable. 24,984 ( 0.00%) match (&other.candidate, &victim.candidate) { . (_, AutoImplCandidate(..)) | (AutoImplCandidate(..), _) => { . bug!( . "default implementations shouldn't be recorded \ . when there are other valid candidates" . ); . } . . // (*) -- line 1582 ---------------------------------------- -- line 1674 ---------------------------------------- . } . (ObjectCandidate(_), ProjectionCandidate(_)) . | (ProjectionCandidate(_), ObjectCandidate(_)) => { . bug!("Have both object and projection candidate") . } . . // Arbitrarily give projection and object candidates priority. . ( 2,776 ( 0.00%) ObjectCandidate(_) | ProjectionCandidate(_), . ImplCandidate(..) . | ClosureCandidate . | GeneratorCandidate . | FnPointerCandidate { .. } . | BuiltinObjectCandidate . | BuiltinUnsizeCandidate . | TraitUpcastingUnsizeCandidate(_) . | BuiltinCandidate { .. } -- line 1690 ---------------------------------------- -- line 1696 ---------------------------------------- . | ClosureCandidate . | GeneratorCandidate . | FnPointerCandidate { .. } . | BuiltinObjectCandidate . | BuiltinUnsizeCandidate . | TraitUpcastingUnsizeCandidate(_) . | BuiltinCandidate { .. } . | TraitAliasCandidate(..), 5,552 ( 0.00%) ObjectCandidate(_) | ProjectionCandidate(_), . ) => false, . 13,880 ( 0.00%) (&ImplCandidate(other_def), &ImplCandidate(victim_def)) => { . // See if we can toss out `victim` based on specialization. . // This requires us to know *for sure* that the `other` impl applies . // i.e., `EvaluatedToOk`. . // . // FIXME(@lcnr): Using `modulo_regions` here seems kind of scary . // to me but is required for `std` to compile, so I didn't change it . // for now. . let tcx = self.tcx(); 5,552 ( 0.00%) if other.evaluation.must_apply_modulo_regions() { 11,104 ( 0.00%) if tcx.specializes((other_def, victim_def)) { . return true; . } . } . 6,940 ( 0.00%) if other.evaluation.must_apply_considering_regions() { 5,552 ( 0.00%) match tcx.impls_are_allowed_to_overlap(other_def, victim_def) { . Some(ty::ImplOverlapKind::Permitted { marker: true }) => { . // Subtle: If the predicate we are evaluating has inference . // variables, do *not* allow discarding candidates due to . // marker trait impls. . // . // Without this restriction, we could end up accidentally . // constrainting inference variables based on an arbitrarily . // chosen trait impl. -- line 1731 ---------------------------------------- -- line 1790 ---------------------------------------- . | BuiltinUnsizeCandidate . | TraitUpcastingUnsizeCandidate(_) . | BuiltinCandidate { has_nested: true } . | TraitAliasCandidate(..), . ) => false, . } . } . 1,540 ( 0.00%) fn sized_conditions( . &mut self, . obligation: &TraitObligation<'tcx>, . ) -> BuiltinImplConditions<'tcx> { . use self::BuiltinImplConditions::{Ambiguous, None, Where}; . . // NOTE: binder moved to (*) 462 ( 0.00%) let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty()); . 778 ( 0.00%) match self_ty.kind() { . ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) . | ty::Uint(_) . | ty::Int(_) . | ty::Bool . | ty::Float(_) . | ty::FnDef(..) . | ty::FnPtr(_) . | ty::RawPtr(..) -- line 1815 ---------------------------------------- -- line 1817 ---------------------------------------- . | ty::Ref(..) . | ty::Generator(..) . | ty::GeneratorWitness(..) . | ty::Array(..) . | ty::Closure(..) . | ty::Never . | ty::Error(_) => { . // safe for everything 62 ( 0.00%) Where(ty::Binder::dummy(Vec::new())) . } . . ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None, . . ty::Tuple(tys) => Where( . obligation . .predicate 74 ( 0.00%) .rebind(tys.last().into_iter().map(|k| k.expect_ty()).collect()), . ), . . ty::Adt(def, substs) => { 92 ( 0.00%) let sized_crit = def.sized_constraint(self.tcx()); . // (*) binder moved here 230 ( 0.00%) Where( . obligation.predicate.rebind({ 46 ( 0.00%) sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect() . }), . ) . } . . ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None, . ty::Infer(ty::TyVar(_)) => Ambiguous, . . ty::Placeholder(..) . | ty::Bound(..) . | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty); . } . } 1,232 ( 0.00%) } . 976 ( 0.00%) fn copy_clone_conditions( . &mut self, . obligation: &TraitObligation<'tcx>, . ) -> BuiltinImplConditions<'tcx> { . // NOTE: binder moved to (*) 244 ( 0.00%) let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty()); . . use self::BuiltinImplConditions::{Ambiguous, None, Where}; . 624 ( 0.00%) match *self_ty.kind() { . ty::Infer(ty::IntVar(_)) . | ty::Infer(ty::FloatVar(_)) . | ty::FnDef(..) . | ty::FnPtr(_) 2 ( 0.00%) | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())), . . ty::Uint(_) . | ty::Int(_) . | ty::Bool . | ty::Float(_) . | ty::Char . | ty::RawPtr(..) . | ty::Never -- line 1879 ---------------------------------------- -- line 1886 ---------------------------------------- . ty::Dynamic(..) . | ty::Str . | ty::Slice(..) . | ty::Generator(..) . | ty::GeneratorWitness(..) . | ty::Foreign(..) . | ty::Ref(_, _, hir::Mutability::Mut) => None, . 4 ( 0.00%) ty::Tuple(tys) => { . // (*) binder moved here 22 ( 0.00%) Where(obligation.predicate.rebind(tys.iter().map(|k| k.expect_ty()).collect())) . } . 16 ( 0.00%) ty::Closure(_, substs) => { . // (*) binder moved here 48 ( 0.00%) let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty()); 32 ( 0.00%) if let ty::Infer(ty::TyVar(_)) = ty.kind() { . // Not yet resolved. . Ambiguous . } else { 112 ( 0.00%) Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect())) . } . } . . ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => { . // Fallback to whatever user-defined impls exist in this case. . None . } . -- line 1914 ---------------------------------------- -- line 1920 ---------------------------------------- . } . . ty::Placeholder(..) . | ty::Bound(..) . | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty); . } . } 732 ( 0.00%) } . . /// For default impls, we need to break apart a type into its . /// "constituent types" -- meaning, the types that it contains. . /// . /// Here are some (simple) examples: . /// . /// ``` . /// (i32, u32) -> [i32, u32] -- line 1936 ---------------------------------------- -- line 1937 ---------------------------------------- . /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32] . /// Bar where struct Bar { x: T, y: u32 } -> [i32, u32] . /// Zed where enum Zed { A(T), B(u32) } -> [i32, u32] . /// ``` . fn constituent_types_for_ty( . &self, . t: ty::Binder<'tcx, Ty<'tcx>>, . ) -> ty::Binder<'tcx, Vec>> { 90 ( 0.00%) match *t.skip_binder().kind() { . ty::Uint(_) . | ty::Int(_) . | ty::Bool . | ty::Float(_) . | ty::FnDef(..) . | ty::FnPtr(_) . | ty::Str . | ty::Error(_) -- line 1953 ---------------------------------------- -- line 1960 ---------------------------------------- . | ty::Param(..) . | ty::Foreign(..) . | ty::Projection(..) . | ty::Bound(..) . | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("asked to assemble constituent types of unexpected type: {:?}", t); . } . 6 ( 0.00%) ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => { . t.rebind(vec![element_ty]) . } . . ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]), . . ty::Tuple(ref tys) => { . // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet 2 ( 0.00%) t.rebind(tys.iter().map(|k| k.expect_ty()).collect()) . } . . ty::Closure(_, ref substs) => { . let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty()); . t.rebind(vec![ty]) . } . . ty::Generator(_, ref substs, _) => { -- line 1984 ---------------------------------------- -- line 1988 ---------------------------------------- . } . . ty::GeneratorWitness(types) => { . debug_assert!(!types.has_escaping_bound_vars()); . types.map_bound(|types| types.to_vec()) . } . . // For `PhantomData`, we pass `T`. 8 ( 0.00%) ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()), . 4 ( 0.00%) ty::Adt(def, substs) => { 20 ( 0.00%) t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect()) . } . . ty::Opaque(def_id, substs) => { . // We can resolve the `impl Trait` to its concrete type, . // which enforces a DAG between the functions requiring . // the auto trait bounds in question. . t.rebind(vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]) . } . } . } . 576 ( 0.00%) fn collect_predicates_for_types( . &mut self, . param_env: ty::ParamEnv<'tcx>, . cause: ObligationCause<'tcx>, . recursion_depth: usize, . trait_def_id: DefId, . types: ty::Binder<'tcx, Vec>>, . ) -> Vec> { . // Because the types were potentially derived from -- line 2019 ---------------------------------------- -- line 2030 ---------------------------------------- . // 2. Produce something like `&'0 i32 : Copy` . // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy` . . types . .as_ref() . .skip_binder() // binder moved -\ . .iter() . .flat_map(|ty| { 153 ( 0.00%) let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(ty); // <----/ . 612 ( 0.00%) self.infcx.commit_unconditionally(|_| { 153 ( 0.00%) let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(ty); 255 ( 0.00%) let Normalized { value: normalized_ty, mut obligations } = 510 ( 0.00%) ensure_sufficient_stack(|| { . project::normalize_with_depth( . self, 51 ( 0.00%) param_env, . cause.clone(), 51 ( 0.00%) recursion_depth, 51 ( 0.00%) placeholder_ty, . ) . }); 561 ( 0.00%) let placeholder_obligation = predicate_for_trait_def( . self.tcx(), 51 ( 0.00%) param_env, . cause.clone(), 102 ( 0.00%) trait_def_id, . recursion_depth, . normalized_ty, . &[], . ); 306 ( 0.00%) obligations.push(placeholder_obligation); . obligations . }) . }) . .collect() 288 ( 0.00%) } . . /////////////////////////////////////////////////////////////////////////// . // Matching . // . // Matching is a common path used for both evaluation and . // confirmation. It basically unifies types that appear in impls . // and traits. This does affect the surrounding environment; . // therefore, when used during evaluation, match routines must be -- line 2074 ---------------------------------------- -- line 2075 ---------------------------------------- . // run inside of a `probe()` so that their side-effects are . // contained. . . fn rematch_impl( . &mut self, . impl_def_id: DefId, . obligation: &TraitObligation<'tcx>, . ) -> Normalized<'tcx, SubstsRef<'tcx>> { 7,475 ( 0.00%) match self.match_impl(impl_def_id, obligation) { 5,980 ( 0.00%) Ok(substs) => substs, . Err(()) => { . bug!( . "Impl {:?} was matchable against {:?} but now is not", . impl_def_id, . obligation . ); . } . } . } . 151,943 ( 0.01%) #[tracing::instrument(level = "debug", skip(self))] . fn match_impl( . &mut self, . impl_def_id: DefId, . obligation: &TraitObligation<'tcx>, . ) -> Result>, ()> { . let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap(); . . // Before we create the substitutions and everything, first . // consider a "quick reject". This avoids creating more types . // and so forth that we need to. . if self.fast_reject_trait_refs(obligation, &impl_trait_ref) { 390 ( 0.00%) return Err(()); . } . . let placeholder_obligation = 54,614 ( 0.00%) self.infcx().replace_bound_vars_with_placeholders(obligation.predicate); 23,406 ( 0.00%) let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref; . 39,010 ( 0.00%) let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id); . 15,604 ( 0.00%) let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs); . . debug!(?impl_trait_ref); . 46,812 ( 0.00%) let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } = 54,614 ( 0.00%) ensure_sufficient_stack(|| { . project::normalize_with_depth( . self, 7,802 ( 0.00%) obligation.param_env, . obligation.cause.clone(), 23,406 ( 0.00%) obligation.recursion_depth + 1, 15,604 ( 0.00%) impl_trait_ref, . ) . }); . . debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref); . . let cause = ObligationCause::new( 7,802 ( 0.00%) obligation.cause.span, 15,604 ( 0.00%) obligation.cause.body_id, 70,218 ( 0.00%) ObligationCauseCode::MatchImpl(obligation.cause.clone(), impl_def_id), . ); . 15,604 ( 0.00%) let InferOk { obligations, .. } = self . .infcx 7,802 ( 0.00%) .at(&cause, obligation.param_env) . .eq(placeholder_obligation_trait_ref, impl_trait_ref) . .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?; . nested_obligations.extend(obligations); . 7,473 ( 0.00%) if !self.intercrate . && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation . { . debug!("match_impl: reservation impls only apply in intercrate mode"); . return Err(()); . } . . debug!(?impl_substs, ?nested_obligations, "match_impl: success"); 14,946 ( 0.00%) Ok(Normalized { value: impl_substs, obligations: nested_obligations }) . } . . fn fast_reject_trait_refs( . &mut self, . obligation: &TraitObligation<'_>, . impl_trait_ref: &ty::TraitRef<'_>, . ) -> bool { . // We can avoid creating type variables and doing the full . // substitution if we find that any of the input types, when . // simplified, do not match. . 23,991 ( 0.00%) iter::zip(obligation.predicate.skip_binder().trait_ref.substs, impl_trait_ref.substs).any( . |(obligation_arg, impl_arg)| { 92,050 ( 0.00%) match (obligation_arg.unpack(), impl_arg.unpack()) { . (GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => { . // Note, we simplify parameters for the obligation but not the . // impl so that we do not reject a blanket impl but do reject . // more concrete impls if we're searching for `T: Trait`. 122,392 ( 0.00%) let simplified_obligation_ty = fast_reject::simplify_type( . self.tcx(), . obligation_ty, . SimplifyParams::Yes, . StripReferences::No, . ); 91,794 ( 0.00%) let simplified_impl_ty = fast_reject::simplify_type( . self.tcx(), . impl_ty, . SimplifyParams::No, . StripReferences::No, . ); . 45,897 ( 0.00%) simplified_obligation_ty.is_some() . && simplified_impl_ty.is_some() . && simplified_obligation_ty != simplified_impl_ty . } . (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => { . // Lifetimes can never cause a rejection. . false . } . (GenericArgKind::Const(_), GenericArgKind::Const(_)) => { -- line 2194 ---------------------------------------- -- line 2201 ---------------------------------------- . } . }, . ) . } . . /// Normalize `where_clause_trait_ref` and try to match it against . /// `obligation`. If successful, return any predicates that . /// result from the normalization. 342 ( 0.00%) fn match_where_clause_trait_ref( . &mut self, . obligation: &TraitObligation<'tcx>, . where_clause_trait_ref: ty::PolyTraitRef<'tcx>, . ) -> Result>, ()> { . self.match_poly_trait_ref(obligation, where_clause_trait_ref) 304 ( 0.00%) } . . /// Returns `Ok` if `poly_trait_ref` being true implies that the . /// obligation is satisfied. . #[instrument(skip(self), level = "debug")] . fn match_poly_trait_ref( . &mut self, . obligation: &TraitObligation<'tcx>, . poly_trait_ref: ty::PolyTraitRef<'tcx>, . ) -> Result>, ()> { 95 ( 0.00%) self.infcx 38 ( 0.00%) .at(&obligation.cause, obligation.param_env) 285 ( 0.00%) .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref) . .map(|InferOk { obligations, .. }| obligations) . .map_err(|_| ()) . } . . /////////////////////////////////////////////////////////////////////////// . // Miscellany . . fn match_fresh_trait_refs( . &self, . previous: ty::PolyTraitPredicate<'tcx>, . current: ty::PolyTraitPredicate<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> bool { 30 ( 0.00%) let mut matcher = ty::_match::Match::new(self.tcx(), param_env); . matcher.relate(previous, current).is_ok() . } . . fn push_stack<'o>( . &mut self, . previous_stack: TraitObligationStackList<'o, 'tcx>, . obligation: &'o TraitObligation<'tcx>, . ) -> TraitObligationStack<'o, 'tcx> { 181,672 ( 0.01%) let fresh_trait_pred = obligation.predicate.fold_with(&mut self.freshener); . . let dfn = previous_stack.cache.next_dfn(); 1,300 ( 0.00%) let depth = previous_stack.depth() + 1; 268,608 ( 0.01%) TraitObligationStack { . obligation, 150,960 ( 0.01%) fresh_trait_pred, . reached_depth: Cell::new(depth), . previous: previous_stack, . dfn, . depth, . } . } . . #[instrument(skip(self), level = "debug")] . fn closure_trait_ref_unnormalized( . &mut self, . obligation: &TraitObligation<'tcx>, . substs: SubstsRef<'tcx>, . ) -> ty::PolyTraitRef<'tcx> { 195 ( 0.00%) let closure_sig = substs.as_closure().sig(); . . debug!(?closure_sig); . . // (1) Feels icky to skip the binder here, but OTOH we know . // that the self-type is an unboxed closure type and hence is . // in fact unparameterized (or at least does not reference any . // regions bound in the obligation). Still probably some . // refactoring could make this nicer. 650 ( 0.00%) closure_trait_ref_and_return_type( . self.tcx(), 390 ( 0.00%) obligation.predicate.def_id(), 65 ( 0.00%) obligation.predicate.skip_binder().self_ty(), // (1) 260 ( 0.00%) closure_sig, . util::TupleArgumentsFlag::No, . ) . .map_bound(|(trait_ref, _)| trait_ref) . } . . fn generator_trait_ref_unnormalized( . &mut self, . obligation: &TraitObligation<'tcx>, -- line 2291 ---------------------------------------- -- line 2307 ---------------------------------------- . ) . .map_bound(|(trait_ref, ..)| trait_ref) . } . . /// Returns the obligations that are implied by instantiating an . /// impl or trait. The obligations are substituted and fully . /// normalized. This is used when confirming an impl or default . /// impl. 34,799 ( 0.00%) #[tracing::instrument(level = "debug", skip(self, cause, param_env))] . fn impl_or_trait_obligations( . &mut self, . cause: ObligationCause<'tcx>, . recursion_depth: usize, . param_env: ty::ParamEnv<'tcx>, . def_id: DefId, // of impl or trait . substs: SubstsRef<'tcx>, // for impl or trait . ) -> Vec> { -- line 2323 ---------------------------------------- -- line 2334 ---------------------------------------- . // V: Iterator, V: Sized, . // ::Item: Copy . // When we substitute, say, `V => IntoIter, U => $0`, the last . // obligation will normalize to `<$0 as Iterator>::Item = $1` and . // `$1: Copy`, so we must ensure the obligations are emitted in . // that order. . let predicates = tcx.predicates_of(def_id); . debug!(?predicates); 1,513 ( 0.00%) assert_eq!(predicates.parent, None); 4,539 ( 0.00%) let mut obligations = Vec::with_capacity(predicates.predicates.len()); . for (predicate, _) in predicates.predicates { . debug!(?predicate); 4,205 ( 0.00%) let predicate = normalize_with_depth_to( . self, . param_env, . cause.clone(), . recursion_depth, 841 ( 0.00%) predicate.subst(tcx, substs), . &mut obligations, . ); 8,410 ( 0.00%) obligations.push(Obligation { . cause: cause.clone(), . recursion_depth, . param_env, . predicate, . }); . } . . // We are performing deduplication here to avoid exponential blowups -- line 2362 ---------------------------------------- -- line 2363 ---------------------------------------- . // (#38528) from happening, but the real cause of the duplication is . // unknown. What we know is that the deduplication avoids exponential . // amount of predicates being propagated when processing deeply nested . // types. . // . // This code is hot enough that it's worth avoiding the allocation . // required for the FxHashSet when possible. Special-casing lengths 0, . // 1 and 2 covers roughly 75-80% of the cases. 1,254 ( 0.00%) if obligations.len() <= 1 { . // No possibility of duplicates. 273 ( 0.00%) } else if obligations.len() == 2 { . // Only two elements. Drop the second if they are equal. . if obligations[0] == obligations[1] { . obligations.truncate(1); . } . } else { . // Three or more elements. Use a general deduplication process. . let mut seen = FxHashSet::default(); 85 ( 0.00%) obligations.retain(|i| seen.insert(i.clone())); . } . 6,052 ( 0.00%) obligations . } . } . . trait TraitObligationExt<'tcx> { . fn derived_cause( . &self, . variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>, . ) -> ObligationCause<'tcx>; -- line 2392 ---------------------------------------- -- line 2408 ---------------------------------------- . */ . . let obligation = self; . . // NOTE(flaper87): As of now, it keeps track of the whole error . // chain. Ideally, we should have a way to configure this either . // by using -Z verbose or just a CLI argument. . let derived_cause = DerivedObligationCause { 6,244 ( 0.00%) parent_trait_pred: obligation.predicate, 3,092 ( 0.00%) parent_code: obligation.cause.clone_code(), . }; . let derived_code = variant(derived_cause); 18,666 ( 0.00%) ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code) . } . } . . impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> { . fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> { . TraitObligationStackList::with(self) . } . . fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> { 2,242 ( 0.00%) self.previous.cache . } . . fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> { . self.list() . } . . /// Indicates that attempting to evaluate this stack entry . /// required accessing something from the stack at depth `reached_depth`. 36 ( 0.00%) fn update_reached_depth(&self, reached_depth: usize) { 18 ( 0.00%) assert!( 18 ( 0.00%) self.depth >= reached_depth, . "invoked `update_reached_depth` with something under this stack: \ . self.depth={} reached_depth={}", . self.depth, . reached_depth, . ); . debug!(reached_depth, "update_reached_depth"); . let mut p = self; 54 ( 0.00%) while reached_depth < p.depth { . debug!(?p.fresh_trait_pred, "update_reached_depth: marking as cycle participant"); 18 ( 0.00%) p.reached_depth.set(p.reached_depth.get().min(reached_depth)); 18 ( 0.00%) p = p.previous.head.unwrap(); . } 36 ( 0.00%) } . } . . /// The "provisional evaluation cache" is used to store intermediate cache results . /// when solving auto traits. Auto traits are unusual in that they can support . /// cycles. So, for example, a "proof tree" like this would be ok: . /// . /// - `Foo: Send` :- . /// - `Bar: Send` :- -- line 2462 ---------------------------------------- -- line 2540 ---------------------------------------- . /// evaluation. When we create an entry in the evaluation cache using this provisional . /// cache entry (see `on_completion`), we use this `dep_node` to ensure that future reads from . /// the cache will have all of the necessary incr comp dependencies tracked. . dep_node: DepNodeIndex, . } . . impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> { . fn default() -> Self { 31,232 ( 0.00%) Self { dfn: Cell::new(0), map: Default::default() } . } . } . . impl<'tcx> ProvisionalEvaluationCache<'tcx> { . /// Get the next DFN in sequence (basically a counter). . fn next_dfn(&self) -> usize { 650 ( 0.00%) let result = self.dfn.get(); 2,600 ( 0.00%) self.dfn.set(result + 1); . result . } . . /// Check the provisional cache for any result for . /// `fresh_trait_ref`. If there is a hit, then you must consider . /// it an access to the stack slots at depth . /// `reached_depth` (from the returned value). . fn get_provisional( -- line 2564 ---------------------------------------- -- line 2663 ---------------------------------------- . fn on_completion( . &self, . dfn: usize, . mut op: impl FnMut(ty::PolyTraitPredicate<'tcx>, EvaluationResult, DepNodeIndex), . ) { . debug!(?dfn, "on_completion"); . . for (fresh_trait_pred, eval) in 3,255 ( 0.00%) self.map.borrow_mut().drain_filter(|_k, eval| eval.from_dfn >= dfn) . { . debug!(?fresh_trait_pred, ?eval, "on_completion"); . . op(fresh_trait_pred, eval.result, eval.dep_node); . } . } . } . -- line 2679 ---------------------------------------- -- line 2692 ---------------------------------------- . TraitObligationStackList { cache: r.cache(), head: Some(r) } . } . . fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> { . self.head . } . . fn depth(&self) -> usize { 1,534 ( 0.00%) if let Some(head) = self.head { head.depth } else { 0 } . } . } . . impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> { . type Item = &'o TraitObligationStack<'o, 'tcx>; . . fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> { 1,949 ( 0.00%) let o = self.head?; 388 ( 0.00%) *self = o.previous; . Some(o) . } . } . . impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(f, "TraitObligationStack({:?})", self.obligation) . } -- line 2717 ---------------------------------------- 121,229 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_borrowck/src/type_check/mod.rs -------------------------------------------------------------------------------- Ir -- line 118 ---------------------------------------- . /// - `promoted` -- map of promoted constants within `body` . /// - `universal_regions` -- the universal regions from `body`s function signature . /// - `location_table` -- MIR location map of `body` . /// - `borrow_set` -- information about borrows occurring in `body` . /// - `all_facts` -- when using Polonius, this is the generated set of Polonius facts . /// - `flow_inits` -- results of a maybe-init dataflow analysis . /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis . /// - `elements` -- MIR region map 792 ( 0.00%) pub(crate) fn type_check<'mir, 'tcx>( . infcx: &InferCtxt<'_, 'tcx>, . param_env: ty::ParamEnv<'tcx>, . body: &Body<'tcx>, . promoted: &IndexVec>, . universal_regions: &Rc>, . location_table: &LocationTable, . borrow_set: &BorrowSet<'tcx>, . all_facts: &mut Option, . flow_inits: &mut ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'mir, 'tcx>>, . move_data: &MoveData<'tcx>, . elements: &Rc, . upvars: &[Upvar<'tcx>], . ) -> MirTypeckResults<'tcx> { 594 ( 0.00%) let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body)); . let mut universe_causes = FxHashMap::default(); . universe_causes.insert(ty::UniverseIndex::from_u32(0), UniverseInfo::other()); 1,452 ( 0.00%) let mut constraints = MirTypeckRegionConstraints { . placeholder_indices: PlaceholderIndices::default(), . placeholder_index_to_region: IndexVec::default(), 66 ( 0.00%) liveness_constraints: LivenessValues::new(elements.clone()), . outlives_constraints: OutlivesConstraintSet::default(), . member_constraints: MemberConstraintSet::default(), . closure_bounds_mapping: Default::default(), . type_tests: Vec::default(), 264 ( 0.00%) universe_causes, . }; . . let CreateResult { 132 ( 0.00%) universal_region_relations, 264 ( 0.00%) region_bound_pairs, 264 ( 0.00%) normalized_inputs_and_output, 330 ( 0.00%) } = free_region_relations::create( . infcx, . param_env, . Some(implicit_region_bound), . universal_regions, . &mut constraints, . ); . 132 ( 0.00%) for u in ty::UniverseIndex::ROOT..infcx.universe() { . let info = UniverseInfo::other(); . constraints.universe_causes.insert(u, info); . } . 594 ( 0.00%) let mut borrowck_context = BorrowCheckContext { 66 ( 0.00%) universal_regions, . location_table, . borrow_set, . all_facts, . constraints: &mut constraints, . upvars, . }; . . let opaque_type_values = type_check_internal( -- line 180 ---------------------------------------- -- line 243 ---------------------------------------- . } else { . Some((opaque_type_key, decl)) . } . }) . .collect() . }, . ); . 792 ( 0.00%) MirTypeckResults { constraints, universal_region_relations, opaque_type_values } 528 ( 0.00%) } . . #[instrument( . skip(infcx, body, promoted, region_bound_pairs, borrowck_context, extra), . level = "debug" . )] . fn type_check_internal<'a, 'tcx, R>( . infcx: &'a InferCtxt<'a, 'tcx>, . param_env: ty::ParamEnv<'tcx>, -- line 260 ---------------------------------------- -- line 270 ---------------------------------------- . body, . param_env, . region_bound_pairs, . implicit_region_bound, . borrowck_context, . ); . let errors_reported = { . let mut verifier = TypeVerifier::new(&mut checker, body, promoted); 66 ( 0.00%) verifier.visit_body(&body); 66 ( 0.00%) verifier.errors_reported . }; . 66 ( 0.00%) if !errors_reported { . // if verifier failed, don't do further checks to avoid ICEs 66 ( 0.00%) checker.typeck_mir(body); . } . 858 ( 0.00%) extra(checker) . } . . fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) { . let cx = &mut typeck.borrowck_context; 264 ( 0.00%) if let Some(facts) = cx.all_facts { . let _prof_timer = typeck.infcx.tcx.prof.generic_activity("polonius_fact_generation"); . let location_table = cx.location_table; . facts.subset_base.extend(cx.constraints.outlives_constraints.outlives().iter().flat_map( . |constraint: &OutlivesConstraint<'_>| { . if let Some(from_location) = constraint.locations.from_location() { . Either::Left(iter::once(( . constraint.sup, . constraint.sub, -- line 300 ---------------------------------------- -- line 334 ---------------------------------------- . body: &'b Body<'tcx>, . promoted: &'b IndexVec>, . last_span: Span, . errors_reported: bool, . } . . impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> { . fn visit_span(&mut self, span: &Span) { 306,814 ( 0.01%) if !span.is_dummy() { 76,637 ( 0.00%) self.last_span = *span; . } . } . 390,588 ( 0.02%) fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) { . self.sanitize_place(place, location, context); 284,064 ( 0.01%) } . 263,340 ( 0.01%) fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) { . self.super_constant(constant, location); 175,560 ( 0.01%) let ty = self.sanitize_type(constant, constant.literal.ty()); . 197,505 ( 0.01%) self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| { . let live_region_vid = . self.cx.borrowck_context.universal_regions.to_region_vid(live_region); 372 ( 0.00%) self.cx . .borrowck_context . .constraints . .liveness_constraints 372 ( 0.00%) .add_element(live_region_vid, location); . }); . 87,780 ( 0.00%) if let Some(annotation_index) = constant.user_ty { 171 ( 0.00%) if let Err(terr) = self.cx.relate_type_and_user_type( 38 ( 0.00%) constant.literal.ty(), . ty::Variance::Invariant, 38 ( 0.00%) &UserTypeProjection { base: annotation_index, projs: vec![] }, 38 ( 0.00%) location.to_locations(), . ConstraintCategory::Boring, . ) { . let annotation = &self.cx.user_type_annotations[annotation_index]; . span_mirbug!( . self, . constant, . "bad constant user type {:?} vs {:?}: {:?}", . annotation, . constant.literal.ty(), . terr, . ); . } . } else { . let tcx = self.tcx(); 65,778 ( 0.00%) let maybe_uneval = match constant.literal { 65,778 ( 0.00%) ConstantKind::Ty(ct) => match ct.val { 35 ( 0.00%) ty::ConstKind::Unevaluated(uv) => Some(uv), . _ => None, . }, . _ => None, . }; 70 ( 0.00%) if let Some(uv) = maybe_uneval { 70 ( 0.00%) if let Some(promoted) = uv.promoted { . let check_err = |verifier: &mut TypeVerifier<'a, 'b, 'tcx>, . promoted: &Body<'tcx>, . ty, . san_ty| { 27 ( 0.00%) if let Err(terr) = verifier.cx.eq_types( . ty, . san_ty, 18 ( 0.00%) location.to_locations(), . ConstraintCategory::Boring, . ) { . span_mirbug!( . verifier, . promoted, . "bad promoted type ({:?}: {:?}): {:?}", . ty, . san_ty, . terr . ); . }; . }; . 18 ( 0.00%) if !self.errors_reported { 9 ( 0.00%) let promoted_body = &self.promoted[promoted]; 36 ( 0.00%) self.sanitize_promoted(promoted_body, location); . . let promoted_ty = promoted_body.return_ty(); . check_err(self, promoted_body, ty, promoted_ty); . } . } else { 182 ( 0.00%) if let Err(terr) = self.cx.fully_perform_op( 52 ( 0.00%) location.to_locations(), . ConstraintCategory::Boring, 182 ( 0.00%) self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new( 52 ( 0.00%) constant.literal.ty(), . uv.def.did, 104 ( 0.00%) UserSubsts { substs: uv.substs, user_self_ty: None }, . )), . ) { . span_mirbug!( . self, . constant, . "bad constant type {:?} ({:?})", . constant, . terr . ); . } . } 87,564 ( 0.00%) } else if let Some(static_def_id) = constant.check_static_ptr(tcx) { . let unnormalized_ty = tcx.type_of(static_def_id); 68 ( 0.00%) let locations = location.to_locations(); 238 ( 0.00%) let normalized_ty = self.cx.normalize(unnormalized_ty, locations); 170 ( 0.00%) let literal_ty = constant.literal.ty().builtin_deref(true).unwrap().ty; . 102 ( 0.00%) if let Err(terr) = self.cx.eq_types( . literal_ty, . normalized_ty, . locations, . ConstraintCategory::Boring, . ) { . span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr); . } . } . 88,418 ( 0.00%) if let ty::FnDef(def_id, substs) = *constant.literal.ty().kind() { 476 ( 0.00%) let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs); 476 ( 0.00%) self.cx.normalize_and_prove_instantiated_predicates( . def_id, 1,428 ( 0.00%) instantiated_predicates, 476 ( 0.00%) location.to_locations(), . ); . } . } 175,560 ( 0.01%) } . 188,782 ( 0.01%) fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) { . self.super_rvalue(rvalue, location); 51,486 ( 0.00%) let rval_ty = rvalue.ty(self.body, self.tcx()); 205,944 ( 0.01%) self.sanitize_type(rvalue, rval_ty); . } . 331,510 ( 0.01%) fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) { . self.super_local_decl(local, local_decl); 165,755 ( 0.01%) self.sanitize_type(local_decl, local_decl.ty); . 99,453 ( 0.00%) if let Some(user_ty) = &local_decl.user_ty { . for (user_ty, span) in user_ty.projections_and_spans() { . let ty = if !local_decl.is_nonref_binding() { . // If we have a binding of the form `let ref x: T = ..` . // then remove the outermost reference so we can check the . // type annotation for the remaining type. . if let ty::Ref(_, rty, _) = local_decl.ty.kind() { . rty . } else { -- line 486 ---------------------------------------- -- line 504 ---------------------------------------- . local, . local_decl.ty, . local_decl.user_ty, . terr, . ); . } . } . } 265,208 ( 0.01%) } . 525 ( 0.00%) fn visit_body(&mut self, body: &Body<'tcx>) { 225 ( 0.00%) self.sanitize_type(&"return type", body.return_ty()); . for local_decl in &body.local_decls { 165,755 ( 0.01%) self.sanitize_type(local_decl, local_decl.ty); . } 150 ( 0.00%) if self.errors_reported { . return; . } . self.super_body(body); 600 ( 0.00%) } . } . . impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> { . fn new( . cx: &'a mut TypeChecker<'b, 'tcx>, . body: &'b Body<'tcx>, . promoted: &'b IndexVec>, . ) -> Self { 594 ( 0.00%) TypeVerifier { body, promoted, cx, last_span: body.span, errors_reported: false } . } . . fn tcx(&self) -> TyCtxt<'tcx> { 122,908 ( 0.00%) self.cx.infcx.tcx . } . 1,058,150 ( 0.04%) fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> { 211,630 ( 0.01%) if ty.has_escaping_bound_vars() || ty.references_error() { . span_mirbug_and_err!(self, parent, "bad type {:?}", ty) . } else { . ty . } 740,705 ( 0.03%) } . . /// Checks that the types internal to the `place` match up with . /// what would be expected. . fn sanitize_place( . &mut self, . place: &Place<'tcx>, . location: Location, . context: PlaceContext, . ) -> PlaceTy<'tcx> { . debug!("sanitize_place: {:?}", place); . 142,032 ( 0.01%) let mut place_ty = PlaceTy::from_ty(self.body.local_decls[place.local].ty); . 37,052 ( 0.00%) for elem in place.projection.iter() { 772 ( 0.00%) if place_ty.variant_index.is_none() { 722 ( 0.00%) if place_ty.ty.references_error() { . assert!(self.errors_reported); . return PlaceTy::from_ty(self.tcx().ty_error()); . } . } . place_ty = self.sanitize_projection(place_ty, elem, place, location); . } . 106,370 ( 0.00%) if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context { . let tcx = self.tcx(); . let trait_ref = ty::TraitRef { 5,210 ( 0.00%) def_id: tcx.require_lang_item(LangItem::Copy, Some(self.last_span)), 2,605 ( 0.00%) substs: tcx.mk_substs_trait(place_ty.ty, &[]), . }; . . // To have a `Copy` operand, the type `T` of the . // value must be `Copy`. Note that we prove that `T: Copy`, . // rather than using the `is_copy_modulo_regions` . // test. This is important because . // `is_copy_modulo_regions` ignores the resulting region . // obligations and assumes they pass. This can result in . // bounds from `Copy` impls being unsoundly ignored (e.g., . // #29149). Note that we decide to use `Copy` before knowing . // whether the bounds fully apply: in effect, the rule is . // that if a value of some type could implement `Copy`, then . // it must. 1,563 ( 0.00%) self.cx.prove_trait_ref( . trait_ref, . location.to_locations(), . ConstraintCategory::CopyBound, . ); . } . . place_ty . } -- line 595 ---------------------------------------- -- line 598 ---------------------------------------- . // Determine the constraints from the promoted MIR by running the type . // checker on the promoted MIR, then transfer the constraints back to . // the main MIR, changing the locations to the provided location. . . let parent_body = mem::replace(&mut self.body, promoted_body); . . // Use new sets of constraints and closure bounds so that we can . // modify their locations. 9 ( 0.00%) let all_facts = &mut None; . let mut constraints = Default::default(); . let mut closure_bounds = Default::default(); . let mut liveness_constraints = 18 ( 0.00%) LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body))); . // Don't try to add borrow_region facts for the promoted MIR . . let mut swap_constraints = |this: &mut Self| { 36 ( 0.00%) mem::swap(this.cx.borrowck_context.all_facts, all_facts); . mem::swap( 36 ( 0.00%) &mut this.cx.borrowck_context.constraints.outlives_constraints, . &mut constraints, . ); . mem::swap( 36 ( 0.00%) &mut this.cx.borrowck_context.constraints.closure_bounds_mapping, . &mut closure_bounds, . ); . mem::swap( 36 ( 0.00%) &mut this.cx.borrowck_context.constraints.liveness_constraints, . &mut liveness_constraints, . ); . }; . 9 ( 0.00%) swap_constraints(self); . 27 ( 0.00%) self.visit_body(&promoted_body); . 18 ( 0.00%) if !self.errors_reported { . // if verifier failed, don't do further checks to avoid ICEs 27 ( 0.00%) self.cx.typeck_mir(promoted_body); . } . 9 ( 0.00%) self.body = parent_body; . // Merge the outlives constraints back in, at the given location. 9 ( 0.00%) swap_constraints(self); . . let locations = location.to_locations(); . for constraint in constraints.outlives().iter() { . let mut constraint = constraint.clone(); . constraint.locations = locations; 72 ( 0.00%) if let ConstraintCategory::Return(_) . | ConstraintCategory::UseAsConst . | ConstraintCategory::UseAsStatic = constraint.category . { . // "Returning" from a promoted is an assignment to a . // temporary from the user's point of view. . constraint.category = ConstraintCategory::Boring; . } . self.cx.borrowck_context.constraints.outlives_constraints.push(constraint) -- line 654 ---------------------------------------- -- line 661 ---------------------------------------- . self.cx . .borrowck_context . .constraints . .liveness_constraints . .add_element(region, location); . } . } . 9 ( 0.00%) if !closure_bounds.is_empty() { . let combined_bounds_mapping = . closure_bounds.into_iter().flat_map(|(_, value)| value).collect(); . let existing = self . .cx . .borrowck_context . .constraints . .closure_bounds_mapping . .insert(location, combined_bounds_mapping); . assert!(existing.is_none(), "Multiple promoteds/closures at the same location."); . } 36 ( 0.00%) } . . fn sanitize_projection( . &mut self, . base: PlaceTy<'tcx>, . pi: PlaceElem<'tcx>, . place: &Place<'tcx>, . location: Location, . ) -> PlaceTy<'tcx> { . debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place); . let tcx = self.tcx(); 772 ( 0.00%) let base_ty = base.ty; 3,860 ( 0.00%) match pi { . ProjectionElem::Deref => { 1,158 ( 0.00%) let deref_ty = base_ty.builtin_deref(true); . PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| { . span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty) . })) . } 5 ( 0.00%) ProjectionElem::Index(i) => { 20 ( 0.00%) let index_ty = Place::from(i).ty(self.body, tcx).ty; 5 ( 0.00%) if index_ty != tcx.types.usize { . PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i)) . } else { 5 ( 0.00%) PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| { . span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty) . })) . } . } . ProjectionElem::ConstantIndex { .. } => { . // consider verifying in-bounds . PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| { . span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty) -- line 712 ---------------------------------------- -- line 720 ---------------------------------------- . } . ty::Slice(..) => { . assert!(from_end, "slice subslices should use from_end"); . base_ty . } . _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty), . }) . } 150 ( 0.00%) ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind() { 150 ( 0.00%) ty::Adt(adt_def, _substs) if adt_def.is_enum() => { 150 ( 0.00%) if index.as_usize() >= adt_def.variants.len() { . PlaceTy::from_ty(span_mirbug_and_err!( . self, . place, . "cast to variant #{:?} but enum only has {:?}", . index, . adt_def.variants.len() . )) . } else { -- line 738 ---------------------------------------- -- line 752 ---------------------------------------- . ) . } else { . span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty) . }; . PlaceTy::from_ty(ty) . } . }, . ProjectionElem::Field(field, fty) => { 1,655 ( 0.00%) let fty = self.sanitize_type(place, fty); 4,634 ( 0.00%) let fty = self.cx.normalize(fty, location); . match self.field_ty(place, base, field, location) { . Ok(ty) => { 2,648 ( 0.00%) let ty = self.cx.normalize(ty, location); 662 ( 0.00%) if let Err(terr) = self.cx.eq_types( . ty, . fty, . location.to_locations(), . ConstraintCategory::Boring, . ) { . span_mirbug!( . self, . place, -- line 773 ---------------------------------------- -- line 800 ---------------------------------------- . &mut self, . parent: &dyn fmt::Debug, . base_ty: PlaceTy<'tcx>, . field: Field, . location: Location, . ) -> Result, FieldAccessError> { . let tcx = self.tcx(); . 331 ( 0.00%) let (variant, substs) = match base_ty { 200 ( 0.00%) PlaceTy { ty, variant_index: Some(variant_index) } => match *ty.kind() { 100 ( 0.00%) ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs), . ty::Generator(def_id, substs, _) => { . let mut variants = substs.as_generator().state_tys(def_id, tcx); . let mut variant = match variants.nth(variant_index.into()) { . Some(v) => v, . None => bug!( . "variant_index of generator out of range: {:?}/{:?}", . variant_index, . substs.as_generator().state_tys(def_id, tcx).count() -- line 818 ---------------------------------------- -- line 820 ---------------------------------------- . }; . return match variant.nth(field.index()) { . Some(ty) => Ok(ty), . None => Err(FieldAccessError::OutOfRange { field_count: variant.count() }), . }; . } . _ => bug!("can't have downcast of non-adt non-generator type"), . }, 1,124 ( 0.00%) PlaceTy { ty, variant_index: None } => match *ty.kind() { 408 ( 0.00%) ty::Adt(adt_def, substs) if !adt_def.is_enum() => { . (&adt_def.variants[VariantIdx::new(0)], substs) . } 11 ( 0.00%) ty::Closure(_, substs) => { 99 ( 0.00%) return match substs . .as_closure() . .tupled_upvars_ty() . .tuple_element_ty(field.index()) . { . Some(ty) => Ok(ty), . None => Err(FieldAccessError::OutOfRange { . field_count: substs.as_closure().upvar_tys().count(), . }), -- line 841 ---------------------------------------- -- line 846 ---------------------------------------- . // accessible without a variant index. . return match substs.as_generator().prefix_tys().nth(field.index()) { . Some(ty) => Ok(ty), . None => Err(FieldAccessError::OutOfRange { . field_count: substs.as_generator().prefix_tys().count(), . }), . }; . } 168 ( 0.00%) ty::Tuple(tys) => { 168 ( 0.00%) return match tys.get(field.index()) { 672 ( 0.00%) Some(&ty) => Ok(ty.expect_ty()), . None => Err(FieldAccessError::OutOfRange { field_count: tys.len() }), . }; . } . _ => { . return Ok(span_mirbug_and_err!( . self, . parent, . "can't project out of {:?}", . base_ty . )); . } . }, . }; . 152 ( 0.00%) if let Some(field) = variant.fields.get(field.index()) { 1,520 ( 0.00%) Ok(self.cx.normalize(field.ty(tcx, substs), location)) . } else { . Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() }) . } . } . } . . /// The MIR type checker. Visits the MIR and enforces all the . /// constraints needed for it to be valid and well-typed. Along the -- line 880 ---------------------------------------- -- line 943 ---------------------------------------- . FxHashMap>, . . crate universe_causes: FxHashMap>, . . crate type_tests: Vec>, . } . . impl<'tcx> MirTypeckRegionConstraints<'tcx> { 300 ( 0.00%) fn placeholder_region( . &mut self, . infcx: &InferCtxt<'_, 'tcx>, . placeholder: ty::PlaceholderRegion, . ) -> ty::Region<'tcx> { . let placeholder_index = self.placeholder_indices.insert(placeholder); 60 ( 0.00%) match self.placeholder_index_to_region.get(placeholder_index) { 40 ( 0.00%) Some(&v) => v, . None => { 40 ( 0.00%) let origin = NllRegionVariableOrigin::Placeholder(placeholder); 90 ( 0.00%) let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe); . self.placeholder_index_to_region.push(region); . region . } . } 240 ( 0.00%) } . } . . /// The `Locations` type summarizes *where* region constraints are . /// required to hold. Normally, this is at a particular point which . /// created the obligation, but for constraints that the user gave, we . /// want the constraint to hold at all points. 3,146 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] . pub enum Locations { . /// Indicates that a type constraint should always be true. This . /// is particularly important in the new borrowck analysis for . /// things like the type of the return slot. Consider this . /// example: . /// . /// ``` . /// fn foo<'a>(x: &'a u32) -> &'a u32 { -- line 981 ---------------------------------------- -- line 1036 ---------------------------------------- . fn new( . infcx: &'a InferCtxt<'a, 'tcx>, . body: &'a Body<'tcx>, . param_env: ty::ParamEnv<'tcx>, . region_bound_pairs: &'a RegionBoundPairs<'tcx>, . implicit_region_bound: ty::Region<'tcx>, . borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>, . ) -> Self { 858 ( 0.00%) let mut checker = Self { . infcx, . last_span: DUMMY_SP, . body, 66 ( 0.00%) user_type_annotations: &body.user_type_annotations, . param_env, . region_bound_pairs, . implicit_region_bound, . borrowck_context, . reported_errors: Default::default(), . }; . checker.check_user_type_annotations(); . checker . } . . fn unsized_feature_enabled(&self) -> bool { 50,409 ( 0.00%) let features = self.tcx().features(); 100,818 ( 0.00%) features.unsized_locals || features.unsized_fn_params . } . . /// Equate the inferred type and the annotated type for user type annotations . fn check_user_type_annotations(&mut self) { . debug!( . "check_user_type_annotations: user_type_annotations={:?}", . self.user_type_annotations . ); 29 ( 0.00%) for user_annotation in self.user_type_annotations { 58 ( 0.00%) let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation; 174 ( 0.00%) let inferred_ty = self.normalize(inferred_ty, Locations::All(span)); 58 ( 0.00%) let annotation = self.instantiate_canonical_with_fresh_inference_vars(span, user_ty); 58 ( 0.00%) match annotation { 20 ( 0.00%) UserType::Ty(mut ty) => { 60 ( 0.00%) ty = self.normalize(ty, Locations::All(span)); . 20 ( 0.00%) if let Err(terr) = self.eq_types( . ty, 10 ( 0.00%) inferred_ty, . Locations::All(span), . ConstraintCategory::BoringNoLocation, . ) { . span_mirbug!( . self, . user_annotation, . "bad user type ({:?} = {:?}): {:?}", . ty, . inferred_ty, . terr . ); . } . 70 ( 0.00%) self.prove_predicate( 30 ( 0.00%) ty::Binder::dummy(ty::PredicateKind::WellFormed(inferred_ty.into())) . .to_predicate(self.tcx()), 20 ( 0.00%) Locations::All(span), . ConstraintCategory::TypeAnnotation, . ); . } 152 ( 0.00%) UserType::TypeOf(def_id, user_substs) => { 171 ( 0.00%) if let Err(terr) = self.fully_perform_op( 38 ( 0.00%) Locations::All(span), . ConstraintCategory::BoringNoLocation, 95 ( 0.00%) self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new( 19 ( 0.00%) inferred_ty, . def_id, 38 ( 0.00%) user_substs, . )), . ) { . span_mirbug!( . self, . user_annotation, . "bad user type AscribeUserType({:?}, {:?} {:?}, type_of={:?}): {:?}", . inferred_ty, . def_id, -- line 1116 ---------------------------------------- -- line 1128 ---------------------------------------- . fn push_region_constraints( . &mut self, . locations: Locations, . category: ConstraintCategory, . data: &QueryRegionConstraints<'tcx>, . ) { . debug!("constraints generated: {:#?}", data); . 314 ( 0.00%) constraint_conversion::ConstraintConversion::new( . self.infcx, 624 ( 0.00%) self.borrowck_context.universal_regions, 312 ( 0.00%) self.region_bound_pairs, . Some(self.implicit_region_bound), 25 ( 0.00%) self.param_env, . locations, . category, 312 ( 0.00%) &mut self.borrowck_context.constraints, . ) . .convert_all(data); . } . . /// Try to relate `sub <: sup` . fn sub_types( . &mut self, . sub: Ty<'tcx>, . sup: Ty<'tcx>, . locations: Locations, . category: ConstraintCategory, . ) -> Fallible<()> { . // Use this order of parameters because the sup type is usually the . // "expected" type in diagnostics. 565,214 ( 0.02%) self.relate_types(sup, ty::Variance::Contravariant, sub, locations, category) . } . . #[instrument(skip(self, category), level = "debug")] . fn eq_types( . &mut self, . expected: Ty<'tcx>, . found: Ty<'tcx>, . locations: Locations, . category: ConstraintCategory, . ) -> Fallible<()> { 6,227 ( 0.00%) self.relate_types(expected, ty::Variance::Invariant, found, locations, category) . } . 323 ( 0.00%) #[instrument(skip(self), level = "debug")] . fn relate_type_and_user_type( . &mut self, . a: Ty<'tcx>, . v: ty::Variance, . user_ty: &UserTypeProjection, . locations: Locations, . category: ConstraintCategory, . ) -> Fallible<()> { 76 ( 0.00%) let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty; . let mut curr_projected_ty = PlaceTy::from_ty(annotated_type); . 57 ( 0.00%) let tcx = self.infcx.tcx; . . for proj in &user_ty.projs { . let projected_ty = curr_projected_ty.projection_ty_core( . tcx, . self.param_env, . proj, . |this, field, &()| { . let ty = this.field_ty(tcx, field); -- line 1193 ---------------------------------------- -- line 1197 ---------------------------------------- . curr_projected_ty = projected_ty; . } . debug!( . "user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}", . user_ty.base, annotated_type, user_ty.projs, curr_projected_ty . ); . . let ty = curr_projected_ty.ty; 304 ( 0.00%) self.relate_types(ty, v.xform(ty::Variance::Contravariant), a, locations, category)?; . . Ok(()) . } . . /// Equates a type `anon_ty` that may contain opaque types whose . /// values are to be inferred by the MIR. . /// . /// The type `revealed_ty` contains the same type as `anon_ty`, but with the -- line 1213 ---------------------------------------- -- line 1231 ---------------------------------------- . /// . /// In terms of our function parameters: . /// . /// * `anon_ty` would be `Box>` where `Foo` is an opaque type . /// scoped to this function (note that it is parameterized by the . /// generics of `foo`). Note that `anon_ty` is not just the opaque type, . /// but the entire return type (which may contain opaque types within it). . /// * `revealed_ty` would be `Box<(T, u32)>` 1,463 ( 0.00%) #[instrument(skip(self), level = "debug")] . fn eq_opaque_type_and_type( . &mut self, . revealed_ty: Ty<'tcx>, . anon_ty: Ty<'tcx>, . locations: Locations, . category: ConstraintCategory, . ) -> Fallible<()> { . // Fast path for the common case. 77 ( 0.00%) if !anon_ty.has_opaque_types() { 154 ( 0.00%) if let Err(terr) = self.eq_types(anon_ty, revealed_ty, locations, category) { . span_mirbug!( . self, . locations, . "eq_opaque_type_and_type: `{:?}=={:?}` failed with `{:?}`", . revealed_ty, . anon_ty, . terr . ); -- line 1257 ---------------------------------------- -- line 1328 ---------------------------------------- . || "opaque_type_map".to_string(), . ), . )?; . } . Ok(()) . } . . fn tcx(&self) -> TyCtxt<'tcx> { 305,485 ( 0.01%) self.infcx.tcx . } . . #[instrument(skip(self, body, location), level = "debug")] . fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) { . let tcx = self.tcx(); 79,844 ( 0.00%) match stmt.kind { 17,162 ( 0.00%) StatementKind::Assign(box (ref place, ref rv)) => { . // Assignments to temporaries are not "interesting"; . // they are not caused by the user, but rather artifacts . // of lowering. Assignments to other sorts of places *are* interesting . // though. 68,596 ( 0.00%) let category = match place.as_local() { . Some(RETURN_PLACE) => { 186 ( 0.00%) let defining_ty = &self.borrowck_context.universal_regions.defining_ty; 93 ( 0.00%) if defining_ty.is_const() { 60 ( 0.00%) if tcx.is_static(defining_ty.def_id()) { . ConstraintCategory::UseAsStatic . } else { . ConstraintCategory::UseAsConst . } . } else { . ConstraintCategory::Return(ReturnConstraint::Normal) . } . } . Some(l) 18,115 ( 0.00%) if matches!( 34,354 ( 0.00%) body.local_decls[l].local_info, . Some(box LocalInfo::AggregateTemp) . ) => . { . ConstraintCategory::Usage . } . Some(l) if !body.local_decls[l].is_user_variable() => { . ConstraintCategory::Boring . } -- line 1371 ---------------------------------------- -- line 1373 ---------------------------------------- . }; . debug!( . "assignment category: {:?} {:?}", . category, . place.as_local().map(|l| &body.local_decls[l]) . ); . . let place_ty = place.ty(body, tcx).ty; 205,944 ( 0.01%) let place_ty = self.normalize(place_ty, location); 17,162 ( 0.00%) let rv_ty = rv.ty(body, tcx); 102,972 ( 0.00%) let rv_ty = self.normalize(rv_ty, location); 34,324 ( 0.00%) if let Err(terr) = . self.sub_types(rv_ty, place_ty, location.to_locations(), category) . { . span_mirbug!( . self, . stmt, . "bad assignment ({:?} = {:?}): {:?}", . place_ty, . rv_ty, . terr . ); . } . 13,926 ( 0.00%) if let Some(annotation_index) = self.rvalue_user_ty(rv) { . if let Err(terr) = self.relate_type_and_user_type( . rv_ty, . ty::Variance::Invariant, . &UserTypeProjection { base: annotation_index, projs: vec![] }, . location.to_locations(), . ConstraintCategory::Boring, . ) { . let annotation = &self.user_type_annotations[annotation_index]; -- line 1405 ---------------------------------------- -- line 1409 ---------------------------------------- . "bad user type on rvalue ({:?} = {:?}): {:?}", . annotation, . rv_ty, . terr . ); . } . } . 120,134 ( 0.00%) self.check_rvalue(body, rv, location); 17,162 ( 0.00%) if !self.unsized_feature_enabled() { . let trait_ref = ty::TraitRef { 188,782 ( 0.01%) def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)), 85,810 ( 0.00%) substs: tcx.mk_substs_trait(place_ty, &[]), . }; 51,486 ( 0.00%) self.prove_trait_ref( . trait_ref, . location.to_locations(), . ConstraintCategory::SizedBound, . ); . } . } . StatementKind::SetDiscriminant { ref place, variant_index } => { . let place_type = place.ty(body, tcx).ty; -- line 1431 ---------------------------------------- -- line 1488 ---------------------------------------- . #[instrument(skip(self, body, term_location), level = "debug")] . fn check_terminator( . &mut self, . body: &Body<'tcx>, . term: &Terminator<'tcx>, . term_location: Location, . ) { . let tcx = self.tcx(); 5,300 ( 0.00%) match term.kind { . TerminatorKind::Goto { .. } . | TerminatorKind::Resume . | TerminatorKind::Abort . | TerminatorKind::Return . | TerminatorKind::GeneratorDrop . | TerminatorKind::Unreachable . | TerminatorKind::Drop { .. } . | TerminatorKind::FalseEdge { .. } -- line 1504 ---------------------------------------- -- line 1520 ---------------------------------------- . term, . "bad DropAndReplace ({:?} = {:?}): {:?}", . place_ty, . rv_ty, . terr . ); . } . } 568 ( 0.00%) TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => { 426 ( 0.00%) self.check_operand(discr, term_location); . 142 ( 0.00%) let discr_ty = discr.ty(body, tcx); 284 ( 0.00%) if let Err(terr) = self.sub_types( . discr_ty, . switch_ty, . term_location.to_locations(), . ConstraintCategory::Assignment, . ) { . span_mirbug!( . self, . term, . "bad SwitchInt ({:?} on {:?}): {:?}", . switch_ty, . discr_ty, . terr . ); . } 204 ( 0.00%) if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() { . span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty); . } . // FIXME: check the values . } 1,542 ( 0.00%) TerminatorKind::Call { ref func, ref args, ref destination, from_hir_call, .. } => { 1,285 ( 0.00%) self.check_operand(func, term_location); . for arg in args { 1,680 ( 0.00%) self.check_operand(arg, term_location); . } . 257 ( 0.00%) let func_ty = func.ty(body, tcx); . debug!("check_terminator: call, func_ty={:?}", func_ty); 1,028 ( 0.00%) let sig = match func_ty.kind() { 1,028 ( 0.00%) ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx), . _ => { . span_mirbug!(self, term, "call to non-function {:?}", func_ty); . return; . } . }; 2,570 ( 0.00%) let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars( 771 ( 0.00%) term.source_info.span, . LateBoundRegionConversionTime::FnCall, . sig, . ); 514 ( 0.00%) let sig = self.normalize(sig, term_location); 1,028 ( 0.00%) self.check_call_dest(body, term, &sig, destination, term_location); . . self.prove_predicates( 257 ( 0.00%) sig.inputs_and_output . .iter() 1,186 ( 0.00%) .map(|ty| ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))), . term_location.to_locations(), . ConstraintCategory::Boring, . ); . . // The ordinary liveness rules will ensure that all . // regions in the type of the callee are live here. We . // then further constrain the late-bound regions that . // were instantiated at the call site to be live as . // well. The resulting is that all the input (and . // output) types in the signature must be live, since . // all the inputs that fed into it were live. 1,942 ( 0.00%) for &late_bound_region in map.values() { . let region_vid = 400 ( 0.00%) self.borrowck_context.universal_regions.to_region_vid(late_bound_region); 400 ( 0.00%) self.borrowck_context . .constraints . .liveness_constraints . .add_element(region_vid, term_location); . } . 514 ( 0.00%) self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call); . } 180 ( 0.00%) TerminatorKind::Assert { ref cond, ref msg, .. } => { 270 ( 0.00%) self.check_operand(cond, term_location); . 180 ( 0.00%) let cond_ty = cond.ty(body, tcx); 90 ( 0.00%) if cond_ty != tcx.types.bool { . span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty); . } . 196 ( 0.00%) if let AssertKind::BoundsCheck { ref len, ref index } = *msg { 4 ( 0.00%) if len.ty(body, tcx) != tcx.types.usize { . span_mirbug!(self, len, "bounds-check length non-usize {:?}", len) . } 4 ( 0.00%) if index.ty(body, tcx) != tcx.types.usize { . span_mirbug!(self, index, "bounds-check index non-usize {:?}", index) . } . } . } . TerminatorKind::Yield { ref value, .. } => { . self.check_operand(value, term_location); . . let value_ty = value.ty(body, tcx); -- line 1621 ---------------------------------------- -- line 1647 ---------------------------------------- . &mut self, . body: &Body<'tcx>, . term: &Terminator<'tcx>, . sig: &ty::FnSig<'tcx>, . destination: &Option<(Place<'tcx>, BasicBlock)>, . term_location: Location, . ) { . let tcx = self.tcx(); 1,028 ( 0.00%) match *destination { . Some((ref dest, _target_block)) => { . let dest_ty = dest.ty(body, tcx).ty; 1,536 ( 0.00%) let dest_ty = self.normalize(dest_ty, term_location); 1,280 ( 0.00%) let category = match dest.as_local() { . Some(RETURN_PLACE) => { 203 ( 0.00%) if let BorrowCheckContext { . universal_regions: . UniversalRegions { . defining_ty: . DefiningTy::Const(def_id, _) . | DefiningTy::InlineConst(def_id, _), . .. . }, . .. -- line 1669 ---------------------------------------- -- line 1673 ---------------------------------------- . ConstraintCategory::UseAsStatic . } else { . ConstraintCategory::UseAsConst . } . } else { . ConstraintCategory::Return(ReturnConstraint::Normal) . } . } 150 ( 0.00%) Some(l) if !body.local_decls[l].is_user_variable() => { . ConstraintCategory::Boring . } . _ => ConstraintCategory::Assignment, . }; . . let locations = term_location.to_locations(); . 1,792 ( 0.00%) if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) { . span_mirbug!( . self, . term, . "call dest mismatch ({:?} <- {:?}): {:?}", . dest_ty, . sig.output(), . terr . ); . } . . // When `unsized_fn_params` and `unsized_locals` are both not enabled, . // this check is done at `check_local`. 256 ( 0.00%) if self.unsized_feature_enabled() { . let span = term.source_info.span; . self.ensure_place_sized(dest_ty, span); . } . } . None => { 1 ( 0.00%) if !self . .tcx() 3 ( 0.00%) .conservative_is_privately_uninhabited(self.param_env.and(sig.output())) . { . span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig); . } . } . } . } . . fn check_call_inputs( -- line 1718 ---------------------------------------- -- line 1720 ---------------------------------------- . body: &Body<'tcx>, . term: &Terminator<'tcx>, . sig: &ty::FnSig<'tcx>, . args: &[Operand<'tcx>], . term_location: Location, . from_hir_call: bool, . ) { . debug!("check_call_inputs({:?}, {:?})", sig, args); 1,799 ( 0.00%) if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) { . span_mirbug!(self, term, "call to {:?} with wrong # of args", sig); . } 1,186 ( 0.00%) for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() { . let op_arg_ty = op_arg.ty(body, self.tcx()); 1,344 ( 0.00%) let op_arg_ty = self.normalize(op_arg_ty, term_location); . let category = if from_hir_call { . ConstraintCategory::CallArgument . } else { . ConstraintCategory::Boring . }; 672 ( 0.00%) if let Err(terr) = 672 ( 0.00%) self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category) . { . span_mirbug!( . self, . term, . "bad arg #{:?} ({:?} <- {:?}): {:?}", . n, . fn_arg, . op_arg_ty, . terr . ); . } . } . } . . fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) { 512 ( 0.00%) let is_cleanup = block_data.is_cleanup; 3,180 ( 0.00%) self.last_span = block_data.terminator().source_info.span; 6,360 ( 0.00%) match block_data.terminator().kind { 261 ( 0.00%) TerminatorKind::Goto { target } => { 1,044 ( 0.00%) self.assert_iscleanup(body, block_data, target, is_cleanup) . } 142 ( 0.00%) TerminatorKind::SwitchInt { ref targets, .. } => { 142 ( 0.00%) for target in targets.all_targets() { 2,088 ( 0.00%) self.assert_iscleanup(body, block_data, *target, is_cleanup); . } . } . TerminatorKind::Resume => { 42 ( 0.00%) if !is_cleanup { . span_mirbug!(self, block_data, "resume on non-cleanup block!") . } . } . TerminatorKind::Abort => { . if !is_cleanup { . span_mirbug!(self, block_data, "abort on non-cleanup block!") . } . } . TerminatorKind::Return => { 75 ( 0.00%) if is_cleanup { . span_mirbug!(self, block_data, "return on cleanup block") . } . } . TerminatorKind::GeneratorDrop { .. } => { . if is_cleanup { . span_mirbug!(self, block_data, "generator_drop in cleanup block") . } . } -- line 1786 ---------------------------------------- -- line 1792 ---------------------------------------- . if let Some(drop) = drop { . self.assert_iscleanup(body, block_data, drop, is_cleanup); . } . } . TerminatorKind::Unreachable => {} . TerminatorKind::Drop { target, unwind, .. } . | TerminatorKind::DropAndReplace { target, unwind, .. } . | TerminatorKind::Assert { target, cleanup: unwind, .. } => { 730 ( 0.00%) self.assert_iscleanup(body, block_data, target, is_cleanup); 292 ( 0.00%) if let Some(unwind) = unwind { 118 ( 0.00%) if is_cleanup { . span_mirbug!(self, block_data, "unwind on cleanup block") . } . self.assert_iscleanup(body, block_data, unwind, true); . } . } 257 ( 0.00%) TerminatorKind::Call { ref destination, cleanup, .. } => { 1,282 ( 0.00%) if let &Some((_, target)) = destination { 512 ( 0.00%) self.assert_iscleanup(body, block_data, target, is_cleanup); . } 771 ( 0.00%) if let Some(cleanup) = cleanup { 257 ( 0.00%) if is_cleanup { . span_mirbug!(self, block_data, "cleanup on cleanup block") . } . self.assert_iscleanup(body, block_data, cleanup, true); . } . } 184 ( 0.00%) TerminatorKind::FalseEdge { real_target, imaginary_target } => { 552 ( 0.00%) self.assert_iscleanup(body, block_data, real_target, is_cleanup); 460 ( 0.00%) self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup); . } 40 ( 0.00%) TerminatorKind::FalseUnwind { real_target, unwind } => { 100 ( 0.00%) self.assert_iscleanup(body, block_data, real_target, is_cleanup); 40 ( 0.00%) if let Some(unwind) = unwind { 20 ( 0.00%) if is_cleanup { . span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind"); . } . self.assert_iscleanup(body, block_data, unwind, true); . } . } . TerminatorKind::InlineAsm { destination, cleanup, .. } => { . if let Some(target) = destination { . self.assert_iscleanup(body, block_data, target, is_cleanup); -- line 1834 ---------------------------------------- -- line 1838 ---------------------------------------- . span_mirbug!(self, block_data, "cleanup on cleanup block") . } . self.assert_iscleanup(body, block_data, cleanup, true); . } . } . } . } . 14,490 ( 0.00%) fn assert_iscleanup( . &mut self, . body: &Body<'tcx>, . ctxt: &dyn fmt::Debug, . bb: BasicBlock, . iscleanuppad: bool, . ) { 9,660 ( 0.00%) if body[bb].is_cleanup != iscleanuppad { . span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad); . } 8,050 ( 0.00%) } . . fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) { . match body.local_kind(local) { . LocalKind::ReturnPointer | LocalKind::Arg => { . // return values of normal functions are required to be . // sized by typeck, but return values of ADT constructors are . // not because we don't include a `Self: Sized` bounds on them. . // -- line 1864 ---------------------------------------- -- line 1866 ---------------------------------------- . // - maybe we should make that a warning. . return; . } . LocalKind::Var | LocalKind::Temp => {} . } . . // When `unsized_fn_params` or `unsized_locals` is enabled, only function calls . // and nullary ops are checked in `check_call_dest`. 32,991 ( 0.00%) if !self.unsized_feature_enabled() { 65,982 ( 0.00%) let span = local_decl.source_info.span; 32,991 ( 0.00%) let ty = local_decl.ty; 65,982 ( 0.00%) self.ensure_place_sized(ty, span); . } . } . 296,919 ( 0.01%) fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) { . let tcx = self.tcx(); . . // Erase the regions from `ty` to get a global type. The . // `Sized` bound in no way depends on precise regions, so this . // shouldn't affect `is_sized`. . let erased_ty = tcx.erase_regions(ty); 197,946 ( 0.01%) if !erased_ty.is_sized(tcx.at(span), self.param_env) { . // in current MIR construction, all non-control-flow rvalue . // expressions evaluate through `as_temp` or `into` a return . // slot or local, so to find all unsized rvalues it is enough . // to check all temps, return slots and locals. . if self.reported_errors.replace((ty, span)).is_none() { . let mut diag = struct_span_err!( . self.tcx().sess, . span, -- line 1896 ---------------------------------------- -- line 1901 ---------------------------------------- . ); . . // While this is located in `nll::typeck` this error is not . // an NLL error, it's a required check to prevent creation . // of unsized rvalues in a call expression. . diag.emit(); . } . } 197,946 ( 0.01%) } . . fn aggregate_field_ty( . &mut self, . ak: &AggregateKind<'tcx>, . field_index: usize, . location: Location, . ) -> Result, FieldAccessError> { . let tcx = self.tcx(); . 166,650 ( 0.01%) match *ak { 210,384 ( 0.01%) AggregateKind::Adt(adt_did, variant_index, substs, _, active_field_index) => { . let def = tcx.adt_def(adt_did); . let variant = &def.variants[variant_index]; . let adj_field_index = active_field_index.unwrap_or(field_index); 23,376 ( 0.00%) if let Some(field) = variant.fields.get(adj_field_index) { 210,384 ( 0.01%) Ok(self.normalize(field.ty(tcx, substs), location)) . } else { . Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() }) . } . } 5 ( 0.00%) AggregateKind::Closure(_, substs) => { 60 ( 0.00%) match substs.as_closure().upvar_tys().nth(field_index) { . Some(ty) => Ok(ty), . None => Err(FieldAccessError::OutOfRange { . field_count: substs.as_closure().upvar_tys().count(), . }), . } . } . AggregateKind::Generator(_, substs, _) => { . // It doesn't make sense to look at a field beyond the prefix; -- line 1939 ---------------------------------------- -- line 1941 ---------------------------------------- . // aggregate rvalues. . match substs.as_generator().prefix_tys().nth(field_index) { . Some(ty) => Ok(ty), . None => Err(FieldAccessError::OutOfRange { . field_count: substs.as_generator().prefix_tys().count(), . }), . } . } 9,949 ( 0.00%) AggregateKind::Array(ty) => Ok(ty), . AggregateKind::Tuple => { . unreachable!("This should have been covered in check_rvalues"); . } . } . } . 273,378 ( 0.01%) fn check_operand(&mut self, op: &Operand<'tcx>, location: Location) { 78,108 ( 0.00%) if let Operand::Constant(constant) = op { 65,682 ( 0.00%) let maybe_uneval = match constant.literal { 65,682 ( 0.00%) ConstantKind::Ty(ct) => match ct.val { 18 ( 0.00%) ty::ConstKind::Unevaluated(uv) => Some(uv), . _ => None, . }, . _ => None, . }; 36 ( 0.00%) if let Some(uv) = maybe_uneval { 18 ( 0.00%) if uv.promoted.is_none() { . let tcx = self.tcx(); 63 ( 0.00%) let def_id = uv.def.def_id_for_type_of(); 36 ( 0.00%) if tcx.def_kind(def_id) == DefKind::InlineConst { . let predicates = self.prove_closure_bounds( . tcx, . def_id.expect_local(), . uv.substs, . location, . ); . self.normalize_and_prove_instantiated_predicates( . def_id, . predicates, . location.to_locations(), . ); . } . } . } . } 312,432 ( 0.01%) } . 223,106 ( 0.01%) fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) { . let tcx = self.tcx(); . 86,138 ( 0.00%) match rvalue { . Rvalue::Aggregate(ak, ops) => { . for op in ops { 185,680 ( 0.01%) self.check_operand(op, location); . } 31,710 ( 0.00%) self.check_aggregate_rvalue(&body, rvalue, ak, ops, location) . } . . Rvalue::Repeat(operand, len) => { . self.check_operand(operand, location); . . // If the length cannot be evaluated we must assume that the length can be larger . // than 1. . // If the length is larger than 1, the repeat expression will need to copy the -- line 2003 ---------------------------------------- -- line 2071 ---------------------------------------- . . self.prove_trait_ref( . trait_ref, . location.to_locations(), . ConstraintCategory::SizedBound, . ); . } . 100 ( 0.00%) Rvalue::Cast(cast_kind, op, ty) => { 100 ( 0.00%) self.check_operand(op, location); . 155 ( 0.00%) match cast_kind { . CastKind::Pointer(PointerCast::ReifyFnPointer) => { . let fn_sig = op.ty(body, tcx).fn_sig(tcx); . . // The type that we see in the fcx is like . // `foo::<'a, 'b>`, where `foo` is the path to a . // function definition. When we extract the . // signature, it comes from the `fn_sig` query, . // and hence may contain unnormalized results. -- line 2090 ---------------------------------------- -- line 2158 ---------------------------------------- . ty_fn_ptr_from, . ty, . terr . ); . } . } . . CastKind::Pointer(PointerCast::Unsize) => { 24 ( 0.00%) let &ty = ty; . let trait_ref = ty::TraitRef { 88 ( 0.00%) def_id: tcx 8 ( 0.00%) .require_lang_item(LangItem::CoerceUnsized, Some(self.last_span)), 96 ( 0.00%) substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]), . }; . 72 ( 0.00%) self.prove_trait_ref( . trait_ref, . location.to_locations(), . ConstraintCategory::Cast, . ); . } . . CastKind::Pointer(PointerCast::MutToConstPointer) => { . let ty_from = match op.ty(body, tcx).kind() { -- line 2181 ---------------------------------------- -- line 2290 ---------------------------------------- . ty_elem, . ty_to, . terr . ) . } . } . . CastKind::Misc => { 17 ( 0.00%) let ty_from = op.ty(body, tcx); 68 ( 0.00%) let cast_ty_from = CastTy::from_ty(ty_from); 51 ( 0.00%) let cast_ty_to = CastTy::from_ty(ty); 221 ( 0.00%) match (cast_ty_from, cast_ty_to) { . (None, _) . | (_, None | Some(CastTy::FnPtr)) . | (Some(CastTy::Float), Some(CastTy::Ptr(_))) . | (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Float)) => { . span_mirbug!(self, rvalue, "Invalid cast {:?} -> {:?}", ty_from, ty,) . } . ( . Some(CastTy::Int(_)), -- line 2309 ---------------------------------------- -- line 2312 ---------------------------------------- . | (Some(CastTy::Float), Some(CastTy::Int(_) | CastTy::Float)) . | (Some(CastTy::Ptr(_)), Some(CastTy::Int(_) | CastTy::Ptr(_))) . | (Some(CastTy::FnPtr), Some(CastTy::Int(_) | CastTy::Ptr(_))) => (), . } . } . } . } . 325 ( 0.00%) Rvalue::Ref(region, _borrow_kind, borrowed_place) => { 1,950 ( 0.00%) self.add_reborrow_constraint(&body, location, region, borrowed_place); . } . . Rvalue::BinaryOp( . BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge, 192 ( 0.00%) box (left, right), . ) => { 320 ( 0.00%) self.check_operand(left, location); 320 ( 0.00%) self.check_operand(right, location); . 64 ( 0.00%) let ty_left = left.ty(body, tcx); 192 ( 0.00%) match ty_left.kind() { . // Types with regions are comparable if they have a common super-type. . ty::RawPtr(_) | ty::FnPtr(_) => { . let ty_right = right.ty(body, tcx); . let common_ty = self.infcx.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::MiscVariable, . span: body.source_info(location).span, . }); . self.sub_types( -- line 2340 ---------------------------------------- -- line 2360 ---------------------------------------- . ty_right, . terr . ) . } . } . // For types with no regions we can just check that the . // both operands have the same type. . ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_) 320 ( 0.00%) if ty_left == right.ty(body, tcx) => {} . // Other types are compared by trait methods, not by . // `Rvalue::BinaryOp`. . _ => span_mirbug!( . self, . rvalue, . "unexpected comparison types {:?} and {:?}", . ty_left, . right.ty(body, tcx) . ), . } . } . . Rvalue::Use(operand) | Rvalue::UnaryOp(_, operand) => { 1,516 ( 0.00%) self.check_operand(operand, location); . } . . Rvalue::BinaryOp(_, box (left, right)) . | Rvalue::CheckedBinaryOp(_, box (left, right)) => { 364 ( 0.00%) self.check_operand(left, location); 182 ( 0.00%) self.check_operand(right, location); . } . . Rvalue::AddressOf(..) . | Rvalue::ThreadLocalRef(..) . | Rvalue::Len(..) . | Rvalue::Discriminant(..) => {} . } 130,504 ( 0.01%) } . . /// If this rvalue supports a user-given type annotation, then . /// extract and return it. This represents the final type of the . /// rvalue and will be unified with the inferred type. . fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option { 68,648 ( 0.00%) match rvalue { . Rvalue::Use(_) . | Rvalue::ThreadLocalRef(_) . | Rvalue::Repeat(..) . | Rvalue::Ref(..) . | Rvalue::AddressOf(..) . | Rvalue::Len(..) . | Rvalue::Cast(..) . | Rvalue::ShallowInitBox(..) . | Rvalue::BinaryOp(..) . | Rvalue::CheckedBinaryOp(..) . | Rvalue::NullaryOp(..) . | Rvalue::UnaryOp(..) . | Rvalue::Discriminant(..) => None, . 47,565 ( 0.00%) Rvalue::Aggregate(aggregate, _) => match **aggregate { 41,778 ( 0.00%) AggregateKind::Adt(_, _, _, user_ty, _) => user_ty, . AggregateKind::Array(_) => None, . AggregateKind::Tuple => None, . AggregateKind::Closure(_, _) => None, . AggregateKind::Generator(_, _, _) => None, . }, . } . } . -- line 2426 ---------------------------------------- -- line 2431 ---------------------------------------- . aggregate_kind: &AggregateKind<'tcx>, . operands: &[Operand<'tcx>], . location: Location, . ) { . let tcx = self.tcx(); . . self.prove_aggregate_predicates(aggregate_kind, location); . 15,855 ( 0.00%) if *aggregate_kind == AggregateKind::Tuple { . // tuple rvalue field type is always the type of the op. Nothing to check here. . return; . } . 33,330 ( 0.00%) for (i, operand) in operands.iter().enumerate() { 15 ( 0.00%) let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) { 66,660 ( 0.00%) Ok(field_ty) => field_ty, . Err(FieldAccessError::OutOfRange { field_count }) => { . span_mirbug!( . self, . rvalue, . "accessed field #{} but variant only has {}", . i, . field_count . ); . continue; . } . }; . let operand_ty = operand.ty(body, tcx); 199,980 ( 0.01%) let operand_ty = self.normalize(operand_ty, location); . 66,660 ( 0.00%) if let Err(terr) = self.sub_types( . operand_ty, 33,330 ( 0.00%) field_ty, . location.to_locations(), . ConstraintCategory::Boring, . ) { . span_mirbug!( . self, . rvalue, . "{:?} is not a subtype of {:?}: {:?}", . operand_ty, -- line 2471 ---------------------------------------- -- line 2486 ---------------------------------------- . fn add_reborrow_constraint( . &mut self, . body: &Body<'tcx>, . location: Location, . borrow_region: ty::Region<'tcx>, . borrowed_place: &Place<'tcx>, . ) { . // These constraints are only meaningful during borrowck: 325 ( 0.00%) let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } = . self.borrowck_context; . . // In Polonius mode, we also push a `loan_issued_at` fact . // linking the loan to the region (in some cases, though, . // there is no loan associated with this borrow expression -- . // that occurs when we are borrowing an unsafe place, for . // example). 1,950 ( 0.00%) if let Some(all_facts) = all_facts { . let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation"); . if let Some(borrow_index) = borrow_set.get_index_of(&location) { . let region_vid = borrow_region.to_region_vid(); . all_facts.loan_issued_at.push(( . region_vid, . borrow_index, . location_table.mid_index(location), . )); -- line 2510 ---------------------------------------- -- line 2516 ---------------------------------------- . // *p`, where the `p` has type `&'b mut Foo`, for example, we . // need to ensure that `'b: 'a`. . . debug!( . "add_reborrow_constraint({:?}, {:?}, {:?})", . location, borrow_region, borrowed_place . ); . 325 ( 0.00%) let mut cursor = borrowed_place.projection.as_ref(); 325 ( 0.00%) let tcx = self.infcx.tcx; 650 ( 0.00%) let field = path_utils::is_upvar_field_projection( . tcx, 650 ( 0.00%) &self.borrowck_context.upvars, . borrowed_place.as_ref(), . body, . ); 650 ( 0.00%) let category = if let Some(field) = field { . let var_hir_id = self.borrowck_context.upvars[field.index()].place.get_root_variable(); . // FIXME(project-rfc-2229#8): Use Place for better diagnostics . ConstraintCategory::ClosureUpvar(var_hir_id) . } else { . ConstraintCategory::Boring . }; . 1,969 ( 0.00%) while let [proj_base @ .., elem] = cursor { . cursor = proj_base; . . debug!("add_reborrow_constraint - iteration {:?}", elem); . 1,805 ( 0.00%) match elem { . ProjectionElem::Deref => { 480 ( 0.00%) let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty; . . debug!("add_reborrow_constraint - base_ty = {:?}", base_ty); 1,200 ( 0.00%) match base_ty.kind() { . ty::Ref(ref_region, _, mutbl) => { 240 ( 0.00%) constraints.outlives_constraints.push(OutlivesConstraint { 480 ( 0.00%) sup: ref_region.to_region_vid(), . sub: borrow_region.to_region_vid(), . locations: location.to_locations(), . category, . variance_info: ty::VarianceDiagInfo::default(), . }); . 632 ( 0.00%) match mutbl { . hir::Mutability::Not => { . // Immutable reference. We don't need the base . // to be valid for the entire lifetime of . // the borrow. . break; . } . hir::Mutability::Mut => { . // Mutable reference. We *do* need the base -- line 2568 ---------------------------------------- -- line 2617 ---------------------------------------- . ) { . let tcx = self.tcx(); . . debug!( . "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})", . aggregate_kind, location . ); . 216,216 ( 0.01%) let (def_id, instantiated_predicates) = match aggregate_kind { . AggregateKind::Adt(adt_did, _, substs, _, _) => { 111,408 ( 0.00%) (*adt_did, tcx.predicates_of(*adt_did).instantiate(tcx, substs)) . } . . // For closures, we have some **extra requirements** we . // . // have to check. In particular, in their upvars and . // signatures, closures often reference various regions . // from the surrounding function -- we call those the . // closure's free regions. When we borrow-check (and hence -- line 2635 ---------------------------------------- -- line 2644 ---------------------------------------- . // . // Despite the opacity of the previous parapgrah, this is . // actually relatively easy to understand in terms of the . // desugaring. A closure gets desugared to a struct, and . // these extra requirements are basically like where . // clauses on the struct. . AggregateKind::Closure(def_id, substs) . | AggregateKind::Generator(def_id, substs, _) => { 132 ( 0.00%) (*def_id, self.prove_closure_bounds(tcx, def_id.expect_local(), substs, location)) . } . . AggregateKind::Array(_) | AggregateKind::Tuple => { 3,836 ( 0.00%) (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty()) . } . }; . 15,855 ( 0.00%) self.normalize_and_prove_instantiated_predicates( . def_id, 47,565 ( 0.00%) instantiated_predicates, . location.to_locations(), . ); . } . 99 ( 0.00%) fn prove_closure_bounds( . &mut self, . tcx: TyCtxt<'tcx>, . def_id: LocalDefId, . substs: SubstsRef<'tcx>, . location: Location, . ) -> ty::InstantiatedPredicates<'tcx> { 33 ( 0.00%) if let Some(ref closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements . { . let closure_constraints = QueryRegionConstraints { . outlives: closure_region_requirements.apply_requirements( . tcx, . def_id.to_def_id(), . substs, . ), . -- line 2682 ---------------------------------------- -- line 2725 ---------------------------------------- . . self.push_region_constraints( . location.to_locations(), . ConstraintCategory::ClosureBounds, . &closure_constraints, . ); . } . 33 ( 0.00%) tcx.predicates_of(def_id).instantiate(tcx, substs) 88 ( 0.00%) } . 1,125 ( 0.00%) #[instrument(skip(self, body), level = "debug")] . fn typeck_mir(&mut self, body: &Body<'tcx>) { 300 ( 0.00%) self.last_span = body.span; . debug!(?body.span); . . for (local, local_decl) in body.local_decls.iter_enumerated() { . self.check_local(&body, local, local_decl); . } . . for (block, block_data) in body.basic_blocks().iter_enumerated() { . let mut location = Location { block, statement_index: 0 }; . for stmt in &block_data.statements { 79,844 ( 0.00%) if !stmt.source_info.span.is_dummy() { 79,832 ( 0.00%) self.last_span = stmt.source_info.span; . } . self.check_stmt(body, stmt, location); 1,678 ( 0.00%) location.statement_index += 1; . } . . self.check_terminator(&body, block_data.terminator(), location); . self.check_iscleanup(&body, block_data); . } . } . } . -- line 2760 ---------------------------------------- -- line 2765 ---------------------------------------- . impl NormalizeLocation for Locations { . fn to_locations(self) -> Locations { . self . } . } . . impl NormalizeLocation for Location { . fn to_locations(self) -> Locations { 373,825 ( 0.01%) Locations::Single(self) . } . } . . #[derive(Debug, Default)] . struct ObligationAccumulator<'tcx> { . obligations: PredicateObligations<'tcx>, . } . -- line 2781 ---------------------------------------- 290,446 ( 0.01%) -------------------------------------------------------------------------------- -- 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 { 60 ( 0.00%) RefTracking { seen: FxHashSet::default(), todo: vec![] } . } 75 ( 0.00%) pub fn new(op: T) -> Self { . let mut ref_tracking_for_consts = 240 ( 0.00%) RefTracking { seen: FxHashSet::default(), todo: vec![(op, PATH::default())] }; . ref_tracking_for_consts.seen.insert(op); . ref_tracking_for_consts 75 ( 0.00%) } . . pub fn track(&mut self, op: T, path: impl FnOnce() -> PATH) { 46 ( 0.00%) if self.seen.insert(op) { . trace!("Recursing below ptr {:#?}", op); . let path = path(); . // Remember to come back to this later. 66 ( 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> { 1,081,440 ( 0.04%) fn aggregate_field_path_elem(&mut self, layout: TyAndLayout<'tcx>, field: usize) -> PathElem { . // First, check if we are projecting to a variant. 282,016 ( 0.01%) match layout.variants { . Variants::Multiple { tag_field, .. } => { 32,204 ( 0.00%) if tag_field == field { 48,306 ( 0.00%) return match layout.ty.kind() { 32,204 ( 0.00%) 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. 296,072 ( 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 257 ---------------------------------------- . sym::integer(field) . })) . } . . // tuples . ty::Tuple(_) => PathElem::TupleElem(field), . . // enums 93,248 ( 0.00%) ty::Adt(def, ..) if def.is_enum() => { . // we might be projecting *to* a variant, or to a field *in* a variant. 11,656 ( 0.00%) match layout.variants { 11,656 ( 0.00%) Variants::Single { index } => { . // Inside a variant . PathElem::Field(def.variants[index].fields[field].name) . } . Variants::Multiple { .. } => bug!("we handled variants above"), . } . } . . // other ADTs 34,968 ( 0.00%) ty::Adt(def, _) => PathElem::Field(def.non_enum_variant().fields[field].name), . . // arrays/slices . 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), . } 1,171,560 ( 0.05%) } . . fn with_elem( . &mut self, . elem: PathElem, . f: impl FnOnce(&mut Self) -> InterpResult<'tcx, R>, . ) -> InterpResult<'tcx, R> { . // Remember the old state 244,648 ( 0.01%) let path_len = self.path.len(); . // Record new element . self.path.push(elem); . // Perform operation 244,648 ( 0.01%) let r = f(self)?; . // Undo changes . self.path.truncate(path_len); . // Done . Ok(r) . } . 36 ( 0.00%) fn check_wide_ptr_meta( . &mut self, . meta: MemPlaceMeta, . pointee: TyAndLayout<'tcx>, . ) -> InterpResult<'tcx> { 28 ( 0.00%) let tail = self.ecx.tcx.struct_tail_erasing_lifetimes(pointee.ty, self.ecx.param_env); 16 ( 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!( 4 ( 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(()) 36 ( 0.00%) } . . /// Check a reference or `Box`. 66 ( 0.00%) fn check_safe_pointer( . &mut self, . value: &OpTy<'tcx, M::PointerTag>, . kind: &str, . ) -> InterpResult<'tcx> { 18 ( 0.00%) let value = try_validation!( 12 ( 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 60 ( 0.00%) let place = try_validation!( 18 ( 0.00%) self.ecx.ref_to_mplace(&value), . self.path, . err_ub!(InvalidUninitBytes(None)) => { "uninitialized {}", kind }, . ); 18 ( 0.00%) if place.layout.is_unsized() { 44 ( 0.00%) self.check_wide_ptr_meta(place.meta, place.layout)?; . } . // Make sure this is dereferenceable and all. 12 ( 0.00%) let size_and_align = try_validation!( 6 ( 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!( 12 ( 0.00%) self.ecx.memory.check_ptr_access_align( 18 ( 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 18 ( 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 12 ( 0.00%) if let Ok((alloc_id, _offset, _ptr)) = self.ecx.memory.ptr_try_get_alloc(place.ptr) { . // not a ZST 18 ( 0.00%) let alloc_kind = self.ecx.tcx.get_global_alloc(alloc_id); 12 ( 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; 54 ( 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`. 24 ( 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(()) 54 ( 0.00%) } . 410,249 ( 0.02%) fn read_scalar( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, ScalarMaybeUninit> { 468,856 ( 0.02%) Ok(try_validation!( 175,821 ( 0.01%) self.ecx.read_scalar(op), . self.path, . err_unsup!(ReadPointerAsBytes) => { "(potentially part of) a pointer" } expected { "plain (non-pointer) bytes" }, . )) 351,642 ( 0.01%) } . . /// 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. 956,187 ( 0.04%) fn try_visit_primitive( . &mut self, . value: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, bool> { . // Go over all the primitive types 318,729 ( 0.01%) let ty = value.layout.ty; 637,458 ( 0.03%) 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 => { 15,060 ( 0.00%) let value = self.read_scalar(value)?; 7,530 ( 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(_) => { 219,368 ( 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) => { 15 ( 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`" }); . } . } 18 ( 0.00%) self.check_safe_pointer(value, "reference")?; . Ok(true) . } 87,720 ( 0.00%) ty::Adt(def, ..) if def.is_box() => { . self.check_safe_pointer(value, "box")?; . Ok(true) . } . ty::FnPtr(_sig) => { . let value = try_validation!( . self.ecx.read_immediate(value), . self.path, . err_unsup!(ReadPointerAsBytes) => { "part of a pointer" } expected { "a proper pointer or integer value" }, -- line 572 ---------------------------------------- -- line 606 ---------------------------------------- . | ty::Infer(..) . | ty::Placeholder(..) . | ty::Bound(..) . | ty::Param(..) . | ty::Opaque(..) . | ty::Projection(..) . | ty::GeneratorWitness(..) => bug!("Encountered invalid type {:?}", ty), . } 1,593,645 ( 0.06%) } . . 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 688 ---------------------------------------- . &self.ecx . } . . fn read_discriminant( . &mut self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, VariantIdx> { . self.with_elem(PathElem::EnumTag, move |this| { 48,306 ( 0.00%) Ok(try_validation!( 64,408 ( 0.00%) this.ecx.read_discriminant(op), . this.path, . err_ub!(InvalidTag(val)) => . { "{}", val } expected { "a valid enum tag" }, . err_ub!(InvalidUninitBytes(None)) => . { "uninitialized bytes" } expected { "a valid enum tag" }, . err_unsup!(ReadPointerAsBytes) => . { "a pointer" } expected { "a valid enum tag" }, . ) -- line 705 ---------------------------------------- -- line 709 ---------------------------------------- . . #[inline] . fn visit_field( . &mut self, . old_op: &OpTy<'tcx, M::PointerTag>, . field: usize, . new_op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 420,078 ( 0.02%) let elem = self.aggregate_field_path_elem(old_op.layout, field); 270,360 ( 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>, . ) -> InterpResult<'tcx> { 64,408 ( 0.00%) let name = match old_op.layout.ty.kind() { 64,408 ( 0.00%) ty::Adt(adt, _) => PathElem::Variant(adt.variants[variant_id].name), . // Generators also have variants . ty::Generator(..) => PathElem::GeneratorState(variant_id), . _ => bug!("Unexpected type with variant: {:?}", old_op.layout.ty), . }; 112,714 ( 0.00%) self.with_elem(name, move |this| this.visit_value(new_op)) . } . . #[inline(always)] . fn visit_union( . &mut self, . op: &OpTy<'tcx, M::PointerTag>, . _fields: NonZeroUsize, . ) -> InterpResult<'tcx> { -- line 742 ---------------------------------------- -- 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] 955,998 ( 0.04%) 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. 424,951 ( 0.02%) if self.try_visit_primitive(op)? { . return Ok(()); . } . // Sanity check: `builtin_deref` does not know any pointers that are not primitive. 190,520 ( 0.01%) assert!(op.layout.ty.builtin_deref(true).is_none()); . . // Special check preventing `UnsafeCell` in the inner part of constants 182,980 ( 0.01%) if let Some(def) = op.layout.ty.ty_adt_def() { 153,510 ( 0.01%) if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { inner: true, .. })) 153,510 ( 0.01%) && 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. 238,150 ( 0.01%) 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). 238,150 ( 0.01%) 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(()) 849,776 ( 0.03%) } . . fn visit_aggregate( . &mut self, . op: &OpTy<'tcx, M::PointerTag>, . fields: impl Iterator>, . ) -> InterpResult<'tcx> { 428,662 ( 0.02%) match op.layout.ty.kind() { . ty::Str => { . let mplace = op.assert_mem_place(); // strings are never immediate 4 ( 0.00%) let len = mplace.len(self.ecx)?; 4 ( 0.00%) try_validation!( 12 ( 0.00%) 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`" }, . ); . } . 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. 20 ( 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. 36 ( 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> { 126 ( 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 189 ( 0.00%) let mut visitor = ValidityVisitor { path, ref_tracking, ctfe_mode, ecx: self }; . . // Run it. 63 ( 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); . } . } 147 ( 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> { 210 ( 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 ---------------------------------------- 1,579,924 ( 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 { 112,286 ( 0.00%) self.a_is_expected = !self.a_is_expected; . let result = f(self); 749 ( 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> { 2,324 ( 0.00%) self.fields.infcx.tcx 180 ( 0.00%) } . . fn param_env(&self) -> ty::ParamEnv<'tcx> { . self.fields.param_env . } . . fn a_is_expected(&self) -> bool { 1,066 ( 0.00%) self.a_is_expected . } . 42 ( 0.00%) fn with_cause(&mut self, cause: Cause, f: F) -> R . where . F: FnOnce(&mut Self) -> R, . { . debug!("sub with_cause={:?}", cause); 6 ( 0.00%) let old_cause = mem::replace(&mut self.fields.cause, Some(cause)); . let r = f(self); . debug!("sub old_cause={:?}", old_cause); 6 ( 0.00%) self.fields.cause = old_cause; . r 42 ( 0.00%) } . . fn relate_with_variance>( . &mut self, . variance: ty::Variance, . _info: ty::VarianceDiagInfo<'tcx>, . a: T, . b: T, . ) -> RelateResult<'tcx, T> { 1,762 ( 0.00%) match variance { 2,758 ( 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)), . } . } . 931,806 ( 0.04%) fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> { . debug!("{}.tys({:?}, {:?})", self.tag(), a, b); . 103,534 ( 0.00%) if a == b { . return Ok(a); . } . 58,916 ( 0.00%) let infcx = self.fields.infcx; 58,916 ( 0.00%) let a = infcx.inner.borrow_mut().type_variables().replace_if_possible(a); 58,916 ( 0.00%) let b = infcx.inner.borrow_mut().type_variables().replace_if_possible(b); 265,671 ( 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. 34 ( 0.00%) assert!(!a.has_escaping_bound_vars()); 34 ( 0.00%) assert!(!b.has_escaping_bound_vars()); . . // can't make progress on `A <: B` if both A and B are . // type variables, so record an obligation. . self.fields.obligations.push(Obligation::new( . self.fields.trace.cause.clone(), 34 ( 0.00%) self.fields.param_env, 204 ( 0.00%) ty::Binder::dummy(ty::PredicateKind::Subtype(ty::SubtypePredicate { 34 ( 0.00%) a_is_expected: self.a_is_expected, . a, . b, . })) . .to_predicate(self.tcx()), . )); . . Ok(a) . } 27,793 ( 0.00%) (&ty::Infer(TyVar(a_id)), _) => { 166,758 ( 0.01%) self.fields.instantiate(b, RelationDir::SupertypeOf, a_id, !self.a_is_expected)?; . Ok(a) . } 678 ( 0.00%) (_, &ty::Infer(TyVar(b_id))) => { 2,712 ( 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()) . } . . _ => { 5,718 ( 0.00%) self.fields.infcx.super_combine_tys(self, a, b)?; . Ok(a) . } . } 931,806 ( 0.04%) } . 5,436 ( 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. 1,812 ( 0.00%) let origin = SubregionOrigin::Subtype(Box::new(self.fields.trace.clone())); 3,624 ( 0.00%) self.fields . .infcx . .inner . .borrow_mut() . .unwrap_region_constraints() 3,624 ( 0.00%) .make_subregion(origin, a, b); . 1,208 ( 0.00%) Ok(a) 5,436 ( 0.00%) } . . fn consts( . &mut self, . a: &'tcx ty::Const<'tcx>, . b: &'tcx ty::Const<'tcx>, . ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> { 14 ( 0.00%) self.fields.infcx.super_combine_consts(self, a, b) . } . . fn binders( . &mut self, . a: ty::Binder<'tcx, T>, . b: ty::Binder<'tcx, T>, . ) -> RelateResult<'tcx, ty::Binder<'tcx, T>> . where . T: Relate<'tcx>, . { 953 ( 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 ---------------------------------------- 351,701 ( 0.01%) -------------------------------------------------------------------------------- -- 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")] 38,860 ( 0.00%) pub fn from_str_radix(src: &str, radix: u32) -> Result { 19,430 ( 0.00%) from_str_radix(src, radix) 58,290 ( 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 { 16,140 ( 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 { 310,696 ( 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 { 1,018,799 ( 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 { 14,159,728 ( 0.56%) intrinsics::rotate_left(self, n as $SelfT) . } . . /// Shifts the bits to the right by a specified amount, `n`, . /// wrapping the truncated bits to the beginning of the resulting . /// integer. . /// . /// Please note this isn't the same operation as the `>>` shifting operator! . /// -- line 220 ---------------------------------------- -- line 430 ---------------------------------------- . #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] . pub const fn checked_add(self, rhs: Self) -> Option { 2 ( 0.00%) let (a, b) = self.overflowing_add(rhs); . if unlikely!(b) {None} else {Some(a)} . } . . /// Unchecked integer addition. Computes `self + rhs`, assuming overflow . /// cannot occur. . /// . /// # Safety . /// -- line 446 ---------------------------------------- -- line 456 ---------------------------------------- . )] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] . #[inline(always)] . pub const unsafe fn unchecked_add(self, rhs: Self) -> Self { . // SAFETY: the caller must uphold the safety contract for . // `unchecked_add`. 1,228,614 ( 0.05%) 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`. 94,040 ( 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 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 { 235,908 ( 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 { 697,026 ( 0.03%) 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 { 9,190,801 ( 0.36%) 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 { 1,806,627 ( 0.07%) 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 { 9,452,964 ( 0.37%) intrinsics::wrapping_mul(self, rhs) . } . . /// Wrapping (modular) division. Computes `self / rhs`. . /// Wrapped division on unsigned types is just normal division. . /// There's no way wrapping could ever happen. . /// This function exists, so that all operations . /// are accounted for in the wrapping operations. . /// -- line 1256 ---------------------------------------- -- line 1397 ---------------------------------------- . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_shl(self, rhs: u32) -> Self { . // SAFETY: the masking by the bitsize of the type ensures that we do not shift . // out of bounds . unsafe { 9 ( 0.00%) intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT) . } . } . . /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, . /// where `mask` removes any high-order bits of `rhs` that . /// would cause the shift to exceed the bitwidth of the type. . /// . /// Note that this is *not* the same as a rotate-right; the -- line 1413 ---------------------------------------- -- line 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) { 3,394,898 ( 0.13%) 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) { 184,662 ( 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) { 1,823,646 ( 0.07%) let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// Calculates the divisor when `self` is divided by `rhs`. . /// . /// Returns a tuple of the divisor along with a boolean indicating . /// whether an arithmetic overflow would occur. Note that for unsigned . /// integers overflow never occurs, so the second value is always -- line 1690 ---------------------------------------- -- line 1838 ---------------------------------------- . #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) { 3 ( 0.00%) (self.wrapping_shl(rhs), (rhs > ($BITS - 1))) . } . . /// Shifts self right by `rhs` bits. . /// . /// Returns a tuple of the shifted version of self along with a boolean . /// indicating whether the shift value was larger than or equal to the . /// number of bits. If the shift value is too large, then value is . /// masked (N-1) where N is the number of bits, and this value is then -- line 1854 ---------------------------------------- -- line 2132 ---------------------------------------- . #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")] . #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")] . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")] . #[inline(always)] . pub const fn is_power_of_two(self) -> bool { 174 ( 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 { 6,790 ( 0.00%) if self <= 1 { return 0; } . 6,574 ( 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. 19,528 ( 0.00%) let z = unsafe { intrinsics::ctlz_nonzero(p) }; 6,680 ( 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 { 6,314 ( 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 ---------------------------------------- 89,390 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs -------------------------------------------------------------------------------- Ir -- line 72 ---------------------------------------- . /// it might do things like invoke `sub_regions`, which would be . /// bad, because it would create subregion relationships that are . /// not captured in the return value. . fn perform_query( . tcx: TyCtxt<'tcx>, . canonicalized: Canonicalized<'tcx, ParamEnvAnd<'tcx, Self>>, . ) -> Fallible>; . 1,048,382 ( 0.04%) fn fully_perform_into( . query_key: ParamEnvAnd<'tcx, Self>, . infcx: &InferCtxt<'_, 'tcx>, . output_query_region_constraints: &mut QueryRegionConstraints<'tcx>, . ) -> Fallible<( . Self::QueryResponse, . Option>>, . PredicateObligations<'tcx>, . Certainty, . )> { 189,259 ( 0.01%) if let Some(result) = QueryTypeOp::try_fast_path(infcx.tcx, &query_key) { 536,748 ( 0.02%) return Ok((result, None, vec![], Certainty::Proven)); . } . . // FIXME(#33684) -- We need to use . // `canonicalize_query_keep_static` here because of things . // like the subtype query, which go awry around . // `'static` otherwise. 3,200 ( 0.00%) let mut canonical_var_values = OriginalQueryValues::default(); 45 ( 0.00%) let old_param_env = query_key.param_env; . let canonical_self = 1,770 ( 0.00%) infcx.canonicalize_query_keep_static(query_key, &mut canonical_var_values); 15,648 ( 0.00%) let canonical_result = Self::perform_query(infcx.tcx, canonical_self)?; . 20,470 ( 0.00%) let InferOk { value, obligations } = infcx . .instantiate_nll_query_response_and_region_obligations( . &ObligationCause::dummy(), . old_param_env, . &canonical_var_values, . canonical_result, . output_query_region_constraints, . )?; . 25,147 ( 0.00%) Ok((value, Some(canonical_self), obligations, canonical_result.value.certainty)) 990,000 ( 0.04%) } . } . . impl<'tcx, Q> TypeOp<'tcx> for ParamEnvAnd<'tcx, Q> . where . Q: QueryTypeOp<'tcx>, . { . type Output = Q::QueryResponse; . 897,016 ( 0.04%) fn fully_perform(self, infcx: &InferCtxt<'_, 'tcx>) -> Fallible> { . let mut region_constraints = QueryRegionConstraints::default(); 675,194 ( 0.03%) let (output, canonicalized_query, mut obligations, _) = 114,633 ( 0.00%) Q::fully_perform_into(self, infcx, &mut region_constraints)?; . . // Typically, instantiating NLL query results does not . // create obligations. However, in some cases there . // are unresolved type variables, and unify them *can* . // create obligations. In that case, we have to go . // fulfill them. We do this via a (recursive) query. 112,127 ( 0.00%) while !obligations.is_empty() { . trace!("{:#?}", obligations); . let mut progress = false; . for obligation in std::mem::take(&mut obligations) { . let obligation = infcx.resolve_vars_if_possible(obligation); . match ProvePredicate::fully_perform_into( . obligation.param_env.and(ProvePredicate::new(obligation.predicate)), . infcx, . &mut region_constraints, -- line 141 ---------------------------------------- -- line 153 ---------------------------------------- . if !progress { . return Err(NoSolution); . } . } . . // Promote the final query-region-constraints into a . // (optional) ref-counted vector: . let region_constraints = 448,508 ( 0.02%) if region_constraints.is_empty() { None } else { Some(Rc::new(region_constraints)) }; . 1,421,483 ( 0.06%) Ok(TypeOpOutput { output, constraints: region_constraints, canonicalized_query }) 1,121,270 ( 0.04%) } . } 786,723 ( 0.03%) -------------------------------------------------------------------------------- -- 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 { 1,847,023 ( 0.07%) 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)); 47,262 ( 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::()); 43,413,268 ( 1.72%) 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" . ); . 289,966 ( 0.01%) self.stride += Group::WIDTH; 289,966 ( 0.01%) self.pos += self.stride; 268,506 ( 0.01%) 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. 88,350 ( 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. 208,470 ( 0.01%) 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. 14,886 ( 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 { 226,827 ( 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. 20,014 ( 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 = 163,954 ( 0.01%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 223,974 ( 0.01%) let len = ctrl_offset.checked_add(buckets + Group::WIDTH)?; . . Some(( . unsafe { Layout::from_size_align_unchecked(len, ctrl_align) }, . ctrl_offset, . )) . } . } . -- line 263 ---------------------------------------- -- line 337 ---------------------------------------- . } . } . #[cfg_attr(feature = "inline-more", inline)] . pub unsafe fn drop(&self) { . self.as_ptr().drop_in_place(); . } . #[inline] . pub unsafe fn read(&self) -> T { 35,284 ( 0.00%) self.as_ptr().read() . } . #[inline] . pub unsafe fn write(&self, val: T) { . self.as_ptr().write(val); . } . #[inline] . pub unsafe fn as_ref<'a>(&self) -> &'a T { . &*self.as_ptr() -- line 353 ---------------------------------------- -- line 422 ---------------------------------------- . /// Creates a new empty hash table without allocating any memory, using the . /// given allocator. . /// . /// In effect this returns a table with exactly 1 bucket. However we can . /// leave the data pointer dangling since that bucket is never written to . /// due to our load factor forcing us to always have at least 1 free bucket. . #[inline] . pub fn new_in(alloc: A) -> Self { 102 ( 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 { 85 ( 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 { 10,085 ( 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")] 3,645 ( 0.00%) pub unsafe fn erase_no_drop(&mut self, item: &Bucket) { 3,645 ( 0.00%) let index = self.bucket_index(item); . self.table.erase(index); 7,290 ( 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. 2,588 ( 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 { 4,702 ( 0.00%) self.erase_no_drop(&item); 14 ( 0.00%) item.read() . } . . /// Finds and removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] 657,965 ( 0.03%) pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option { . // Avoid `Option::map` because it bloats LLVM IR. 35,084 ( 0.00%) match self.find(hash, eq) { 19,718 ( 0.00%) Some(bucket) => Some(unsafe { self.remove(bucket) }), 327,472 ( 0.01%) None => None, . } 1,045,066 ( 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) { 25,258 ( 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) { 164,859 ( 0.01%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 126,849 ( 0.01%) 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)] 356,165 ( 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 . }, . ) . } 311,080 ( 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)] 2,177,600 ( 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. 1,105 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 1,943,317 ( 0.08%) if unlikely(self.table.growth_left == 0 && special_is_empty(old_ctrl)) { . self.reserve(1, hasher); . index = self.table.find_insert_slot(hash); . } . . self.table.record_item_insert_at(index, old_ctrl, hash); . . let bucket = self.bucket(index); 2 ( 0.00%) bucket.write(value); . bucket . } 1,621,783 ( 0.06%) } . . /// 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)] 295,704 ( 0.01%) pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T { 120 ( 0.00%) unsafe { self.insert(hash, value, hasher).as_mut() } 221,778 ( 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"))] 706 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 138,767 ( 0.01%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 6,376 ( 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. 286,754 ( 0.01%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 224,224 ( 0.01%) self.table.items += 1; . bucket 1,311 ( 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] 400 ( 0.00%) pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { 97,069 ( 0.00%) let result = self.table.find_inner(hash, &mut |index| unsafe { 72,058 ( 0.00%) eq(self.bucket(index).as_ref()) 71,670 ( 0.00%) }); . . // Avoid `Option::map` because it bloats LLVM IR. . match result { 17,393 ( 0.00%) Some(index) => Some(unsafe { self.bucket(index) }), . None => None, . } 400 ( 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. 37,056 ( 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. 298 ( 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 { 2,076,561 ( 0.08%) self.len() == 0 . } . . /// Returns the number of buckets in the table. . #[inline] . pub fn buckets(&self) -> usize { . self.table.bucket_mask + 1 . } . . /// Returns an iterator over every element in the table. It is up to . /// 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 { 7 ( 0.00%) let data = Bucket::from_base_index(self.data_end(), 0); . RawIter { . iter: RawIterRange::new(self.table.ctrl.as_ptr(), data, self.table.buckets()), 229,775 ( 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(); 1,692 ( 0.00%) let allocation = self.into_allocation(); 1,269 ( 0.00%) RawIntoIter { 2,115 ( 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)> { 618 ( 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(( 143 ( 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 { 1,104,283 ( 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)] 299,511 ( 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()); . } . 85,080 ( 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)); 165,114 ( 0.01%) Ok(Self { . ctrl, 71,711 ( 0.00%) bucket_mask: buckets - 1, . items: 0, . growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 218,020 ( 0.01%) } . . #[inline] 22,267 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 5,608 ( 0.00%) if capacity == 0 { 4,740 ( 0.00%) Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = . capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 136,229 ( 0.01%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; . result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 11,071 ( 0.00%) Ok(result) . } . } 22,267 ( 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] 46,633 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { . let index = self.find_insert_slot(hash); 46,633 ( 0.00%) let old_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . (index, old_ctrl) 93,266 ( 0.00%) } . . /// Searches for an empty or deleted bucket which is suitable for inserting . /// a new element. . /// . /// There must be at least 1 empty bucket in the table. . #[inline] . fn find_insert_slot(&self, hash: u64) -> usize { . let mut probe_seq = self.probe_seq(hash); . loop { . unsafe { . let group = Group::load(self.ctrl(probe_seq.pos)); 1,151,034 ( 0.05%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 3,390,443 ( 0.13%) 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). 1,607,116 ( 0.06%) 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); . 15,764 ( 0.00%) loop { . let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 6,026,977 ( 0.24%) for bit in group.match_byte(h2_hash) { 12,235,368 ( 0.48%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 8,580,394 ( 0.34%) if likely(eq(index)) { . return Some(index); . } . } . 1,562,570 ( 0.06%) 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(); 4,740,824 ( 0.19%) 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 { 29,821,492 ( 1.18%) 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) { 2,385,230 ( 0.09%) self.growth_left -= special_is_empty(old_ctrl) as usize; . self.set_ctrl_h2(index, hash); 1,908,184 ( 0.08%) 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] | . // --------------------------------------------- 3,350,733 ( 0.13%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 1,116,911 ( 0.04%) *self.ctrl(index) = ctrl; 1,117,056 ( 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 { 427,518 ( 0.02%) self.bucket_mask + 1 . } . . #[inline] . fn num_ctrl_bytes(&self) -> usize { 146,626 ( 0.01%) self.bucket_mask + 1 + Group::WIDTH . } . . #[inline] . fn is_empty_singleton(&self) -> bool { 1,787,412 ( 0.07%) 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. 807 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( . self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 99,485 ( 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_| { 42,598 ( 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. 85,200 ( 0.00%) let new_items = match self.items.checked_add(additional) { . Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 85,196 ( 0.00%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 179,234 ( 0.01%) 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( 42,598 ( 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> { 1,989 ( 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() { 716,953 ( 0.03%) 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); . 42,598 ( 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( 34,123 ( 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) { 1,403 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 1,617 ( 0.00%) self.items = 0; 1,403 ( 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))); 77,473 ( 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. 309,892 ( 0.01%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 386,125 ( 0.02%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 309,892 ( 0.01%) self.items -= 1; . } . } . . impl Clone for RawTable { 288 ( 0.00%) fn clone(&self) -> Self { 56 ( 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) . } . } 324 ( 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; 34 ( 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)] 684,865 ( 0.03%) fn drop(&mut self) { 780,467 ( 0.03%) if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); . self.free_buckets(); . } . } 729,466 ( 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)] 1,692 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 2,115 ( 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 { 358,540 ( 0.01%) if let Some(index) = self.current_group.lowest_set_bit() { 80,521 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 140,762 ( 0.01%) return Some(self.data.next_n(index)); . } . 319,486 ( 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). 9,813 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); 18,442 ( 0.00%) self.data = self.data.next_n(Group::WIDTH); 10,789 ( 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) { 426 ( 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)] 81,762 ( 0.00%) fn next(&mut self) -> Option> { 166,782 ( 0.01%) if let Some(b) = self.iter.next() { 508,907 ( 0.02%) 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 . } 163,524 ( 0.01%) } . . #[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)] 892 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 2,782 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 262 ( 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)] 127 ( 0.00%) fn next(&mut self) -> Option { 27 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 254 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 3 ( 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)] 40 ( 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. 5 ( 0.00%) self.orig_table . .as_ptr() . .copy_from_nonoverlapping(&*self.table, 1); . } 40 ( 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 ---------------------------------------- 15,238,927 ( 0.60%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/cx/expr.rs -------------------------------------------------------------------------------- Ir -- line 18 ---------------------------------------- . use rustc_middle::ty::{self, AdtKind, Ty, UpvarSubsts, UserType}; . use rustc_span::def_id::DefId; . use rustc_span::Span; . use rustc_target::abi::VariantIdx; . . impl<'tcx> Cx<'tcx> { . crate fn mirror_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> ExprId { . // `mirror_expr` is recursing very deep. Make sure the stack doesn't overflow. 96,321 ( 0.00%) ensure_sufficient_stack(|| self.mirror_expr_inner(expr)) . } . 228 ( 0.00%) crate fn mirror_exprs(&mut self, exprs: &'tcx [hir::Expr<'tcx>]) -> Box<[ExprId]> { 42,171 ( 0.00%) exprs.iter().map(|expr| self.mirror_expr_inner(expr)).collect() 456 ( 0.00%) } . 351,036 ( 0.01%) pub(super) fn mirror_expr_inner(&mut self, hir_expr: &'tcx hir::Expr<'tcx>) -> ExprId { 273,028 ( 0.01%) let temp_lifetime = self.region_scope_tree.temporary_scope(hir_expr.hir_id.local_id); . let expr_scope = . region::Scope { id: hir_expr.hir_id.local_id, data: region::ScopeData::Node }; . . debug!("Expr::make_mirror(): id={}, span={:?}", hir_expr.hir_id, hir_expr.span); . 156,016 ( 0.01%) let mut expr = self.make_mirror_unadjusted(hir_expr); . 234,024 ( 0.01%) let adjustment_span = match self.adjustment_span { 1,333 ( 0.00%) Some((hir_id, span)) if hir_id == hir_expr.hir_id => Some(span), . _ => None, . }; . . // Now apply adjustments, if any. 156,016 ( 0.01%) for adjustment in self.typeck_results.expr_adjustments(hir_expr) { . debug!("make_mirror: expr={:?} applying adjustment={:?}", expr, adjustment); 1,392 ( 0.00%) let span = expr.span; 3,794 ( 0.00%) expr = 9,756 ( 0.00%) self.apply_adjustment(hir_expr, expr, adjustment, adjustment_span.unwrap_or(span)); . } . . // Next, wrap this up in the expr's scope. 507,052 ( 0.02%) expr = Expr { . temp_lifetime, 38,656 ( 0.00%) ty: expr.ty, 39,004 ( 0.00%) span: hir_expr.span, . kind: ExprKind::Scope { . region_scope: expr_scope, 702,072 ( 0.03%) value: self.thir.exprs.push(expr), 78,008 ( 0.00%) lint_level: LintLevel::Explicit(hir_expr.hir_id), . }, . }; . . // Finally, create a destruction scope, if any. 117,012 ( 0.00%) if let Some(region_scope) = 78,008 ( 0.00%) self.region_scope_tree.opt_destruction_scope(hir_expr.hir_id.local_id) . { 4,308 ( 0.00%) expr = Expr { . temp_lifetime, . ty: expr.ty, 359 ( 0.00%) span: hir_expr.span, . kind: ExprKind::Scope { . region_scope, 5,026 ( 0.00%) value: self.thir.exprs.push(expr), . lint_level: LintLevel::Inherited, . }, . }; . } . . // OK, all done! 858,088 ( 0.03%) self.thir.exprs.push(expr) 351,036 ( 0.01%) } . . fn apply_adjustment( . &mut self, . hir_expr: &'tcx hir::Expr<'tcx>, . mut expr: Expr<'tcx>, . adjustment: &Adjustment<'tcx>, . mut span: Span, . ) -> Expr<'tcx> { 1,084 ( 0.00%) let Expr { temp_lifetime, .. } = expr; . . // Adjust the span from the block, to the last expression of the . // block. This is a better span when returning a mutable reference . // with too short a lifetime. The error message will use the span . // from the assignment to the return place, which should only point . // at the returned value, not the entire function body. . // . // fn return_short_lived<'a>(x: &'a mut i32) -> &'static mut i32 { . // x . // // ^ error message points at this expression. . // } . let mut adjust_span = |expr: &mut Expr<'tcx>| { 482 ( 0.00%) if let ExprKind::Block { body } = &expr.kind { 6 ( 0.00%) if let Some(last_expr) = body.expr { 6 ( 0.00%) span = self.thir[last_expr].span; 4 ( 0.00%) expr.span = span; . } . } . }; . 4,748 ( 0.00%) let kind = match adjustment.kind { . Adjust::Pointer(PointerCast::Unsize) => { . adjust_span(&mut expr); 136 ( 0.00%) ExprKind::Pointer { cast: PointerCast::Unsize, source: self.thir.exprs.push(expr) } . } . Adjust::Pointer(cast) => ExprKind::Pointer { cast, source: self.thir.exprs.push(expr) }, 1,173 ( 0.00%) Adjust::NeverToAny => ExprKind::NeverToAny { source: self.thir.exprs.push(expr) }, . Adjust::Deref(None) => { . adjust_span(&mut expr); 3,961 ( 0.00%) ExprKind::Deref { arg: self.thir.exprs.push(expr) } . } 24 ( 0.00%) Adjust::Deref(Some(deref)) => { . // We don't need to do call adjust_span here since . // deref coercions always start with a built-in deref. 30 ( 0.00%) let call = deref.method_call(self.tcx(), expr.ty); . 36 ( 0.00%) expr = Expr { . temp_lifetime, 6 ( 0.00%) ty: self . .tcx 12 ( 0.00%) .mk_ref(deref.region, ty::TypeAndMut { ty: expr.ty, mutbl: deref.mutbl }), . span, . kind: ExprKind::Borrow { . borrow_kind: deref.mutbl.to_borrow_kind(), 90 ( 0.00%) arg: self.thir.exprs.push(expr), . }, . }; . 126 ( 0.00%) let expr = Box::new([self.thir.exprs.push(expr)]); . 78 ( 0.00%) self.overloaded_place(hir_expr, adjustment.target, Some(call), expr, deref.span) . } 904 ( 0.00%) Adjust::Borrow(AutoBorrow::Ref(_, m)) => ExprKind::Borrow { . borrow_kind: m.to_borrow_kind(), 3,164 ( 0.00%) arg: self.thir.exprs.push(expr), . }, . Adjust::Borrow(AutoBorrow::RawPtr(mutability)) => { . ExprKind::AddressOf { mutability, arg: self.thir.exprs.push(expr) } . } . }; . 10,298 ( 0.00%) Expr { temp_lifetime, ty: adjustment.target, span, kind } . } . 390,040 ( 0.02%) fn make_mirror_unadjusted(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Expr<'tcx> { 156,016 ( 0.01%) let expr_ty = self.typeck_results().expr_ty(expr); 39,004 ( 0.00%) let expr_span = expr.span; 195,020 ( 0.01%) let temp_lifetime = self.region_scope_tree.temporary_scope(expr.hir_id.local_id); . 234,285 ( 0.01%) let kind = match expr.kind { . // Here comes the interesting stuff: 369 ( 0.00%) hir::ExprKind::MethodCall(segment, ref args, fn_span) => { . // Rewrite a.b(c) into UFCS form like Trait::b(a, c) 861 ( 0.00%) let expr = self.method_callee(expr, segment.ident.span, None); . // When we apply adjustments to the receiver, use the span of . // the overall method call for better diagnostics. args[0] . // is guaranteed to exist, since a method call always has a receiver. 492 ( 0.00%) let old_adjustment_span = self.adjustment_span.replace((args[0].hir_id, expr_span)); . tracing::info!("Using method span: {:?}", expr.span); 123 ( 0.00%) let args = self.mirror_exprs(args); 246 ( 0.00%) self.adjustment_span = old_adjustment_span; 861 ( 0.00%) ExprKind::Call { 123 ( 0.00%) ty: expr.ty, 1,722 ( 0.00%) fun: self.thir.exprs.push(expr), . args, . from_hir_call: true, . fn_span, . } . } . . hir::ExprKind::Call(ref fun, ref args) => { 23,860 ( 0.00%) if self.typeck_results().is_method_call(expr) { . // The callee is something implementing Fn, FnMut, or FnOnce. . // Find the actual method implementation being called and . // build the appropriate UFCS call expression with the . // callee-object as expr parameter. . . // rewrite f(u, v) into FnOnce::call_once(f, (u, v)) . . let method = self.method_callee(expr, fun.span, None); -- line 194 ---------------------------------------- -- line 206 ---------------------------------------- . ty: method.ty, . fun: self.thir.exprs.push(method), . args: Box::new([self.mirror_expr(fun), tupled_args]), . from_hir_call: true, . fn_span: expr.span, . } . } else { . let adt_data = 29,825 ( 0.00%) if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = fun.kind { . // Tuple-like ADTs are represented as ExprKind::Call. We convert them here. 64,608 ( 0.00%) expr_ty.ty_adt_def().and_then(|adt_def| match path.res { 11,702 ( 0.00%) Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_id) => { 23,404 ( 0.00%) Some((adt_def, adt_def.variant_index_with_ctor_id(ctor_id))) . } . Res::SelfCtor(..) => Some((adt_def, VariantIdx::new(0))), . _ => None, . }) . } else { . None . }; 11,802 ( 0.00%) if let Some((adt_def, index)) = adt_data { 29,255 ( 0.00%) let substs = self.typeck_results().node_substs(fun.hir_id); 17,553 ( 0.00%) let user_provided_types = self.typeck_results().user_provided_types(); . let user_ty = 29,255 ( 0.00%) user_provided_types.get(fun.hir_id).copied().map(|mut u_ty| { . if let UserType::TypeOf(ref mut did, _) = &mut u_ty.value { . *did = adt_def.did; . } . u_ty . }); . debug!("make_mirror_unadjusted: (call) user_ty={:?}", user_ty); . 5,851 ( 0.00%) let field_refs = args . .iter() . .enumerate() . .map(|(idx, e)| FieldExpr { . name: Field::new(idx), . expr: self.mirror_expr(e), . }) . .collect(); . ExprKind::Adt(Box::new(Adt { -- line 246 ---------------------------------------- -- line 247 ---------------------------------------- . adt_def, . substs, . variant_index: index, . fields: field_refs, . user_ty, . base: None, . })) . } else { 456 ( 0.00%) ExprKind::Call { 620 ( 0.00%) ty: self.typeck_results().node_type(fun.hir_id), 114 ( 0.00%) fun: self.mirror_expr(fun), 456 ( 0.00%) args: self.mirror_exprs(args), . from_hir_call: true, 114 ( 0.00%) fn_span: expr.span, . } . } . } . } . . hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, ref arg) => { 270 ( 0.00%) ExprKind::Borrow { borrow_kind: mutbl.to_borrow_kind(), arg: self.mirror_expr(arg) } . } . . hir::ExprKind::AddrOf(hir::BorrowKind::Raw, mutability, ref arg) => { . ExprKind::AddressOf { mutability, arg: self.mirror_expr(arg) } . } . 2,394 ( 0.00%) hir::ExprKind::Block(ref blk, _) => ExprKind::Block { body: self.mirror_block(blk) }, . . hir::ExprKind::Assign(ref lhs, ref rhs, _) => { 258 ( 0.00%) ExprKind::Assign { lhs: self.mirror_expr(lhs), rhs: self.mirror_expr(rhs) } . } . 26 ( 0.00%) hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => { 104 ( 0.00%) if self.typeck_results().is_method_call(expr) { . let lhs = self.mirror_expr(lhs); . let rhs = self.mirror_expr(rhs); . self.overloaded_operator(expr, Box::new([lhs, rhs])) . } else { 130 ( 0.00%) ExprKind::AssignOp { 78 ( 0.00%) op: bin_op(op.node), 26 ( 0.00%) lhs: self.mirror_expr(lhs), 26 ( 0.00%) rhs: self.mirror_expr(rhs), . } . } . } . 21,421 ( 0.00%) hir::ExprKind::Lit(ref lit) => ExprKind::Literal { 85,684 ( 0.00%) literal: self.const_eval_literal(&lit.node, expr_ty, lit.span, false), . user_ty: None, . const_id: None, . }, . 124 ( 0.00%) hir::ExprKind::Binary(op, ref lhs, ref rhs) => { 496 ( 0.00%) if self.typeck_results().is_method_call(expr) { 7 ( 0.00%) let lhs = self.mirror_expr(lhs); 7 ( 0.00%) let rhs = self.mirror_expr(rhs); . self.overloaded_operator(expr, Box::new([lhs, rhs])) . } else { . // FIXME overflow 460 ( 0.00%) match op.node { 16 ( 0.00%) hir::BinOpKind::And => ExprKind::LogicalOp { . op: LogicalOp::And, 4 ( 0.00%) lhs: self.mirror_expr(lhs), 4 ( 0.00%) rhs: self.mirror_expr(rhs), . }, 60 ( 0.00%) hir::BinOpKind::Or => ExprKind::LogicalOp { . op: LogicalOp::Or, 15 ( 0.00%) lhs: self.mirror_expr(lhs), 15 ( 0.00%) rhs: self.mirror_expr(rhs), . }, . _ => { 392 ( 0.00%) let op = bin_op(op.node); 490 ( 0.00%) ExprKind::Binary { . op, 98 ( 0.00%) lhs: self.mirror_expr(lhs), 98 ( 0.00%) rhs: self.mirror_expr(rhs), . } . } . } . } . } . . hir::ExprKind::Index(ref lhs, ref index) => { 55 ( 0.00%) if self.typeck_results().is_method_call(expr) { . let lhs = self.mirror_expr(lhs); . let index = self.mirror_expr(index); 91 ( 0.00%) self.overloaded_place(expr, expr_ty, None, Box::new([lhs, index]), expr.span) . } else { 16 ( 0.00%) ExprKind::Index { lhs: self.mirror_expr(lhs), index: self.mirror_expr(index) } . } . } . . hir::ExprKind::Unary(hir::UnOp::Deref, ref arg) => { 105 ( 0.00%) if self.typeck_results().is_method_call(expr) { . let arg = self.mirror_expr(arg); . self.overloaded_place(expr, expr_ty, None, Box::new([arg]), expr.span) . } else { 63 ( 0.00%) ExprKind::Deref { arg: self.mirror_expr(arg) } . } . } . . hir::ExprKind::Unary(hir::UnOp::Not, ref arg) => { 90 ( 0.00%) if self.typeck_results().is_method_call(expr) { . let arg = self.mirror_expr(arg); . self.overloaded_operator(expr, Box::new([arg])) . } else { 54 ( 0.00%) ExprKind::Unary { op: UnOp::Not, arg: self.mirror_expr(arg) } . } . } . . hir::ExprKind::Unary(hir::UnOp::Neg, ref arg) => { . if self.typeck_results().is_method_call(expr) { . let arg = self.mirror_expr(arg); . self.overloaded_operator(expr, Box::new([arg])) . } else if let hir::ExprKind::Lit(ref lit) = arg.kind { -- line 362 ---------------------------------------- -- line 365 ---------------------------------------- . user_ty: None, . const_id: None, . } . } else { . ExprKind::Unary { op: UnOp::Neg, arg: self.mirror_expr(arg) } . } . } . 11,684 ( 0.00%) hir::ExprKind::Struct(ref qpath, ref fields, ref base) => match expr_ty.kind() { 11,684 ( 0.00%) ty::Adt(adt, substs) => match adt.adt_kind() { . AdtKind::Struct | AdtKind::Union => { 17,526 ( 0.00%) let user_provided_types = self.typeck_results().user_provided_types(); 23,368 ( 0.00%) let user_ty = user_provided_types.get(expr.hir_id).copied(); . debug!("make_mirror_unadjusted: (struct/union) user_ty={:?}", user_ty); 23,368 ( 0.00%) ExprKind::Adt(Box::new(Adt { 11,684 ( 0.00%) adt_def: adt, . variant_index: VariantIdx::new(0), 11,684 ( 0.00%) substs, . user_ty, 11,684 ( 0.00%) fields: self.field_refs(fields), 23,368 ( 0.00%) base: base.as_ref().map(|base| FruInfo { . base: self.mirror_expr(base), . field_types: self.typeck_results().fru_field_types()[expr.hir_id] . .iter() . .copied() . .collect(), . }), . })) . } -- line 393 ---------------------------------------- -- line 418 ---------------------------------------- . } . }, . _ => { . span_bug!(expr.span, "unexpected type for struct literal: {:?}", expr_ty); . } . }, . . hir::ExprKind::Closure(..) => { 33 ( 0.00%) let closure_ty = self.typeck_results().expr_ty(expr); 33 ( 0.00%) let (def_id, substs, movability) = match *closure_ty.kind() { . ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs), None), . ty::Generator(def_id, substs, movability) => { . (def_id, UpvarSubsts::Generator(substs), Some(movability)) . } . _ => { . span_bug!(expr.span, "closure expr w/o closure type: {:?}", closure_ty); . } . }; . 66 ( 0.00%) let upvars = self . .typeck_results . .closure_min_captures_flattened(def_id) . .zip(substs.upvar_tys()) . .map(|(captured_place, ty)| { 25 ( 0.00%) let upvars = self.capture_upvar(expr, captured_place, ty); 70 ( 0.00%) self.thir.exprs.push(upvars) . }) . .collect(); . . // Convert the closure fake reads, if any, from hir `Place` to ExprRef 11 ( 0.00%) let fake_reads = match self.typeck_results.closure_fake_reads.get(&def_id) { . Some(fake_reads) => fake_reads . .iter() . .map(|(place, cause, hir_id)| { . let expr = self.convert_captured_hir_place(expr, place.clone()); . (self.thir.exprs.push(expr), *cause, *hir_id) . }) . .collect(), . None => Vec::new(), . }; . 209 ( 0.00%) ExprKind::Closure { closure_id: def_id, substs, upvars, movability, fake_reads } . } . 2,890 ( 0.00%) hir::ExprKind::Path(ref qpath) => { 11,560 ( 0.00%) let res = self.typeck_results().qpath_res(qpath, expr.hir_id); 11,560 ( 0.00%) self.convert_path_expr(expr, res) . } . . hir::ExprKind::InlineAsm(ref asm) => ExprKind::InlineAsm { . template: asm.template, . operands: asm . .operands . .iter() . .map(|(op, _op_sp)| { -- line 472 ---------------------------------------- -- line 581 ---------------------------------------- . let count = match ty.kind() { . ty::Array(_, ct) => ct, . _ => span_bug!(expr.span, "unexpected repeat expr ty: {:?}", ty), . }; . . ExprKind::Repeat { value: self.mirror_expr(v), count } . } . hir::ExprKind::Ret(ref v) => { 99 ( 0.00%) ExprKind::Return { value: v.as_ref().map(|v| self.mirror_expr(v)) } . } 69 ( 0.00%) hir::ExprKind::Break(dest, ref value) => match dest.target_id { 115 ( 0.00%) Ok(target_id) => ExprKind::Break { . label: region::Scope { id: target_id.local_id, data: region::ScopeData::Node }, . value: value.as_ref().map(|value| self.mirror_expr(value)), . }, . Err(err) => bug!("invalid loop id for break: {}", err), . }, 24 ( 0.00%) hir::ExprKind::Continue(dest) => match dest.target_id { 32 ( 0.00%) Ok(loop_id) => ExprKind::Continue { . label: region::Scope { id: loop_id.local_id, data: region::ScopeData::Node }, . }, . Err(err) => bug!("invalid loop id for continue: {}", err), . }, 40 ( 0.00%) hir::ExprKind::Let(let_expr) => ExprKind::Let { 5 ( 0.00%) expr: self.mirror_expr(let_expr.init), 15 ( 0.00%) pat: self.pattern_from_hir(let_expr.pat), . }, 748 ( 0.00%) hir::ExprKind::If(cond, then, else_opt) => ExprKind::If { . if_then_scope: region::Scope { 68 ( 0.00%) id: then.hir_id.local_id, . data: region::ScopeData::IfThen, . }, . cond: self.mirror_expr(cond), . then: self.mirror_expr(then), . else_opt: else_opt.map(|el| self.mirror_expr(el)), . }, 245 ( 0.00%) hir::ExprKind::Match(ref discr, ref arms, _) => ExprKind::Match { 49 ( 0.00%) scrutinee: self.mirror_expr(discr), 367 ( 0.00%) arms: arms.iter().map(|a| self.convert_arm(a)).collect(), . }, . hir::ExprKind::Loop(ref body, ..) => { 100 ( 0.00%) let block_ty = self.typeck_results().node_type(body.hir_id); 120 ( 0.00%) let temp_lifetime = self.region_scope_tree.temporary_scope(body.hir_id.local_id); 80 ( 0.00%) let block = self.mirror_block(body); 300 ( 0.00%) let body = self.thir.exprs.push(Expr { . ty: block_ty, . temp_lifetime, 20 ( 0.00%) span: block.span, 160 ( 0.00%) kind: ExprKind::Block { body: block }, . }); 60 ( 0.00%) ExprKind::Loop { body } . } 280 ( 0.00%) hir::ExprKind::Field(ref source, ..) => ExprKind::Field { 70 ( 0.00%) lhs: self.mirror_expr(source), 420 ( 0.00%) name: Field::new(self.tcx.field_index(expr.hir_id, self.typeck_results)), . }, . hir::ExprKind::Cast(ref source, ref cast_ty) => { . // Check for a user-given type annotation on this `cast` 68 ( 0.00%) let user_provided_types = self.typeck_results.user_provided_types(); 102 ( 0.00%) let user_ty = user_provided_types.get(cast_ty.hir_id); . . debug!( . "cast({:?}) has ty w/ hir_id {:?} and user provided ty {:?}", . expr, cast_ty.hir_id, user_ty, . ); . . // Check to see if this cast is a "coercion cast", where the cast is actually done . // using a coercion (or is a no-op). 102 ( 0.00%) let cast = if self.typeck_results().is_coercion_cast(source.hir_id) { . // Convert the lexpr to a vexpr. . ExprKind::Use { source: self.mirror_expr(source) } 51 ( 0.00%) } else if self.typeck_results().expr_ty(source).is_region_ptr() { . // Special cased so that we can type check that the element . // type of the source matches the pointed to type of the . // destination. . ExprKind::Pointer { . source: self.mirror_expr(source), . cast: PointerCast::ArrayToPointer, . } . } else { -- line 660 ---------------------------------------- -- line 664 ---------------------------------------- . // enum's layout (or its tag type) to compute it during const eval . // Example: . // enum Foo { . // A, . // B = A as isize + 4, . // } . // The correct solution would be to add symbolic computations to miri, . // so we wouldn't have to compute and store the actual value 61 ( 0.00%) let var = if let hir::ExprKind::Path(ref qpath) = source.kind { 60 ( 0.00%) let res = self.typeck_results().qpath_res(qpath, source.hir_id); 70 ( 0.00%) self.typeck_results().node_type(source.hir_id).ty_adt_def().and_then( . |adt_def| match res { . Res::Def( . DefKind::Ctor(CtorOf::Variant, CtorKind::Const), . variant_ctor_id, . ) => { . let idx = adt_def.variant_index_with_ctor_id(variant_ctor_id); . let (d, o) = adt_def.discriminant_def_for_variant(idx); . use rustc_middle::ty::util::IntTypeExt; -- line 682 ---------------------------------------- -- line 683 ---------------------------------------- . let ty = adt_def.repr.discr_type(); . let ty = ty.to_ty(self.tcx()); . Some((d, o, ty)) . } . _ => None, . }, . ) . } else { 14 ( 0.00%) None . }; . 30 ( 0.00%) let source = if let Some((did, offset, var_ty)) = var { . let mk_const = |literal| Expr { . temp_lifetime, . ty: var_ty, . span: expr.span, . kind: ExprKind::Literal { literal, user_ty: None, const_id: None }, . }; . let offset = self.thir.exprs.push(mk_const(ty::Const::from_bits( . self.tcx, -- line 702 ---------------------------------------- -- line 723 ---------------------------------------- . ty: var_ty, . span: expr.span, . kind: bin, . }) . } . None => offset, . } . } else { 10 ( 0.00%) self.mirror_expr(source) . }; . . ExprKind::Cast { source: source } . }; . 34 ( 0.00%) if let Some(user_ty) = user_ty { . // NOTE: Creating a new Expr and wrapping a Cast inside of it may be . // inefficient, revisit this when performance becomes an issue. . let cast_expr = self.thir.exprs.push(Expr { . temp_lifetime, . ty: expr_ty, . span: expr.span, . kind: cast, . }); . debug!("make_mirror_unadjusted: (cast) user_ty={:?}", user_ty); . . ExprKind::ValueTypeAscription { source: cast_expr, user_ty: Some(*user_ty) } . } else { 68 ( 0.00%) cast . } . } . hir::ExprKind::Type(ref source, ref ty) => { . let user_provided_types = self.typeck_results.user_provided_types(); . let user_ty = user_provided_types.get(ty.hir_id).copied(); . debug!("make_mirror_unadjusted: (type) user_ty={:?}", user_ty); . let mirrored = self.mirror_expr(source); . if source.is_syntactic_place_expr() { . ExprKind::PlaceTypeAscription { source: mirrored, user_ty } . } else { . ExprKind::ValueTypeAscription { source: mirrored, user_ty } . } . } . hir::ExprKind::DropTemps(ref source) => { 292 ( 0.00%) ExprKind::Use { source: self.mirror_expr(source) } . } . hir::ExprKind::Box(ref value) => ExprKind::Box { value: self.mirror_expr(value) }, . hir::ExprKind::Array(ref fields) => { 20 ( 0.00%) ExprKind::Array { fields: self.mirror_exprs(fields) } . } 9,570 ( 0.00%) hir::ExprKind::Tup(ref fields) => ExprKind::Tuple { fields: self.mirror_exprs(fields) }, . . hir::ExprKind::Yield(ref v, _) => ExprKind::Yield { value: self.mirror_expr(v) }, . hir::ExprKind::Err => unreachable!(), . }; . 1,326,136 ( 0.05%) Expr { temp_lifetime, ty: expr_ty, span: expr.span, kind } 312,032 ( 0.01%) } . 2,340 ( 0.00%) fn user_substs_applied_to_res( . &mut self, . hir_id: hir::HirId, . res: Res, . ) -> Option> { . debug!("user_substs_applied_to_res: res={:?}", res); 1,560 ( 0.00%) let user_provided_type = match res { . // A reference to something callable -- e.g., a fn, method, or . // a tuple-struct or tuple-variant. This has the type of a . // `Fn` but with the user-given substitutions. . Res::Def(DefKind::Fn, _) . | Res::Def(DefKind::AssocFn, _) . | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) . | Res::Def(DefKind::Const, _) . | Res::Def(DefKind::AssocConst, _) => { 1,820 ( 0.00%) self.typeck_results().user_provided_types().get(hir_id).copied() . } . . // A unit struct/variant which is used as a value (e.g., . // `None`). This has the type of the enum/struct that defines . // this variant -- but with the substitutions given by the . // user. . Res::Def(DefKind::Ctor(_, CtorKind::Const), _) => { . self.user_substs_applied_to_ty_of_hir_id(hir_id) -- line 803 ---------------------------------------- -- line 805 ---------------------------------------- . . // `Self` is used in expression as a tuple struct constructor or a unit struct constructor . Res::SelfCtor(_) => self.user_substs_applied_to_ty_of_hir_id(hir_id), . . _ => bug!("user_substs_applied_to_res: unexpected res {:?} at {:?}", res, hir_id), . }; . debug!("user_substs_applied_to_res: user_provided_type={:?}", user_provided_type); . user_provided_type 1,560 ( 0.00%) } . 1,859 ( 0.00%) fn method_callee( . &mut self, . expr: &hir::Expr<'_>, . span: Span, . overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>, . ) -> Expr<'tcx> { 858 ( 0.00%) let temp_lifetime = self.region_scope_tree.temporary_scope(expr.hir_id.local_id); 1,144 ( 0.00%) let (def_id, substs, user_ty) = match overloaded_callee { . Some((def_id, substs)) => (def_id, substs, None), . None => { . let (kind, def_id) = 1,233 ( 0.00%) self.typeck_results().type_dependent_def(expr.hir_id).unwrap_or_else(|| { . span_bug!(expr.span, "no type-dependent def for method callee") . }); 2,055 ( 0.00%) let user_ty = self.user_substs_applied_to_res(expr.hir_id, Res::Def(kind, def_id)); . debug!("method_callee: user_ty={:?}", user_ty); 2,055 ( 0.00%) (def_id, self.typeck_results().node_substs(expr.hir_id), user_ty) . } . }; . let ty = self.tcx().mk_fn_def(def_id, substs); 1,859 ( 0.00%) Expr { . temp_lifetime, . ty, . span, . kind: ExprKind::Literal { . literal: ty::Const::zero_sized(self.tcx(), ty), 858 ( 0.00%) user_ty, . const_id: None, . }, . } 1,144 ( 0.00%) } . 954 ( 0.00%) fn convert_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) -> ArmId { 848 ( 0.00%) let arm = Arm { 318 ( 0.00%) pattern: self.pattern_from_hir(&arm.pat), 10 ( 0.00%) guard: arm.guard.as_ref().map(|g| match g { 5 ( 0.00%) hir::Guard::If(ref e) => Guard::If(self.mirror_expr(e)), . hir::Guard::IfLet(ref pat, ref e) => { . Guard::IfLet(self.pattern_from_hir(pat), self.mirror_expr(e)) . } . }), 106 ( 0.00%) body: self.mirror_expr(arm.body), 212 ( 0.00%) lint_level: LintLevel::Explicit(arm.hir_id), . scope: region::Scope { id: arm.hir_id.local_id, data: region::ScopeData::Node }, 106 ( 0.00%) span: arm.span, . }; 1,590 ( 0.00%) self.thir.arms.push(arm) 954 ( 0.00%) } . . fn convert_path_expr(&mut self, expr: &'tcx hir::Expr<'tcx>, res: Res) -> ExprKind<'tcx> { 20,230 ( 0.00%) let substs = self.typeck_results().node_substs(expr.hir_id); 31,395 ( 0.00%) match res { . // A regular function, constructor function or a constant. . Res::Def(DefKind::Fn, _) . | Res::Def(DefKind::AssocFn, _) . | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) . | Res::SelfCtor(..) => { 1,140 ( 0.00%) let user_ty = self.user_substs_applied_to_res(expr.hir_id, res); . debug!("convert_path_expr: user_ty={:?}", user_ty); 114 ( 0.00%) ExprKind::Literal { . literal: ty::Const::zero_sized( 228 ( 0.00%) self.tcx, 342 ( 0.00%) self.typeck_results().node_type(expr.hir_id), . ), 912 ( 0.00%) user_ty, . const_id: None, . } . } . . Res::Def(DefKind::ConstParam, def_id) => { . let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); . let item_id = self.tcx.hir().get_parent_node(hir_id); . let item_def_id = self.tcx.hir().local_def_id(item_id); -- line 887 ---------------------------------------- -- line 895 ---------------------------------------- . ty: self.typeck_results().node_type(expr.hir_id), . }), . user_ty: None, . const_id: Some(def_id), . } . } . . Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => { 81 ( 0.00%) let user_ty = self.user_substs_applied_to_res(expr.hir_id, res); . debug!("convert_path_expr: (const) user_ty={:?}", user_ty); 45 ( 0.00%) ExprKind::Literal { 108 ( 0.00%) literal: self.tcx.mk_const(ty::Const { . val: ty::ConstKind::Unevaluated(ty::Unevaluated::new( . ty::WithOptConstParam::unknown(def_id), . substs, . )), 27 ( 0.00%) ty: self.typeck_results().node_type(expr.hir_id), . }), 72 ( 0.00%) user_ty, . const_id: Some(def_id), . } . } . 11,165 ( 0.00%) Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id) => { 11,165 ( 0.00%) let user_provided_types = self.typeck_results.user_provided_types(); 8,932 ( 0.00%) let user_provided_type = user_provided_types.get(expr.hir_id).copied(); . debug!("convert_path_expr: user_provided_type={:?}", user_provided_type); 8,932 ( 0.00%) let ty = self.typeck_results().node_type(expr.hir_id); 4,466 ( 0.00%) match ty.kind() { . // A unit struct/variant which is used as a value. . // We return a completely different ExprKind here to account for this special case. . ty::Adt(adt_def, substs) => ExprKind::Adt(Box::new(Adt { 2,233 ( 0.00%) adt_def, 11,165 ( 0.00%) variant_index: adt_def.variant_index_with_ctor_id(def_id), 2,233 ( 0.00%) substs, . user_ty: user_provided_type, . fields: Box::new([]), . base: None, . })), . _ => bug!("unexpected ty: {:?}", ty), . } . } . . // We encode uses of statics as a `*&STATIC` where the `&STATIC` part is . // a constant reference (or constant raw pointer for `static mut`) in MIR 68 ( 0.00%) Res::Def(DefKind::Static, id) => { 204 ( 0.00%) let ty = self.tcx.static_ptr_ty(id); 204 ( 0.00%) let temp_lifetime = self.region_scope_tree.temporary_scope(expr.hir_id.local_id); 204 ( 0.00%) let kind = if self.tcx.is_thread_local_static(id) { . ExprKind::ThreadLocalRef(id) . } else { 136 ( 0.00%) let ptr = self.tcx.create_static_alloc(id); . ExprKind::StaticRef { . literal: ty::Const::from_scalar( . self.tcx, . Scalar::from_pointer(ptr.into(), &self.tcx), . ty, . ), . def_id: id, . } . }; 102 ( 0.00%) ExprKind::Deref { 374 ( 0.00%) arg: self.thir.exprs.push(Expr { ty, temp_lifetime, span: expr.span, kind }), . } . } . 4,000 ( 0.00%) Res::Local(var_hir_id) => self.convert_var(var_hir_id), . . _ => span_bug!(expr.span, "res `{:?}` not yet implemented", res), . } . } . 5,050 ( 0.00%) fn convert_var(&mut self, var_hir_id: hir::HirId) -> ExprKind<'tcx> { . // We want upvars here not captures. . // Captures will be handled in MIR. . let is_upvar = self . .tcx . .upvars_mentioned(self.body_owner) . .map_or(false, |upvars| upvars.contains_key(&var_hir_id)); . . debug!( . "convert_var({:?}): is_upvar={}, body_owner={:?}", . var_hir_id, is_upvar, self.body_owner . ); . 8 ( 0.00%) if is_upvar { 42 ( 0.00%) ExprKind::UpvarRef { closure_def_id: self.body_owner, var_hir_id } . } else { 1,497 ( 0.00%) ExprKind::VarRef { id: var_hir_id } . } 4,040 ( 0.00%) } . 77 ( 0.00%) fn overloaded_operator( . &mut self, . expr: &'tcx hir::Expr<'tcx>, . args: Box<[ExprId]>, . ) -> ExprKind<'tcx> { 49 ( 0.00%) let fun = self.method_callee(expr, expr.span, None); 105 ( 0.00%) let fun = self.thir.exprs.push(fun); 49 ( 0.00%) ExprKind::Call { 35 ( 0.00%) ty: self.thir[fun].ty, . fun, . args, . from_hir_call: false, . fn_span: expr.span, . } 56 ( 0.00%) } . 182 ( 0.00%) fn overloaded_place( . &mut self, . expr: &'tcx hir::Expr<'tcx>, . place_ty: Ty<'tcx>, . overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>, . args: Box<[ExprId]>, . span: Span, . ) -> ExprKind<'tcx> { . // For an overloaded *x or x[y] expression of type T, the method . // call returns an &T and we must add the deref so that the types . // line up (this is because `*x` and `x[y]` represent places): . . // Reconstruct the output assuming it's a reference with the . // same region and mutability as the receiver. This holds for . // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`. 104 ( 0.00%) let (region, mutbl) = match *self.thir[args[0]].ty.kind() { 26 ( 0.00%) ty::Ref(region, _, mutbl) => (region, mutbl), . _ => span_bug!(span, "overloaded_place: receiver is not a reference"), . }; 13 ( 0.00%) let ref_ty = self.tcx.mk_ref(region, ty::TypeAndMut { ty: place_ty, mutbl }); . . // construct the complete expression `foo()` for the overloaded call, . // which will yield the &T type 52 ( 0.00%) let temp_lifetime = self.region_scope_tree.temporary_scope(expr.hir_id.local_id); 78 ( 0.00%) let fun = self.method_callee(expr, span, overloaded_callee); 182 ( 0.00%) let fun = self.thir.exprs.push(fun); 78 ( 0.00%) let fun_ty = self.thir[fun].ty; 182 ( 0.00%) let ref_expr = self.thir.exprs.push(Expr { . temp_lifetime, . ty: ref_ty, . span, . kind: ExprKind::Call { ty: fun_ty, fun, args, from_hir_call: false, fn_span: span }, . }); . . // construct and return a deref wrapper `*foo()` 26 ( 0.00%) ExprKind::Deref { arg: ref_expr } 104 ( 0.00%) } . 55 ( 0.00%) fn convert_captured_hir_place( . &mut self, . closure_expr: &'tcx hir::Expr<'tcx>, . place: HirPlace<'tcx>, . ) -> Expr<'tcx> { 20 ( 0.00%) let temp_lifetime = self.region_scope_tree.temporary_scope(closure_expr.hir_id.local_id); . let var_ty = place.base_ty; . . // The result of capture analysis in `rustc_typeck/check/upvar.rs`represents a captured path . // as it's seen for use within the closure and not at the time of closure creation. . // . // That is we see expect to see it start from a captured upvar and not something that is local . // to the closure's parent. 10 ( 0.00%) let var_hir_id = match place.base { 10 ( 0.00%) HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id, . base => bug!("Expected an upvar, found {:?}", base), . }; . 85 ( 0.00%) let mut captured_place_expr = Expr { . temp_lifetime, . ty: var_ty, 5 ( 0.00%) span: closure_expr.span, 25 ( 0.00%) kind: self.convert_var(var_hir_id), . }; . . for proj in place.projections.iter() { . let kind = match proj.kind { . HirProjectionKind::Deref => { . ExprKind::Deref { arg: self.thir.exprs.push(captured_place_expr) } . } . HirProjectionKind::Field(field, ..) => { -- line 1071 ---------------------------------------- -- line 1082 ---------------------------------------- . } . }; . . captured_place_expr = . Expr { temp_lifetime, ty: proj.ty, span: closure_expr.span, kind }; . } . . captured_place_expr 45 ( 0.00%) } . 50 ( 0.00%) fn capture_upvar( . &mut self, . closure_expr: &'tcx hir::Expr<'tcx>, . captured_place: &'tcx ty::CapturedPlace<'tcx>, . upvar_ty: Ty<'tcx>, . ) -> Expr<'tcx> { . let upvar_capture = captured_place.info.capture_kind; . let captured_place_expr = 35 ( 0.00%) self.convert_captured_hir_place(closure_expr, captured_place.place.clone()); 15 ( 0.00%) let temp_lifetime = self.region_scope_tree.temporary_scope(closure_expr.hir_id.local_id); . 10 ( 0.00%) match upvar_capture { 45 ( 0.00%) ty::UpvarCapture::ByValue => captured_place_expr, . ty::UpvarCapture::ByRef(upvar_borrow) => { 10 ( 0.00%) let borrow_kind = match upvar_borrow { . ty::BorrowKind::ImmBorrow => BorrowKind::Shared, . ty::BorrowKind::UniqueImmBorrow => BorrowKind::Unique, . ty::BorrowKind::MutBorrow => BorrowKind::Mut { allow_two_phase_borrow: false }, . }; 14 ( 0.00%) Expr { . temp_lifetime, . ty: upvar_ty, 2 ( 0.00%) span: closure_expr.span, . kind: ExprKind::Borrow { . borrow_kind, 30 ( 0.00%) arg: self.thir.exprs.push(captured_place_expr), . }, . } . } . } 45 ( 0.00%) } . . /// Converts a list of named fields (i.e., for struct-like struct/enum ADTs) into FieldExpr. . fn field_refs(&mut self, fields: &'tcx [hir::ExprField<'tcx>]) -> Box<[FieldExpr]> { . fields . .iter() . .map(|field| FieldExpr { 52,575 ( 0.00%) name: Field::new(self.tcx.field_index(field.hir_id, self.typeck_results)), . expr: self.mirror_expr(field.expr), . }) . .collect() . } . } . . trait ToBorrowKind { . fn to_borrow_kind(&self) -> BorrowKind; . } . . impl ToBorrowKind for AutoBorrowMutability { . fn to_borrow_kind(&self) -> BorrowKind { . use rustc_middle::ty::adjustment::AllowTwoPhase; 1,582 ( 0.00%) match *self { . AutoBorrowMutability::Mut { allow_two_phase_borrow } => BorrowKind::Mut { . allow_two_phase_borrow: match allow_two_phase_borrow { . AllowTwoPhase::Yes => true, . AllowTwoPhase::No => false, . }, . }, . AutoBorrowMutability::Not => BorrowKind::Shared, . } . } . } . . impl ToBorrowKind for hir::Mutability { . fn to_borrow_kind(&self) -> BorrowKind { 12 ( 0.00%) match *self { . hir::Mutability::Mut => BorrowKind::Mut { allow_two_phase_borrow: false }, . hir::Mutability::Not => BorrowKind::Shared, . } . } . } . 248 ( 0.00%) fn bin_op(op: hir::BinOpKind) -> BinOp { 1,116 ( 0.00%) match op { . hir::BinOpKind::Add => BinOp::Add, . hir::BinOpKind::Sub => BinOp::Sub, . hir::BinOpKind::Mul => BinOp::Mul, . hir::BinOpKind::Div => BinOp::Div, . hir::BinOpKind::Rem => BinOp::Rem, . hir::BinOpKind::BitXor => BinOp::BitXor, . hir::BinOpKind::BitAnd => BinOp::BitAnd, . hir::BinOpKind::BitOr => BinOp::BitOr, -- line 1173 ---------------------------------------- -- line 1176 ---------------------------------------- . hir::BinOpKind::Eq => BinOp::Eq, . hir::BinOpKind::Lt => BinOp::Lt, . hir::BinOpKind::Le => BinOp::Le, . hir::BinOpKind::Ne => BinOp::Ne, . hir::BinOpKind::Ge => BinOp::Ge, . hir::BinOpKind::Gt => BinOp::Gt, . _ => bug!("no equivalent for ast binop {:?}", op), . } 248 ( 0.00%) } 610,491 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs -------------------------------------------------------------------------------- Ir -- line 55 ---------------------------------------- . /// `ctxt` values depend partly on the crate size and partly on the form of . /// the code. No crates in `rustc-perf` need more than 15 bits for `ctxt`, . /// but larger crates might need more than 16 bits. . /// . /// In order to reliably use parented spans in incremental compilation, . /// the dependency to the parent definition's span. This is performed . /// using the callback `SPAN_TRACK` to access the query engine. . /// 309,484 ( 0.01%) #[derive(Clone, Copy, Eq, PartialEq, Hash)] . // FIXME(@lcnr): Enable this attribute once the bootstrap . // compiler knows of `rustc_pass_by_value`. . // . // Right now, this lint would only trigger when compiling the . // stage 2 compiler, which is fairly annoying as there are . // a lot of places using `&Span` right now. After the next bootstrap bump, . // the lint will already trigger when using stage 1, which is a lot less annoying. . // . // #[cfg_attr(not(bootstrap), rustc_pass_by_value)] . pub struct Span { 1,479 ( 0.00%) base_or_index: u32, 537 ( 0.00%) len_or_tag: u16, 1,093 ( 0.00%) ctxt_or_zero: u16, . } . . const LEN_TAG: u16 = 0b1000_0000_0000_0000; . const MAX_LEN: u32 = 0b0111_1111_1111_1111; . const MAX_CTXT: u32 = 0b1111_1111_1111_1111; . . /// Dummy span, both position and length are zero, syntax context is zero as well. . pub const DUMMY_SP: Span = Span { base_or_index: 0, len_or_tag: 0, ctxt_or_zero: 0 }; -- line 84 ---------------------------------------- -- line 86 ---------------------------------------- . impl Span { . #[inline] . pub fn new( . mut lo: BytePos, . mut hi: BytePos, . ctxt: SyntaxContext, . parent: Option, . ) -> Self { 395,203 ( 0.02%) if lo > hi { . std::mem::swap(&mut lo, &mut hi); . } . 790,406 ( 0.03%) let (base, len, ctxt2) = (lo.0, hi.0 - lo.0, ctxt.as_u32()); . 2,946,103 ( 0.12%) if len <= MAX_LEN && ctxt2 <= MAX_CTXT && parent.is_none() { . // Inline format. . Span { base_or_index: base, len_or_tag: len as u16, ctxt_or_zero: ctxt2 as u16 } . } else { . // Interned format. . let index = 190 ( 0.00%) with_span_interner(|interner| interner.intern(&SpanData { lo, hi, ctxt, parent })); . Span { base_or_index: index, len_or_tag: LEN_TAG, ctxt_or_zero: 0 } . } 1,104,593 ( 0.04%) } . . #[inline] . pub fn data(self) -> SpanData { . let data = self.data_untracked(); 79,614 ( 0.00%) if let Some(parent) = data.parent { . (*SPAN_TRACK)(parent); . } . data . } . . /// Internal function to translate between an encoded span and the expanded representation. . /// This function must not be used outside the incremental engine. . #[inline] . pub fn data_untracked(self) -> SpanData { 4,039,650 ( 0.16%) if self.len_or_tag != LEN_TAG { . // Inline format. . debug_assert!(self.len_or_tag as u32 <= MAX_LEN); . SpanData { . lo: BytePos(self.base_or_index), 3,637,693 ( 0.14%) hi: BytePos(self.base_or_index + self.len_or_tag as u32), . ctxt: SyntaxContext::from_u32(self.ctxt_or_zero as u32), . parent: None, . } . } else { . // Interned format. . debug_assert!(self.ctxt_or_zero == 0); 49,861 ( 0.00%) let index = self.base_or_index; 189,761 ( 0.01%) with_span_interner(|interner| interner.spans[index as usize]) . } 1,655,337 ( 0.07%) } . } . 4 ( 0.00%) #[derive(Default)] . pub struct SpanInterner { . spans: FxIndexSet, . } . . impl SpanInterner { 42 ( 0.00%) fn intern(&mut self, span_data: &SpanData) -> u32 { 56 ( 0.00%) let (index, _) = self.spans.insert_full(*span_data); . index as u32 56 ( 0.00%) } . } . . // If an interner exists, return it. Otherwise, prepare a fresh one. . #[inline] . fn with_span_interner T>(f: F) -> T { . crate::with_session_globals(|session_globals| f(&mut *session_globals.span_interner.lock())) . } 3,635,384 ( 0.14%) -------------------------------------------------------------------------------- -- 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> { 136 ( 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`. 182 ( 0.00%) if ty.is_never() { 6 ( 0.00%) assert!( 18 ( 0.00%) !self.typeck_results.borrow().adjustments().contains_key(expr.hir_id), . "expression with never type wound up being adjusted" . ); 15 ( 0.00%) let adj_ty = self.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::AdjustmentType, 3 ( 0.00%) span: expr.span, . }); 9 ( 0.00%) self.apply_adjustments( . expr, 6 ( 0.00%) vec![Adjustment { kind: Adjust::NeverToAny, target: adj_ty }], . ); . ty = adj_ty; . } . 1,410 ( 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 . } . 194,643 ( 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) 151,389 ( 0.01%) } . . pub(super) fn check_expr_with_hint( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Ty<'tcx>, . ) -> Ty<'tcx> { 83 ( 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. 60 ( 0.00%) if let Needs::MutPlace = needs { 181 ( 0.00%) 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 141 ---------------------------------------- -- 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> { 216,629 ( 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`. 583,323 ( 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> { 179,484 ( 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. 89,742 ( 0.00%) let is_try_block_generated_unit_expr = match expr.kind { 29,825 ( 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 { 314,097 ( 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); . 107,224 ( 0.00%) let ty = ensure_sufficient_stack(|| match &expr.kind { . hir::ExprKind::Path( . qpath @ hir::QPath::Resolved(..) | qpath @ hir::QPath::TypeRelative(..), 52,266 ( 0.00%) ) => self.check_expr_path(qpath, expr, args), 180,800 ( 0.01%) _ => self.check_expr_kind(expr, expected), . }); . . // Warn for non-block expressions with diverging children. 179,484 ( 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. 29,825 ( 0.00%) ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {} 29,825 ( 0.00%) ExprKind::Call(callee, _) => self.warn_if_unreachable(expr.hir_id, callee.span, "call"), 123 ( 0.00%) ExprKind::MethodCall(segment, ..) => { 369 ( 0.00%) self.warn_if_unreachable(expr.hir_id, segment.ident.span, "call") . } 230,820 ( 0.01%) _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"), . } . . // Any expression that produces a value of type `!` must have diverged 44,871 ( 0.00%) if ty.is_never() { 107 ( 0.00%) 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. 224,355 ( 0.01%) self.write_ty(expr.hir_id, ty); . . // Combine the diverging and has_error flags. . self.diverges.set(self.diverges.get() | old_diverges); 44,871 ( 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 403,839 ( 0.02%) } . 700,025 ( 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); . 36,160 ( 0.00%) let tcx = self.tcx; 217,020 ( 0.01%) match expr.kind { . ExprKind::Box(subexpr) => self.check_expr_box(subexpr, expected), . ExprKind::Lit(ref lit) => self.check_lit(&lit, expected), 1,736 ( 0.00%) ExprKind::Binary(op, lhs, rhs) => self.check_binop(expr, op, lhs, rhs), 129 ( 0.00%) ExprKind::Assign(lhs, rhs, ref span) => { . self.check_expr_assign(expr, expected, lhs, rhs, span) . } 364 ( 0.00%) ExprKind::AssignOp(op, lhs, rhs) => self.check_binop_assign(expr, op, lhs, rhs), 117 ( 0.00%) ExprKind::Unary(unop, oprnd) => self.check_expr_unary(unop, oprnd, expected, expr), 486 ( 0.00%) ExprKind::AddrOf(kind, mutbl, oprnd) => { . self.check_expr_addr_of(kind, mutbl, oprnd, expected, expr) . } 60 ( 0.00%) 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) => { 92 ( 0.00%) self.check_expr_break(destination, expr_opt.as_deref(), expr) . } . ExprKind::Continue(destination) => { 8 ( 0.00%) if destination.target_id.is_ok() { 16 ( 0.00%) tcx.types.never . } else { . // There was an error; make type-check fail. . tcx.ty_error() . } . } . ExprKind::Ret(ref expr_opt) => self.check_expr_return(expr_opt.as_deref(), expr), 5 ( 0.00%) ExprKind::Let(let_expr) => self.check_expr_let(let_expr), 40 ( 0.00%) ExprKind::Loop(body, _, source, _) => { . self.check_expr_loop(body, source, expected, expr) . } 147 ( 0.00%) ExprKind::Match(discrim, arms, match_src) => { 343 ( 0.00%) self.check_match(expr, &discrim, arms, expected, match_src) . } 33 ( 0.00%) ExprKind::Closure(capture, decl, body_id, _, gen) => { 132 ( 0.00%) self.check_expr_closure(expr, capture, &decl, body_id, gen, expected) . } 1,881 ( 0.00%) ExprKind::Block(body, _) => self.check_block_with_expected(&body, expected), 47,720 ( 0.00%) ExprKind::Call(callee, args) => self.check_call(expr, &callee, args, expected), 123 ( 0.00%) ExprKind::MethodCall(segment, args, _) => { . self.check_method_call(expr, segment, args, expected) . } 51 ( 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 . } 340 ( 0.00%) ExprKind::If(cond, then_expr, opt_else_expr) => { 68 ( 0.00%) self.check_then_else(cond, then_expr, opt_else_expr, expr.span, expected) . } 73 ( 0.00%) ExprKind::DropTemps(e) => self.check_expr_with_expectation(e, expected), 8 ( 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) . } 5,742 ( 0.00%) ExprKind::Tup(elts) => self.check_expr_tuple(elts, expected, expr), 29,210 ( 0.00%) ExprKind::Struct(qpath, fields, ref base_expr) => { . self.check_expr_struct(expr, expected, qpath, fields, base_expr) . } 910 ( 0.00%) ExprKind::Field(base, field) => self.check_field(expr, &base, field), 33 ( 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 350 ---------------------------------------- . fn check_expr_unary( . &self, . unop: hir::UnOp, . oprnd: &'tcx hir::Expr<'tcx>, . expected: Expectation<'tcx>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { . let tcx = self.tcx; 39 ( 0.00%) let expected_inner = match unop { . hir::UnOp::Not | hir::UnOp::Neg => expected, . hir::UnOp::Deref => NoExpectation, . }; 78 ( 0.00%) let mut oprnd_t = self.check_expr_with_expectation(&oprnd, expected_inner); . 39 ( 0.00%) if !oprnd_t.references_error() { 273 ( 0.00%) oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t); 114 ( 0.00%) match unop { . hir::UnOp::Deref => { . if let Some(ty) = self.lookup_derefing(expr, oprnd, oprnd_t) { . oprnd_t = ty; . } else { . let mut err = type_error_struct!( . tcx.sess, . expr.span, . oprnd_t, -- line 374 ---------------------------------------- -- line 382 ---------------------------------------- . { . tcx.sess.parse_sess.expr_parentheses_needed(&mut err, *sp); . } . err.emit(); . oprnd_t = tcx.ty_error(); . } . } . hir::UnOp::Not => { 72 ( 0.00%) let result = self.check_user_unop(expr, oprnd_t, unop); . // If it's builtin, we can reuse the type, this helps inference. 102 ( 0.00%) if !(oprnd_t.is_integral() || *oprnd_t.kind() == ty::Bool) { . oprnd_t = result; . } . } . hir::UnOp::Neg => { . let result = self.check_user_unop(expr, oprnd_t, unop); . // If it's builtin, we can reuse the type, this helps inference. . if !oprnd_t.is_numeric() { . oprnd_t = result; -- line 400 ---------------------------------------- -- 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| { 215 ( 0.00%) match ty.kind() { . ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => { 140 ( 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 { 48 ( 0.00%) Expectation::rvalue_hint(self, ty) . } . } . _ => NoExpectation, . } 129 ( 0.00%) }); . let ty = . self.check_expr_with_expectation_and_needs(&oprnd, hint, Needs::maybe_mut_place(mutbl)); . . let tm = ty::TypeAndMut { ty, mutbl }; 54 ( 0.00%) match kind { 54 ( 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. 270 ( 0.00%) let region = self.next_region_var(infer::AddrOfRegion(expr.span)); 54 ( 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 489 ---------------------------------------- . } . . fn check_lang_item_path( . &self, . lang_item: hir::LangItem, . expr: &'tcx hir::Expr<'tcx>, . hir_id: Option, . ) -> Ty<'tcx> { 360 ( 0.00%) self.resolve_lang_item_path(lang_item, expr.span, expr.hir_id, hir_id).1 . } . 95,821 ( 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> { 8,711 ( 0.00%) let tcx = self.tcx; 95,821 ( 0.00%) let (res, opt_ty, segs) = 87,110 ( 0.00%) self.resolve_ty_and_res_fully_qualified_call(qpath, expr.hir_id, expr.span); 51,266 ( 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() . } 156,798 ( 0.01%) _ => self.instantiate_value_path(segs, opt_ty, res, expr.span, expr.hir_id).0, . }; . 26,133 ( 0.00%) if let ty::FnDef(..) = ty.kind() { 17,805 ( 0.00%) let fn_sig = ty.fn_sig(tcx); 23,740 ( 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. 5,946 ( 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; 23,784 ( 0.00%) self.require_type_is_sized_deferred( . input, . span, 17,838 ( 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; 35,610 ( 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. 34,844 ( 0.00%) let substs = self.typeck_results.borrow().node_substs(expr.hir_id); . self.add_wf_bounds(substs, expr); . . ty 69,688 ( 0.00%) } . . fn check_expr_break( . &self, . destination: hir::Destination, . expr_opt: Option<&'tcx hir::Expr<'tcx>>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { 23 ( 0.00%) let tcx = self.tcx; 138 ( 0.00%) if let Ok(target_id) = destination.target_id { . let (e_ty, cause); 69 ( 0.00%) if let Some(e) = expr_opt { . // If this is a break with a value, we need to type-check . // the expression. Get an expected type from the loop context. . let opt_coerce_to = { . // We should release `enclosing_breakables` before the `check_expr_with_hint` . // below, so can't move this block of code to the enclosing scope and share . // `ctxt` with the second `encloding_breakables` borrow below. . let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); . match enclosing_breakables.opt_find_breakable(target_id) { -- line 593 ---------------------------------------- -- line 609 ---------------------------------------- . . // Recurse without `enclosing_breakables` borrowed. . e_ty = self.check_expr_with_hint(e, coerce_to); . cause = self.misc(e.span); . } else { . // Otherwise, this is a break *without* a value. That's . // always legal, and is equivalent to `break ()`. . e_ty = tcx.mk_unit(); 69 ( 0.00%) cause = self.misc(expr.span); . } . . // Now that we have type-checked `expr_opt`, borrow . // the `enclosing_loops` field and let's coerce the . // type of `expr_opt` into what is expected. . let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); 115 ( 0.00%) let ctxt = match enclosing_breakables.opt_find_breakable(target_id) { . Some(ctxt) => ctxt, . None => { . // Avoid ICE when `break` is inside a closure (#65383). . return tcx.ty_error_with_message( . expr.span, . "break was outside loop, but no error was emitted", . ); . } . }; . 46 ( 0.00%) if let Some(ref mut coerce) = ctxt.coerce { 5 ( 0.00%) if let Some(ref e) = expr_opt { . coerce.coerce(self, &cause, e, e_ty); . } else { 5 ( 0.00%) assert!(e_ty.is_unit()); . let ty = coerce.expected_ty(); . coerce.coerce_forced_unit( . self, . &cause, 45 ( 0.00%) &mut |mut err| { . self.suggest_mismatched_types_on_tail( . &mut err, expr, ty, e_ty, target_id, . ); . if let Some(val) = ty_kind_suggestion(ty) { . let label = destination . .label . .map(|l| format!(" {}", l.ident)) . .unwrap_or_else(String::new); -- line 652 ---------------------------------------- -- line 664 ---------------------------------------- . } else { . // If `ctxt.coerce` is `None`, we can just ignore . // the type of the expression. This is because . // either this was a break *without* a value, in . // which case it is always a legal type (`()`), or . // else an error would have been flagged by the . // `loops` pass for using break with an expression . // where you are not supposed to. 18 ( 0.00%) assert!(expr_opt.is_none() || self.tcx.sess.has_errors()); . } . . // If we encountered a `break`, then (no surprise) it may be possible to break from the . // loop... unless the value being returned from the loop diverges itself, e.g. . // `break return 5` or `break loop {}`. 138 ( 0.00%) ctxt.may_break |= !self.diverges.get().is_always(); . . // the type of a `break` is always `!`, since it diverges . tcx.types.never . } else { . // Otherwise, we failed to find the enclosing loop; . // this can only happen if the `break` was not . // inside a loop at all, which is caught by the . // loop-checking pass. -- line 686 ---------------------------------------- -- line 708 ---------------------------------------- . } . } . . fn check_expr_return( . &self, . expr_opt: Option<&'tcx hir::Expr<'tcx>>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { 33 ( 0.00%) if self.ret_coercion.is_none() { . let mut err = ReturnStmtOutsideOfFnBody { . span: expr.span, . encl_body_span: None, . encl_fn_span: None, . }; . . let encl_item_id = self.tcx.hir().get_parent_item(expr.hir_id); . -- line 724 ---------------------------------------- -- line 756 ---------------------------------------- . . self.tcx.sess.emit_err(err); . . if let Some(e) = expr_opt { . // We still have to type-check `e` (issue #86188), but calling . // `check_return_expr` only works inside fn bodies. . self.check_expr(e); . } 66 ( 0.00%) } else if let Some(e) = expr_opt { 30 ( 0.00%) if self.ret_coercion_span.get().is_none() { 45 ( 0.00%) self.ret_coercion_span.set(Some(e.span)); . } 120 ( 0.00%) self.check_return_expr(e, true); . } else { . let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut(); 3 ( 0.00%) if self.ret_coercion_span.get().is_none() { 5 ( 0.00%) self.ret_coercion_span.set(Some(expr.span)); . } . let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression); 18 ( 0.00%) if let Some((fn_decl, _)) = self.get_fn_decl(expr.hir_id) { . coercion.coerce_forced_unit( . self, . &cause, 6 ( 0.00%) &mut |db| { . let span = fn_decl.output.span(); . if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) { . db.span_label( . span, . format!("expected `{}` because of this return type", snippet), . ); . } . }, . true, . ); . } else { . coercion.coerce_forced_unit(self, &cause, &mut |_| (), true); . } . } 99 ( 0.00%) 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. 664 ( 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); 83 ( 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 166 ( 0.00%) if !explicit_return { 148 ( 0.00%) if let ExprKind::Block(body, _) = return_expr.kind { 126 ( 0.00%) if let Some(last_expr) = body.expr { 42 ( 0.00%) span = last_expr.span; . } . } . } . ret_coercion.borrow_mut().coerce( . self, 166 ( 0.00%) &self.cause(span, ObligationCauseCode::ReturnValue(return_expr.hir_id)), . return_expr, . return_expr_ty, . ); 664 ( 0.00%) } . 759 ( 0.00%) pub(crate) fn check_lhs_assignable( . &self, . lhs: &'tcx hir::Expr<'tcx>, . err_code: &'static str, . op_span: Span, . ) { 276 ( 0.00%) if lhs.is_syntactic_place_expr() { . return; . } . . // FIXME: Make this use SessionDiagnostic once error codes can be dynamically set. . let mut err = self.tcx.sess.struct_span_err_with_code( . op_span, . "invalid left-hand side of assignment", . DiagnosticId::Error(err_code.into()), -- line 842 ---------------------------------------- -- line 880 ---------------------------------------- . | hir::Node::Crate(_) => break, . _ => { . parent = self.tcx.hir().get_parent_node(parent); . } . } . } . . err.emit(); 552 ( 0.00%) } . . // A generic function for checking the 'then' and 'else' clauses in an 'if' . // or 'if-else' expression. . fn check_then_else( . &self, . 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, |_| {}); . 340 ( 0.00%) self.warn_if_unreachable( 136 ( 0.00%) cond_expr.hir_id, 68 ( 0.00%) then_expr.span, . "block in `if` or `while` expression", . ); . 136 ( 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); . 136 ( 0.00%) if let Some(else_expr) = opt_else_expr { 44 ( 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 = 176 ( 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). 374 ( 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); . } . 884 ( 0.00%) let result_ty = coerce.complete(self); 68 ( 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>, . lhs: &'tcx hir::Expr<'tcx>, . rhs: &'tcx hir::Expr<'tcx>, . span: &Span, . ) -> Ty<'tcx> { 43 ( 0.00%) let expected_ty = expected.coercion_target_type(self, expr.span); 86 ( 0.00%) if expected_ty == self.tcx.types.bool { . // The expected type is `bool` but this will result in `()` so we can reasonably . // say that the user intended to write `lhs == rhs` instead of `lhs = rhs`. . // The likely cause of this is `if foo = bar { .. }`. . let actual_ty = self.tcx.mk_unit(); . let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap(); . let lhs_ty = self.check_expr(&lhs); . let rhs_ty = self.check_expr(&rhs); . let (applicability, eq) = if self.can_coerce(rhs_ty, lhs_ty) { -- line 989 ---------------------------------------- -- line 1019 ---------------------------------------- . if lhs_ty.references_error() || rhs_ty.references_error() { . err.delay_as_bug() . } else { . err.emit(); . } . return self.tcx.ty_error(); . } . 258 ( 0.00%) self.check_lhs_assignable(lhs, "E0070", *span); . . let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace); 258 ( 0.00%) let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty, Some(lhs)); . 258 ( 0.00%) self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized); . 86 ( 0.00%) if lhs_ty.references_error() || rhs_ty.references_error() { . self.tcx.ty_error() . } else { . self.tcx.mk_unit() . } . } . . fn check_expr_let(&self, let_expr: &'tcx hir::Let<'tcx>) -> Ty<'tcx> { . // for let statements, this is done in check_stmt 5 ( 0.00%) let init = let_expr.init; 35 ( 0.00%) self.warn_if_unreachable(init.hir_id, init.span, "block in `let` expression"); . // otherwise check exactly as a let statement 10 ( 0.00%) self.check_decl(let_expr.into()); . // but return a bool, for this is a boolean expression 15 ( 0.00%) self.tcx.types.bool . } . . fn check_expr_loop( . &self, . body: &'tcx hir::Block<'tcx>, . source: hir::LoopSource, . expected: Expectation<'tcx>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { 40 ( 0.00%) let coerce = match source { . // you can only use break with a value from a normal `loop { }` . hir::LoopSource::Loop => { 35 ( 0.00%) let coerce_to = expected.coercion_target_type(self, body.span); . Some(CoerceMany::new(coerce_to)) . } . . hir::LoopSource::While | hir::LoopSource::ForLoop => None, . }; . . let ctxt = BreakableCtxt { . coerce, . may_break: false, // Will get updated if/when we find a `break`. . }; . 340 ( 0.00%) let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || { 60 ( 0.00%) self.check_block_no_value(&body); . }); . 40 ( 0.00%) if ctxt.may_break { . // No way to know whether it's diverging because . // of a `break` or an outer `break` or `return`. . self.diverges.set(Diverges::Maybe); . } . . // If we permit break with a value, then result type is . // the LUB of the breaks (possibly ! if none); else, it . // is nil. This makes sense because infinite loops . // (which would have type !) are only possible iff we . // permit break with a value [1]. 2 ( 0.00%) if ctxt.coerce.is_none() && !ctxt.may_break { . // [1] . self.tcx.sess.delay_span_bug(body.span, "no coercion, but loop may not break"); . } 84 ( 0.00%) ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.mk_unit()) . } . . /// 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> { 246 ( 0.00%) let rcvr = &args[0]; . let rcvr_t = self.check_expr(&rcvr); . // no need to check for bot/err -- callee does that 492 ( 0.00%) let rcvr_t = self.structurally_resolved_type(args[0].span, rcvr_t); 123 ( 0.00%) let span = segment.ident.span; . 1,968 ( 0.00%) let method = match self.lookup_method(rcvr_t, segment, span, expr, rcvr, args) { 246 ( 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. . 1,353 ( 0.00%) self.write_method_call(expr.hir_id, method); 615 ( 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. 1,722 ( 0.00%) self.check_method_argument_types( . span, . expr, 738 ( 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. 68 ( 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. 34 ( 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(); 51 ( 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> { 4 ( 0.00%) let element_ty = if !args.is_empty() { 12 ( 0.00%) let coerce_to = expected . .to_option(self) 9 ( 0.00%) .and_then(|uty| match *uty.kind() { . ty::Array(ty, _) | ty::Slice(ty) => Some(ty), . _ => None, . }) . .unwrap_or_else(|| { 10 ( 0.00%) self.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::TypeInference, . span: expr.span, . }) . }); . let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args); 4 ( 0.00%) assert_eq!(self.diverges.get(), Diverges::Maybe); . for e in args { . let e_ty = self.check_expr_with_hint(e, coerce_to); 9,949 ( 0.00%) let cause = self.misc(e.span); 59,694 ( 0.00%) coerce.coerce(self, &cause, e, e_ty); . } 48 ( 0.00%) coerce.complete(self) . } else { . self.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::TypeInference, . span: expr.span, . }) . }; 24 ( 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> { 3,828 ( 0.00%) let flds = expected.only_has_type(self).and_then(|ty| { 1,911 ( 0.00%) let ty = self.resolve_vars_with_obligations(ty); 3,822 ( 0.00%) match ty.kind() { 1,907 ( 0.00%) ty::Tuple(flds) => Some(&flds[..]), . _ => None, . } . }); . 13,320 ( 0.00%) let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| match flds { 7,584 ( 0.00%) Some(fs) if i < fs.len() => { 13,272 ( 0.00%) let ety = fs[i].expect_ty(); 24,648 ( 0.00%) self.check_expr_coercable_to_type(&e, ety, None); . ety . } 6 ( 0.00%) _ => self.check_expr_with_expectation(&e, NoExpectation), . }); 3,828 ( 0.00%) let tuple = self.tcx.mk_tup(elt_ts_iter); 1,914 ( 0.00%) if tuple.references_error() { . self.tcx.ty_error() . } else { 13,398 ( 0.00%) self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized); . tuple . } . } . . fn check_expr_struct( . &self, . expr: &hir::Expr<'_>, . expected: Expectation<'tcx>, . qpath: &QPath<'_>, . fields: &'tcx [hir::ExprField<'tcx>], . base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>, . ) -> Ty<'tcx> { . // Find the relevant variant 58,420 ( 0.00%) let (variant, adt_ty) = if let Some(variant_ty) = self.check_struct_path(qpath, expr.hir_id) . { . variant_ty . } else { . self.check_struct_fields_on_error(fields, base_expr); . return self.tcx.ty_error(); . }; . . // Prohibit struct expressions when non-exhaustive flag is set. . let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type"); 5,856 ( 0.00%) if !adt.did.is_local() && variant.is_field_list_non_exhaustive() { . self.tcx . .sess . .emit_err(StructExprNonExhaustive { span: expr.span, what: adt.variant_descr() }); . } . 81,788 ( 0.00%) self.check_expr_struct_fields( . adt_ty, . expected, . expr.hir_id, 17,526 ( 0.00%) qpath.span(), . variant, . fields, . base_expr, 11,684 ( 0.00%) expr.span, . ); . 40,894 ( 0.00%) self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized); . adt_ty . } . 81,788 ( 0.00%) fn check_expr_struct_fields( . &self, . adt_ty: Ty<'tcx>, . expected: Expectation<'tcx>, . expr_id: hir::HirId, . span: Span, . variant: &'tcx ty::VariantDef, . ast_fields: &'tcx [hir::ExprField<'tcx>], . base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>, . expr_span: Span, . ) { 11,684 ( 0.00%) let tcx = self.tcx; . . let adt_ty_hint = self 11,684 ( 0.00%) .expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty]) . .get(0) . .cloned() . .unwrap_or(adt_ty); . // re-link the regions that EIfEO can erase. . self.demand_eqtype(span, adt_ty_hint, adt_ty); . 11,684 ( 0.00%) let (substs, adt_kind, kind_name) = match adt_ty.kind() { 11,684 ( 0.00%) ty::Adt(adt, substs) => (substs, adt.adt_kind(), adt.variant_descr()), . _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields"), . }; . . let mut remaining_fields = variant . .fields . .iter() . .enumerate() 105,150 ( 0.00%) .map(|(i, field)| (field.ident(tcx).normalize_to_macros_2_0(), (i, field))) . .collect::>(); . . let mut seen_fields = FxHashMap::default(); . . let mut error_happened = false; . . // Type-check each field. . for field in ast_fields { 233,672 ( 0.01%) let ident = tcx.adjust_ident(field.ident, variant.def_id); 52,575 ( 0.00%) let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) { 52,575 ( 0.00%) seen_fields.insert(ident, field.span); . self.write_field_index(field.hir_id, i); . . // We don't look at stability attributes on . // struct-like enums (yet...), but it's definitely not . // a bug to have constructed one. 17,525 ( 0.00%) if adt_kind != AdtKind::Enum { 157,725 ( 0.01%) tcx.check_stability(v_field.did, Some(expr_id), field.span, None); . } . 52,575 ( 0.00%) self.field_ty(field.span, v_field, substs) . } else { . error_happened = true; . if let Some(prev_span) = seen_fields.get(&ident) { . tcx.sess.emit_err(FieldMultiplySpecifiedInInitializer { . span: field.ident.span, . prev_span: *prev_span, . ident, . }); -- line 1402 ---------------------------------------- -- line 1406 ---------------------------------------- . ); . } . . tcx.ty_error() . }; . . // Make sure to give a type to the field even if there's . // an error, so we can continue type-checking. 87,625 ( 0.00%) self.check_expr_coercable_to_type(&field.expr, field_type, None); . } . . // Make sure the programmer specified correct number of fields. . if kind_name == "union" { . if ast_fields.len() != 1 { . struct_span_err!( . tcx.sess, . span, -- line 1422 ---------------------------------------- -- line 1425 ---------------------------------------- . ) . .emit(); . } . } . . // If check_expr_struct_fields hit an error, do not attempt to populate . // the fields with the base_expr. This could cause us to hit errors later . // when certain fields are assumed to exist that in fact do not. 11,684 ( 0.00%) if error_happened { . return; . } . 17,526 ( 0.00%) if let Some(base_expr) = base_expr { . // FIXME: We are currently creating two branches here in order to maintain . // consistency. But they should be merged as much as possible. . let fru_tys = if self.tcx.features().type_changing_struct_update { . let base_ty = self.check_expr(base_expr); . match adt_ty.kind() { . ty::Adt(adt, substs) if adt.is_struct() => { . match base_ty.kind() { . ty::Adt(base_adt, base_subs) if adt == base_adt => { -- line 1445 ---------------------------------------- -- line 1528 ---------------------------------------- . return self . .tcx . .sess . .emit_err(FunctionalRecordUpdateOnNonStruct { span: base_expr.span }); . } . } . }; . self.typeck_results.borrow_mut().fru_field_types_mut().insert(expr_id, fru_tys); 5,842 ( 0.00%) } else if kind_name != "union" && !remaining_fields.is_empty() { . let inaccessible_remaining_fields = remaining_fields.iter().any(|(_, (_, field))| { . !field.vis.is_accessible_from(tcx.parent_module(expr_id).to_def_id(), tcx) . }); . . if inaccessible_remaining_fields { . self.report_inaccessible_fields(adt_ty, span); . } else { . self.report_missing_fields(adt_ty, span, remaining_fields); . } . } 58,420 ( 0.00%) } . . fn check_struct_fields_on_error( . &self, . fields: &'tcx [hir::ExprField<'tcx>], . base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>, . ) { . for field in fields { . self.check_expr(&field.expr); -- line 1555 ---------------------------------------- -- line 1805 ---------------------------------------- . names.iter().take(limit).map(|n| format!("`{}`", n)).collect::>().join(", "); . if names.len() > limit { . display = format!("{} ... and {} others", display, names.len() - limit); . } . display . } . . // Check field access expressions 840 ( 0.00%) fn check_field( . &self, . expr: &'tcx hir::Expr<'tcx>, . base: &'tcx hir::Expr<'tcx>, . field: Ident, . ) -> Ty<'tcx> { . debug!("check_field(expr: {:?}, base: {:?}, field: {:?})", expr, base, field); . let expr_t = self.check_expr(base); 350 ( 0.00%) let expr_t = self.structurally_resolved_type(base.span, expr_t); 140 ( 0.00%) let mut private_candidate = None; 70 ( 0.00%) let mut autoderef = self.autoderef(expr.span, expr_t); 480 ( 0.00%) while let Some((base_t, _)) = autoderef.next() { . debug!("base_t: {:?}", base_t); 462 ( 0.00%) match base_t.kind() { 207 ( 0.00%) ty::Adt(base_def, substs) if !base_def.is_enum() => { . debug!("struct named {:?}", base_t); 552 ( 0.00%) let (ident, def_scope) = 828 ( 0.00%) self.tcx.adjust_ident_and_get_scope(field, base_def.did, self.body_id); 138 ( 0.00%) let fields = &base_def.non_enum_variant().fields; . if let Some(index) = fields . .iter() 2,644 ( 0.00%) .position(|f| f.ident(self.tcx).normalize_to_macros_2_0() == ident) . { . let field = &fields[index]; 207 ( 0.00%) let field_ty = self.field_ty(expr.span, field, substs); . // Save the index of all fields regardless of their visibility in case . // of error recovery. . self.write_field_index(expr.hir_id, index); . let adjustments = self.adjust_steps(&autoderef); 69 ( 0.00%) if field.vis.is_accessible_from(def_scope, self.tcx) { 690 ( 0.00%) self.apply_adjustments(base, adjustments); 1,242 ( 0.00%) self.register_predicates(autoderef.into_obligations()); . 966 ( 0.00%) self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None); . return field_ty; . } . private_candidate = Some((adjustments, base_def.did, field_ty)); . } . } . ty::Tuple(tys) => { 2 ( 0.00%) let fstr = field.as_str(); 3 ( 0.00%) if let Ok(index) = fstr.parse::() { 2 ( 0.00%) if fstr == index.to_string() { 3 ( 0.00%) if let Some(field_ty) = tys.get(index) { . let adjustments = self.adjust_steps(&autoderef); 9 ( 0.00%) self.apply_adjustments(base, adjustments); 18 ( 0.00%) self.register_predicates(autoderef.into_obligations()); . . self.write_field_index(expr.hir_id, index); 4 ( 0.00%) return field_ty.expect_ty(); . } . } . } . } . _ => {} . } . } . self.structurally_resolved_type(autoderef.span(), autoderef.final_ty(false)); -- line 1870 ---------------------------------------- -- line 1890 ---------------------------------------- . E0610, . "`{}` is a primitive type and therefore doesn't have fields", . expr_t . ) . .emit(); . } . . self.tcx().ty_error() 770 ( 0.00%) } . . fn suggest_await_on_field_access( . &self, . err: &mut DiagnosticBuilder<'_>, . field_ident: Ident, . base: &'tcx hir::Expr<'tcx>, . ty: Ty<'tcx>, . ) { -- line 1906 ---------------------------------------- -- 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); . 11 ( 0.00%) if base_t.references_error() { . base_t 11 ( 0.00%) } else if idx_t.references_error() { . idx_t . } else { 66 ( 0.00%) let base_t = self.structurally_resolved_type(base.span, base_t); 22 ( 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 ---------------------------------------- 682,302 ( 0.03%) -------------------------------------------------------------------------------- -- 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 . // . 3,573,636 ( 0.14%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 2,680,227 ( 0.11%) 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. 75,028 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 112,542 ( 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) { 912,155 ( 0.04%) libc::free(ptr as *mut libc::c_void) . } . . #[inline] . unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { 146,400 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 292,800 ( 0.01%) libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8 . } else { . realloc_fallback(self, ptr, layout, new_size) . } . } . } . . cfg_if::cfg_if! { . if #[cfg(any( -- line 56 ---------------------------------------- -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/build/expr/as_operand.rs -------------------------------------------------------------------------------- Ir -- line 15 ---------------------------------------- . /// please do *not* return it from functions to avoid bad . /// miscompiles. . crate fn as_local_operand( . &mut self, . block: BasicBlock, . expr: &Expr<'tcx>, . ) -> BlockAnd> { . let local_scope = self.local_scope(); 2,516 ( 0.00%) self.as_operand(block, Some(local_scope), expr, None) . } . . /// Returns an operand suitable for use until the end of the current scope expression and . /// suitable also to be passed as function arguments. . /// . /// The operand returned from this function will *not be valid* after an ExprKind::Scope is . /// passed, so please do *not* return it from functions to avoid bad miscompiles. Returns an . /// operand suitable for use as a call argument. This is almost always equivalent to -- line 31 ---------------------------------------- -- line 72 ---------------------------------------- . /// . /// See #68034 for more details. . crate fn as_local_call_operand( . &mut self, . block: BasicBlock, . expr: &Expr<'tcx>, . ) -> BlockAnd> { . let local_scope = self.local_scope(); 1,680 ( 0.00%) self.as_call_operand(block, Some(local_scope), expr) . } . . /// Compile `expr` into a value that can be used as an operand. . /// If `expr` is a place like `x`, this will introduce a . /// temporary `tmp = x`, so that we capture the value of `x` at . /// this time. . /// . /// If we end up needing to create a temporary, then we will use -- line 88 ---------------------------------------- -- line 89 ---------------------------------------- . /// `local_info` as its `LocalInfo`, unless `as_temporary` . /// has already assigned it a non-`None` `LocalInfo`. . /// Normally, you should use `None` for `local_info` . /// . /// The operand is known to be live until the end of `scope`. . /// . /// Like `as_local_call_operand`, except that the argument will . /// not be valid once `scope` ends. 757,310 ( 0.03%) crate fn as_operand( . &mut self, . mut block: BasicBlock, . scope: Option, . expr: &Expr<'tcx>, . local_info: Option>>, . ) -> BlockAnd> { . debug!("as_operand(block={:?}, expr={:?} local_info={:?})", block, expr, local_info); . let this = self; . 490,106 ( 0.02%) if let ExprKind::Scope { region_scope, lint_level, value } = expr.kind { 75,118 ( 0.00%) let source_info = this.source_info(expr.span); . let region_scope = (region_scope, source_info); . return this.in_scope(region_scope, lint_level, |this| { 488,267 ( 0.02%) this.as_operand(block, scope, &this.thir[value], local_info) . }); . } . . let category = Category::of(&expr.kind).unwrap(); . debug!("as_operand: category={:?} for={:?}", category, expr.kind); . match category { . Category::Constant => { 65,163 ( 0.00%) let constant = this.as_constant(expr); . block.and(Operand::Constant(Box::new(constant))) . } . Category::Place | Category::Rvalue(..) => { . let operand = unpack!(block = this.as_temp(block, scope, expr, Mutability::Mut)); 32,902 ( 0.00%) if this.local_decls[operand].local_info.is_none() { 32,902 ( 0.00%) this.local_decls[operand].local_info = local_info; . } 16,451 ( 0.00%) block.and(Operand::Move(Place::from(operand))) . } . } 698,030 ( 0.03%) } . 8,658 ( 0.00%) crate fn as_call_operand( . &mut self, . mut block: BasicBlock, . scope: Option, . expr: &Expr<'tcx>, . ) -> BlockAnd> { . debug!("as_call_operand(block={:?}, expr={:?})", block, expr); . let this = self; . 4,308 ( 0.00%) if let ExprKind::Scope { region_scope, lint_level, value } = expr.kind { 660 ( 0.00%) let source_info = this.source_info(expr.span); . let region_scope = (region_scope, source_info); . return this.in_scope(region_scope, lint_level, |this| { 3,630 ( 0.00%) this.as_call_operand(block, scope, &this.thir[value]) . }); . } . 336 ( 0.00%) let tcx = this.tcx; . 1,344 ( 0.00%) if tcx.features().unsized_fn_params { . let ty = expr.ty; . let span = expr.span; . let param_env = this.param_env; . . if !ty.is_sized(tcx.at(span), param_env) { . // !sized means !copy, so this is an unsized move . assert!(!ty.is_copy_modulo_regions(tcx.at(span), param_env)); . -- line 159 ---------------------------------------- -- line 171 ---------------------------------------- . projection: tcx.intern_place_elems(&[PlaceElem::Deref]), . }; . . return block.and(Operand::Move(place)); . } . } . } . 3,024 ( 0.00%) this.as_operand(block, scope, expr, None) 5,328 ( 0.00%) } . } 390,382 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/mod.rs -------------------------------------------------------------------------------- Ir -- line 26 ---------------------------------------- . pub struct UnmatchedBrace { . pub expected_delim: token::DelimToken, . pub found_delim: Option, . pub found_span: Span, . pub unclosed_span: Option, . pub candidate_span: Option, . } . 56 ( 0.00%) crate fn parse_token_trees<'a>( . sess: &'a ParseSess, . src: &'a str, . start_pos: BytePos, . override_span: Option, . ) -> (PResult<'a, TokenStream>, Vec) { . StringReader { sess, start_pos, pos: start_pos, end_src_index: src.len(), src, override_span } . .into_token_trees() 36 ( 0.00%) } . . struct StringReader<'a> { . sess: &'a ParseSess, . /// Initial position, read-only. . start_pos: BytePos, . /// The absolute offset within the source_map of the current character. . pos: BytePos, . /// Stop reading src at this index. -- line 50 ---------------------------------------- -- line 51 ---------------------------------------- . end_src_index: usize, . /// Source text to tokenize. . src: &'a str, . override_span: Option, . } . . impl<'a> StringReader<'a> { . fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span { 159,568 ( 0.01%) self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi)) . } . . /// Returns the next token, and info about preceding whitespace, if any. 882,805 ( 0.03%) fn next_token(&mut self) -> (Spacing, Token) { . let mut spacing = Spacing::Joint; . . // Skip `#!` at the start of the file 252,230 ( 0.01%) let start_src_index = self.src_index(self.pos); 378,345 ( 0.01%) let text: &str = &self.src[start_src_index..self.end_src_index]; . let is_beginning_of_file = self.pos == self.start_pos; 126,115 ( 0.00%) if is_beginning_of_file { 16 ( 0.00%) if let Some(shebang_len) = rustc_lexer::strip_shebang(text) { . self.pos = self.pos + BytePos::from_usize(shebang_len); . spacing = Spacing::Alone; . } . } . . // Skip trivial (whitespace & comments) tokens . loop { 248,667 ( 0.01%) let start_src_index = self.src_index(self.pos); 562,173 ( 0.02%) let text: &str = &self.src[start_src_index..self.end_src_index]; . 187,391 ( 0.01%) if text.is_empty() { . let span = self.mk_sp(self.pos, self.pos); 20 ( 0.00%) return (spacing, Token::new(token::Eof, span)); . } . 562,161 ( 0.02%) let token = rustc_lexer::first_token(text); . 374,774 ( 0.01%) let start = self.pos; 187,387 ( 0.01%) self.pos = self.pos + BytePos::from_usize(token.len); . . debug!("next_token: {:?}({:?})", token.kind, self.str_from(start)); . 1,499,420 ( 0.06%) match self.cook_lexer_token(token.kind, start) { 1,008,888 ( 0.04%) Some(kind) => { . let span = self.mk_sp(start, self.pos); 756,666 ( 0.03%) return (spacing, Token::new(kind, span)); . } . None => spacing = Spacing::Alone, . } . } 1,135,035 ( 0.04%) } . . /// Report a fatal lexical error with a given span. . fn fatal_span(&self, sp: Span, m: &str) -> FatalError { . self.sess.span_diagnostic.span_fatal(sp, m) . } . . /// Report a lexical error with a given span. . fn err_span(&self, sp: Span, m: &str) { -- line 110 ---------------------------------------- -- line 130 ---------------------------------------- . ) -> DiagnosticBuilder<'a> { . self.sess . .span_diagnostic . .struct_span_fatal(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c))) . } . . /// Detect usages of Unicode codepoints changing the direction of the text on screen and loudly . /// complain about it. 644 ( 0.00%) fn lint_unicode_text_flow(&self, start: BytePos) { . // Opening delimiter of the length 2 is not included into the comment text. . let content_start = start + BytePos(2); . let content = self.str_from(content_start); . if contains_text_flow_control_chars(content) { . let span = self.mk_sp(start, self.pos); . self.sess.buffer_lint_with_diagnostic( . &TEXT_DIRECTION_CODEPOINT_IN_COMMENT, . span, . ast::CRATE_NODE_ID, . "unicode codepoint changing visible direction of text present in comment", . BuiltinLintDiagnostics::UnicodeTextFlow(span, content.to_string()), . ); . } 736 ( 0.00%) } . . /// Turns simple `rustc_lexer::TokenKind` enum into a rich . /// `rustc_ast::TokenKind`. This turns strings into interned . /// symbols and runs additional validation. . fn cook_lexer_token(&self, token: rustc_lexer::TokenKind, start: BytePos) -> Option { 936,935 ( 0.04%) Some(match token { 173 ( 0.00%) rustc_lexer::TokenKind::LineComment { doc_style } => { . // Skip non-doc comments 589 ( 0.00%) let doc_style = if let Some(doc_style) = doc_style { . doc_style . } else { . self.lint_unicode_text_flow(start); . return None; . }; . . // Opening delimiter of the length 3 is not included into the symbol. . let content_start = start + BytePos(3); . let content = self.str_from(content_start); 405 ( 0.00%) self.cook_doc_comment(content_start, content, CommentKind::Line, doc_style) . } . rustc_lexer::TokenKind::BlockComment { doc_style, terminated } => { . if !terminated { . let msg = match doc_style { . Some(_) => "unterminated block doc-comment", . None => "unterminated block comment", . }; . let last_bpos = self.pos; -- line 179 ---------------------------------------- -- line 198 ---------------------------------------- . let content_end = self.pos - BytePos(if terminated { 2 } else { 0 }); . let content = self.str_from_to(content_start, content_end); . self.cook_doc_comment(content_start, content, CommentKind::Block, doc_style) . } . rustc_lexer::TokenKind::Whitespace => return None, . rustc_lexer::TokenKind::Ident . | rustc_lexer::TokenKind::RawIdent . | rustc_lexer::TokenKind::UnknownPrefix => { 133,796 ( 0.01%) let is_raw_ident = token == rustc_lexer::TokenKind::RawIdent; 167,245 ( 0.01%) let is_unknown_prefix = token == rustc_lexer::TokenKind::UnknownPrefix; . let mut ident_start = start; 66,898 ( 0.00%) if is_raw_ident { . ident_start = ident_start + BytePos(2); . } 100,347 ( 0.00%) if is_unknown_prefix { . self.report_unknown_prefix(start); . } 167,245 ( 0.01%) let sym = nfc_normalize(self.str_from(ident_start)); . let span = self.mk_sp(start, self.pos); 133,796 ( 0.01%) self.sess.symbol_gallery.insert(sym, span); 66,898 ( 0.00%) if is_raw_ident { . if !sym.can_be_raw() { . self.err_span(span, &format!("`{}` cannot be a raw identifier", sym)); . } . self.sess.raw_identifier_spans.borrow_mut().push(span); . } 234,143 ( 0.01%) token::Ident(sym, is_raw_ident) . } . rustc_lexer::TokenKind::InvalidIdent . // Do not recover an identifier with emoji if the codepoint is a confusable . // with a recoverable substitution token, like `➖`. . if UNICODE_ARRAY . .iter() . .find(|&&(c, _, _)| { . let sym = self.str_from(start); -- line 232 ---------------------------------------- -- line 234 ---------------------------------------- . }) . .is_none() => . { . let sym = nfc_normalize(self.str_from(start)); . let span = self.mk_sp(start, self.pos); . self.sess.bad_unicode_identifiers.borrow_mut().entry(sym).or_default().push(span); . token::Ident(sym, false) . } 342,528 ( 0.01%) rustc_lexer::TokenKind::Literal { kind, suffix_start } => { . let suffix_start = start + BytePos(suffix_start as u32); . let (kind, symbol) = self.cook_lexer_literal(start, suffix_start, kind); 64,224 ( 0.00%) let suffix = if suffix_start < self.pos { . let string = self.str_from(suffix_start); . if string == "_" { . self.sess . .span_diagnostic . .struct_span_warn( . self.mk_sp(suffix_start, self.pos), . "underscore literal suffix is not allowed", . ) -- line 253 ---------------------------------------- -- line 264 ---------------------------------------- . .emit(); . None . } else { . Some(Symbol::intern(string)) . } . } else { . None . }; 171,264 ( 0.01%) token::Literal(token::Lit { kind, symbol, suffix }) . } 50 ( 0.00%) rustc_lexer::TokenKind::Lifetime { starts_with_number } => { . // Include the leading `'` in the real identifier, for macro . // expansion purposes. See #12512 for the gory details of why . // this is necessary. . let lifetime_name = self.str_from(start); 25 ( 0.00%) if starts_with_number { . self.err_span_(start, self.pos, "lifetimes cannot start with a number"); . } 75 ( 0.00%) let ident = Symbol::intern(lifetime_name); 100 ( 0.00%) token::Lifetime(ident) . } . rustc_lexer::TokenKind::Semi => token::Semi, . rustc_lexer::TokenKind::Comma => token::Comma, . rustc_lexer::TokenKind::Dot => token::Dot, . rustc_lexer::TokenKind::OpenParen => token::OpenDelim(token::Paren), . rustc_lexer::TokenKind::CloseParen => token::CloseDelim(token::Paren), . rustc_lexer::TokenKind::OpenBrace => token::OpenDelim(token::Brace), . rustc_lexer::TokenKind::CloseBrace => token::CloseDelim(token::Brace), -- line 291 ---------------------------------------- -- line 324 ---------------------------------------- . err.help("source files must contain UTF-8 encoded text, unexpected null bytes might occur when a different encoding is used"); . } . err.emit(); . token? . } . }) . } . 972 ( 0.00%) fn cook_doc_comment( . &self, . content_start: BytePos, . content: &str, . comment_kind: CommentKind, . doc_style: DocStyle, . ) -> TokenKind { 81 ( 0.00%) if content.contains('\r') { . for (idx, _) in content.char_indices().filter(|&(_, c)| c == '\r') { . self.err_span_( . content_start + BytePos(idx as u32), . content_start + BytePos(idx as u32 + 1), . match comment_kind { . CommentKind::Line => "bare CR not allowed in doc-comment", . CommentKind::Block => "bare CR not allowed in block doc-comment", . }, -- line 347 ---------------------------------------- -- line 349 ---------------------------------------- . } . } . . let attr_style = match doc_style { . DocStyle::Outer => AttrStyle::Outer, . DocStyle::Inner => AttrStyle::Inner, . }; . 243 ( 0.00%) token::DocComment(comment_kind, attr_style, Symbol::intern(content)) 1,215 ( 0.00%) } . . fn cook_lexer_literal( . &self, . start: BytePos, . suffix_start: BytePos, . kind: rustc_lexer::LiteralKind, . ) -> (token::LitKind, Symbol) { . // prefix means `"` or `br"` or `r###"`, ... . let (lit_kind, mode, prefix_len, postfix_len) = match kind { 1,946 ( 0.00%) rustc_lexer::LiteralKind::Char { terminated } => { 1,946 ( 0.00%) if !terminated { . self.sess.span_diagnostic.span_fatal_with_code( . self.mk_sp(start, suffix_start), . "unterminated character literal", . error_code!(E0762), . ) . } . (token::Char, Mode::Char, 1, 1) // ' ' . } 11 ( 0.00%) rustc_lexer::LiteralKind::Byte { terminated } => { 11 ( 0.00%) if !terminated { . self.sess.span_diagnostic.span_fatal_with_code( . self.mk_sp(start + BytePos(1), suffix_start), . "unterminated byte constant", . error_code!(E0763), . ) . } . (token::Byte, Mode::Byte, 2, 1) // b' ' . } 20 ( 0.00%) rustc_lexer::LiteralKind::Str { terminated } => { 20 ( 0.00%) if !terminated { . self.sess.span_diagnostic.span_fatal_with_code( . self.mk_sp(start, suffix_start), . "unterminated double quote string", . error_code!(E0765), . ) . } . (token::Str, Mode::Str, 1, 1) // " " . } -- line 397 ---------------------------------------- -- line 410 ---------------------------------------- . let n = u32::from(n_hashes); . (token::StrRaw(n_hashes), Mode::RawStr, 2 + n, 1 + n) // r##" "## . } . rustc_lexer::LiteralKind::RawByteStr { n_hashes, err } => { . self.report_raw_str_error(start, err); . let n = u32::from(n_hashes); . (token::ByteStrRaw(n_hashes), Mode::RawByteStr, 3 + n, 1 + n) // br##" "## . } 38,862 ( 0.00%) rustc_lexer::LiteralKind::Int { base, empty_int } => { 19,431 ( 0.00%) return if empty_int { . self.sess . .span_diagnostic . .struct_span_err_with_code( . self.mk_sp(start, suffix_start), . "no valid digits found for number", . error_code!(E0768), . ) . .emit(); . (token::Integer, sym::integer(0)) . } else { . self.validate_int_literal(base, start, suffix_start); 58,293 ( 0.00%) (token::Integer, self.symbol_from_to(start, suffix_start)) . }; . } . rustc_lexer::LiteralKind::Float { base, empty_exponent } => { . if empty_exponent { . self.err_span_(start, self.pos, "expected at least one digit in exponent"); . } . . match base { -- line 439 ---------------------------------------- -- line 452 ---------------------------------------- . } . . let id = self.symbol_from_to(start, suffix_start); . return (token::Float, id); . } . }; . let content_start = start + BytePos(prefix_len); . let content_end = suffix_start - BytePos(postfix_len); 5,931 ( 0.00%) let id = self.symbol_from_to(content_start, content_end); . self.validate_literal_escape(mode, content_start, content_end, prefix_len, postfix_len); . (lit_kind, id) . } . . #[inline] . fn src_index(&self, pos: BytePos) -> usize { . (pos - self.start_pos).to_usize() . } . . /// Slice of the source text from `start` up to but excluding `self.pos`, . /// meaning the slice does not include the character `self.ch`. . fn str_from(&self, start: BytePos) -> &str { 202,565 ( 0.01%) self.str_from_to(start, self.pos) . } . . /// As symbol_from, with an explicit endpoint. . fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol { . debug!("taking an ident from {:?} to {:?}", start, end); 159,741 ( 0.01%) Symbol::intern(self.str_from_to(start, end)) . } . . /// Slice of the source text spanning from `start` up to but excluding `end`. 57,032 ( 0.00%) fn str_from_to(&self, start: BytePos, end: BytePos) -> &str { . &self.src[self.src_index(start)..self.src_index(end)] 228,128 ( 0.01%) } . . fn report_raw_str_error(&self, start: BytePos, opt_err: Option) { . match opt_err { . Some(RawStrError::InvalidStarter { bad_char }) => { . self.report_non_started_raw_string(start, bad_char) . } . Some(RawStrError::NoTerminator { expected, found, possible_terminator_offset }) => self . .report_unterminated_raw_string(start, expected, possible_terminator_offset, found), -- line 493 ---------------------------------------- -- line 609 ---------------------------------------- . fn validate_literal_escape( . &self, . mode: Mode, . content_start: BytePos, . content_end: BytePos, . prefix_len: u32, . postfix_len: u32, . ) { 11,862 ( 0.00%) let lit_content = self.str_from_to(content_start, content_end); 103,526 ( 0.00%) unescape::unescape_literal(lit_content, mode, &mut |range, result| { . // Here we only check for errors. The actual unescaping is done later. 15,008 ( 0.00%) if let Err(err) = result { . let span_with_quotes = self . .mk_sp(content_start - BytePos(prefix_len), content_end + BytePos(postfix_len)); . let (start, end) = (range.start as u32, range.end as u32); . let lo = content_start + BytePos(start); . let hi = lo + BytePos(end - start); . let span = self.mk_sp(lo, hi); . emit_unescape_error( . &self.sess.span_diagnostic, -- line 628 ---------------------------------------- -- line 629 ---------------------------------------- . lit_content, . span_with_quotes, . span, . mode, . range, . err, . ); . } 67,536 ( 0.00%) }); . } . . fn validate_int_literal(&self, base: Base, content_start: BytePos, content_end: BytePos) { 77,724 ( 0.00%) let base = match base { . Base::Binary => 2, . Base::Octal => 8, . _ => return, . }; . let s = self.str_from_to(content_start + BytePos(2), content_end); . for (idx, c) in s.char_indices() { . let idx = idx as u32; . if c != '_' && c.to_digit(base).is_none() { -- line 649 ---------------------------------------- -- line 650 ---------------------------------------- . let lo = content_start + BytePos(2 + idx); . let hi = content_start + BytePos(2 + idx + c.len_utf8() as u32); . self.err_span_(lo, hi, &format!("invalid digit for a base {} literal", base)); . } . } . } . } . 301,041 ( 0.01%) pub fn nfc_normalize(string: &str) -> Symbol { . use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization}; 66,898 ( 0.00%) match is_nfc_quick(string.chars()) { 334,490 ( 0.01%) IsNormalized::Yes => Symbol::intern(string), . _ => { . let normalized_str: String = string.chars().nfc().collect(); . Symbol::intern(&normalized_str) . } . } . } 602,870 ( 0.02%) -------------------------------------------------------------------------------- -- 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}; . 6,952 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum CommentKind { . Line, . Block, . } . 71 ( 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. 101,531 ( 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, . } . 680 ( 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. 45,632 ( 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 { 15 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 27 ( 0.00%) let Lit { kind, symbol, suffix } = *self; . match kind { . Byte => write!(f, "b'{}'", symbol)?, . Char => write!(f, "'{}'", symbol)?, 3 ( 0.00%) 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 . )?, 6 ( 0.00%) Integer | Float | Bool | Err => write!(f, "{}", symbol)?, . } . 6 ( 0.00%) if let Some(suffix) = suffix { . write!(f, "{}", suffix)?; . } . . Ok(()) 15 ( 0.00%) } . } . . 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 } 273 ( 0.00%) } . } . 120 ( 0.00%) pub fn ident_can_begin_expr(name: Symbol, span: Span, is_raw: bool) -> bool { 210 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 105 ( 0.00%) !ident_token.is_reserved_ident() . || ident_token.is_path_segment_keyword() . || [ . kw::Async, . kw::Do, . kw::Box, . kw::Break, . kw::Const, . kw::Continue, -- line 152 ---------------------------------------- -- line 161 ---------------------------------------- . kw::True, . kw::Try, . kw::Unsafe, . kw::While, . kw::Yield, . kw::Static, . ] . .contains(&name) 150 ( 0.00%) } . . fn ident_can_begin_type(name: Symbol, span: Span, is_raw: bool) -> bool { 156 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 56 ( 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) . } . 12,356,995 ( 0.49%) #[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, 48,354 ( 0.00%) BinOp(BinOpToken), 78 ( 0.00%) BinOpEq(BinOpToken), . . /* Structural symbols */ . At, . Dot, . DotDot, . DotDotDot, . DotDotEq, . Comma, -- line 203 ---------------------------------------- -- 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., `{`). 161,490 ( 0.01%) OpenDelim(DelimToken), . /// A closing delimiter (e.g., `}`). 120,591 ( 0.00%) CloseDelim(DelimToken), . . /* Literals */ 65,617 ( 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. 34,669 ( 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. 108 ( 0.00%) Lifetime(Symbol), . 9 ( 0.00%) Interpolated(Lrc), . . /// A doc comment token. . /// `Symbol` is the doc comment's data excluding its "quotes" (`///`, `/**`, etc) . /// similarly to symbols in string literal tokens. 243 ( 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); . 418,541 ( 0.02%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Token { 3,203 ( 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`. 14,634 ( 0.00%) pub fn break_two_token_op(&self) -> Option<(TokenKind, TokenKind)> { 58,554 ( 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), 14,632 ( 0.00%) _ => return None, . }) 14,634 ( 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 { 140 ( 0.00%) matches!(self, Gt | Ge | BinOp(Shr) | BinOpEq(Shr)) 32 ( 0.00%) } . } . . impl Token { 151,989 ( 0.01%) pub fn new(kind: TokenKind, span: Span) -> Self { 457,013 ( 0.02%) Token { kind, span } 151,989 ( 0.01%) } . . /// Some token that will be thrown away later. 274 ( 0.00%) pub fn dummy() -> Self { . Token::new(TokenKind::Question, DUMMY_SP) 274 ( 0.00%) } . . /// Recovers a `Token` from an `Ident`. This creates a raw identifier if necessary. . pub fn from_ast_ident(ident: Ident) -> Self { 152 ( 0.00%) Token::new(Ident(ident.name, ident.is_raw_guess()), ident.span) . } . . /// Return this token by value and leave a dummy token in its place. 97,777 ( 0.00%) pub fn take(&mut self) -> Self { . mem::replace(self, Token::dummy()) 97,777 ( 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 { 522 ( 0.00%) match &self.kind { . Interpolated(nt) => nt.span(), 261 ( 0.00%) _ => self.span, . } 261 ( 0.00%) } . . pub fn is_op(&self) -> bool { 293,331 ( 0.01%) !matches!( 97,777 ( 0.00%) self.kind, . OpenDelim(..) . | CloseDelim(..) . | Literal(..) . | DocComment(..) . | Ident(..) . | Lifetime(..) . | Interpolated(..) . | Eof . ) 97,777 ( 0.00%) } . . pub fn is_like_plus(&self) -> bool { 1,801 ( 0.00%) matches!(self.kind, BinOp(Plus) | BinOpEq(Plus)) 359 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of an expression. 48 ( 0.00%) pub fn can_begin_expr(&self) -> bool { 240 ( 0.00%) match self.uninterpolate().kind { 270 ( 0.00%) Ident(name, is_raw) => 90 ( 0.00%) ident_can_begin_expr(name, self.span, is_raw), // value name or keyword . OpenDelim(..) | // tuple, array or block . Literal(..) | // literal . Not | // operator not . BinOp(Minus) | // unary minus . BinOp(Star) | // dereference . BinOp(Or) | OrOr | // closure . BinOp(And) | // reference . AndAnd | // double reference -- line 371 ---------------------------------------- -- line 376 ---------------------------------------- . Lifetime(..) | // labeled loop . Pound => true, // expression attributes . Interpolated(ref nt) => matches!(**nt, NtLiteral(..) | . NtExpr(..) | . NtBlock(..) | . NtPath(..)), . _ => false, . } 96 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a type. 164 ( 0.00%) pub fn can_begin_type(&self) -> bool { 265 ( 0.00%) match self.uninterpolate().kind { 234 ( 0.00%) Ident(name, is_raw) => 26 ( 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, . } 246 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a const param. . pub fn can_begin_const_arg(&self) -> bool { 175 ( 0.00%) match self.kind { . OpenDelim(Brace) => true, . Interpolated(ref nt) => matches!(**nt, NtExpr(..) | NtBlock(..) | NtLiteral(..)), 35 ( 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. 43 ( 0.00%) pub fn can_begin_literal_maybe_minus(&self) -> bool { 345 ( 0.00%) match self.uninterpolate().kind { . Literal(..) | BinOp(Minus) => true, 104 ( 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, . } 86 ( 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. 38,487 ( 0.00%) pub fn uninterpolate(&self) -> Cow<'_, Token> { 721,608 ( 0.03%) match &self.kind { 18 ( 0.00%) 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), . } 38,487 ( 0.00%) } . . /// Returns an identifier if this token is an identifier. 179,606 ( 0.01%) pub fn ident(&self) -> Option<(Ident, /* is_raw */ bool)> { . let token = self.uninterpolate(); 534,827 ( 0.02%) match token.kind { 1,670,628 ( 0.07%) Ident(name, is_raw) => Some((Ident::new(name, token.span), is_raw)), . _ => None, . } 1,229,701 ( 0.05%) } . . /// Returns a lifetime identifier if this token is a lifetime. 277 ( 0.00%) pub fn lifetime(&self) -> Option { . let token = self.uninterpolate(); 876 ( 0.00%) match token.kind { 374 ( 0.00%) Lifetime(name) => Some(Ident::new(name, token.span)), . _ => None, . } 1,939 ( 0.00%) } . . /// Returns `true` if the token is an identifier. . pub fn is_ident(&self) -> bool { . self.ident().is_some() 6,367 ( 0.00%) } . . /// Returns `true` if the token is a lifetime. 161 ( 0.00%) pub fn is_lifetime(&self) -> bool { . self.lifetime().is_some() 322 ( 0.00%) } . . /// Returns `true` if the token is an identifier whose name is the given . /// string slice. 14,541 ( 0.00%) pub fn is_ident_named(&self, name: Symbol) -> bool { . self.ident().map_or(false, |(ident, _)| ident.name == name) 29,082 ( 0.00%) } . . /// Returns `true` if the token is an interpolated path. . fn is_path(&self) -> bool { 60,408 ( 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 { 50 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtBlock(..) = **nt { . return true; . } . } . false 25 ( 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) . } . 270 ( 0.00%) pub fn is_qpath_start(&self) -> bool { 30,474 ( 0.00%) self == &Lt || self == &BinOp(Shl) . } . 60,408 ( 0.00%) pub fn is_path_start(&self) -> bool { 90,538 ( 0.00%) self == &ModSep . || self.is_qpath_start() . || self.is_path() . || self.is_path_segment_keyword() 15,036 ( 0.00%) || self.is_ident() && !self.is_reserved_ident() 75,510 ( 0.00%) } . . /// Returns `true` if the token is a given keyword, `kw`. 28,744 ( 0.00%) pub fn is_keyword(&self, kw: Symbol) -> bool { . self.is_non_raw_ident_where(|id| id.name == kw) 57,488 ( 0.00%) } . 225 ( 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. 19 ( 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. 19 ( 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. 19 ( 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`. 225 ( 0.00%) pub fn is_bool_lit(&self) -> bool { 450 ( 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 { 764,065 ( 0.03%) match self.ident() { 15,002 ( 0.00%) Some((id, false)) => pred(id), . _ => false, . } 5 ( 0.00%) } . 343,740 ( 0.01%) pub fn glue(&self, joint: &Token) -> Option { 171,870 ( 0.01%) let kind = match self.kind { 309 ( 0.00%) Eq => match joint.kind { . Eq => EqEq, . Gt => FatArrow, . _ => return None, . }, 12 ( 0.00%) Lt => match joint.kind { . Eq => Le, . Lt => BinOp(Shl), . Le => BinOpEq(Shl), . BinOp(Minus) => LArrow, . _ => return None, . }, 57 ( 0.00%) Gt => match joint.kind { . Eq => Ge, . Gt => BinOp(Shr), . Ge => BinOpEq(Shr), . _ => return None, . }, 2 ( 0.00%) Not => match joint.kind { . Eq => Ne, . _ => return None, . }, 586 ( 0.00%) BinOp(op) => match joint.kind { . Eq => BinOpEq(op), 7 ( 0.00%) BinOp(And) if op == And => AndAnd, 15 ( 0.00%) BinOp(Or) if op == Or => OrOr, 35 ( 0.00%) Gt if op == Minus => RArrow, . _ => return None, . }, 42 ( 0.00%) Dot => match joint.kind { . Dot => DotDot, . DotDot => DotDotDot, . _ => return None, . }, 21 ( 0.00%) DotDot => match joint.kind { . Dot => DotDotDot, . Eq => DotDotEq, . _ => return None, . }, 216 ( 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, . }; . 3,770 ( 0.00%) Some(Token::new(kind, self.span.to(joint.span))) 309,366 ( 0.01%) } . } . . impl PartialEq for Token { . fn eq(&self, rhs: &TokenKind) -> bool { 703,706 ( 0.03%) 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. 56 ( 0.00%) pub fn from_symbol( . symbol: Symbol, . edition: impl FnOnce() -> Edition, . ) -> Option { 120 ( 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, . }) 56 ( 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 ---------------------------------------- 4,079,491 ( 0.16%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_borrowck/src/type_check/canonical.rs -------------------------------------------------------------------------------- Ir -- line 19 ---------------------------------------- . /// `op` and then executes all the further obligations that `op` . /// returns. This will yield a set of outlives constraints amongst . /// regions which are extracted and stored as having occurred at . /// `locations`. . /// . /// **Any `rustc_infer::infer` operations that might generate region . /// constraints should occur within this method so that those . /// constraints can be properly localized!** 833,139 ( 0.03%) #[instrument(skip(self, category, op), level = "trace")] 1,018,381 ( 0.04%) pub(super) fn fully_perform_op( . &mut self, . locations: Locations, . category: ConstraintCategory, . op: Op, . ) -> Fallible . where . Op: type_op::TypeOp<'tcx, Output = R>, . Canonical<'tcx, Op>: ToUniverseInfo<'tcx>, . { 557,868 ( 0.02%) let old_universe = self.infcx.universe(); . 336,214 ( 0.01%) let TypeOpOutput { output, constraints, canonicalized_query } = 449,461 ( 0.02%) op.fully_perform(self.infcx)?; . 223,650 ( 0.01%) if let Some(data) = &constraints { . self.push_region_constraints(locations, category, data); . } . 223,650 ( 0.01%) let universe = self.infcx.universe(); . 111,825 ( 0.00%) if old_universe != universe { 39 ( 0.00%) let universe_info = match canonicalized_query { 12 ( 0.00%) Some(canonicalized_query) => canonicalized_query.to_universe_info(old_universe), . None => UniverseInfo::other(), . }; . for u in old_universe..universe { 10 ( 0.00%) self.borrowck_context . .constraints . .universe_causes 30 ( 0.00%) .insert(u + 1, universe_info.clone()); . } . } . . Ok(output) . } . . pub(super) fn instantiate_canonical_with_fresh_inference_vars( . &mut self, . span: Span, . canonical: &Canonical<'tcx, T>, . ) -> T . where . T: TypeFoldable<'tcx>, . { 276 ( 0.00%) let (instantiated, _) = 149 ( 0.00%) self.infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical); . 40 ( 0.00%) for u in 0..canonical.max_universe.as_u32() { . let info = UniverseInfo::other(); . self.borrowck_context . .constraints . .universe_causes . .insert(ty::UniverseIndex::from_u32(u), info); . } . . instantiated . } . 40 ( 0.00%) pub(super) fn prove_trait_ref( . &mut self, . trait_ref: ty::TraitRef<'tcx>, . locations: Locations, . category: ConstraintCategory, . ) { . self.prove_predicates( 71,293 ( 0.00%) Some(ty::Binder::dummy(ty::PredicateKind::Trait(ty::TraitPredicate { . trait_ref, . constness: ty::BoundConstness::NotConst, . polarity: ty::ImplPolarity::Positive, . }))), . locations, . category, . ); 32 ( 0.00%) } . 144,837 ( 0.01%) pub(super) fn normalize_and_prove_instantiated_predicates( . &mut self, . // Keep this parameter for now, in case we start using . // it in `ConstraintCategory` at some point. . _def_id: DefId, . instantiated_predicates: ty::InstantiatedPredicates<'tcx>, . locations: Locations, . ) { 177,023 ( 0.01%) for (predicate, span) in instantiated_predicates . .predicates . .into_iter() . .zip(instantiated_predicates.spans.into_iter()) . { . let predicate = self.normalize(predicate, locations); 2,792 ( 0.00%) self.prove_predicate(predicate, locations, ConstraintCategory::Predicate(span)); . } 128,744 ( 0.01%) } . . pub(super) fn prove_predicates( . &mut self, . predicates: impl IntoIterator>, . locations: Locations, . category: ConstraintCategory, . ) { 36,568 ( 0.00%) for predicate in predicates { . let predicate = predicate.to_predicate(self.tcx()); . debug!("prove_predicates(predicate={:?}, locations={:?})", predicate, locations,); . 201,044 ( 0.01%) self.prove_predicate(predicate, locations, category); . } . } . 372,860 ( 0.01%) #[instrument(skip(self), level = "debug")] . pub(super) fn prove_predicate( . &mut self, . predicate: ty::Predicate<'tcx>, . locations: Locations, . category: ConstraintCategory, . ) { 18,643 ( 0.00%) let param_env = self.param_env; . self.fully_perform_op( . locations, . category, 55,929 ( 0.00%) param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)), . ) . .unwrap_or_else(|NoSolution| { . span_mirbug!(self, NoSolution, "could not prove {:?}", predicate); . }) . } . 647,622 ( 0.03%) #[instrument(skip(self), level = "debug")] 1,017,651 ( 0.04%) pub(super) fn normalize(&mut self, value: T, location: impl NormalizeLocation) -> T . where . T: type_op::normalize::Normalizable<'tcx> + fmt::Display + Copy + 'tcx, . { 93,137 ( 0.00%) let param_env = self.param_env; 277,593 ( 0.01%) self.fully_perform_op( 380 ( 0.00%) location.to_locations(), . ConstraintCategory::Boring, . param_env.and(type_op::normalize::Normalize::new(value)), . ) . .unwrap_or_else(|NoSolution| { . span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value); . value . }) . } -- line 169 ---------------------------------------- 148,920 ( 0.01%) -------------------------------------------------------------------------------- -- 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 { 40,488 ( 0.00%) pub id: hir::ItemLocalId, 871,590 ( 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(), . ), . } . } . } . 3,958,407 ( 0.16%) #[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 { 17,101 ( 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. 119,707 ( 0.00%) pub fn span(&self, tcx: TyCtxt<'_>, scope_tree: &ScopeTree) -> Span { 34,202 ( 0.00%) let hir_id = match self.hir_id(scope_tree) { . Some(hir_id) => hir_id, . None => return DUMMY_SP, . }; 68,404 ( 0.00%) let span = tcx.hir().span(hir_id); 68,404 ( 0.00%) if let ScopeData::Remainder(first_statement_index) = self.data { 1,194 ( 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) . 1,592 ( 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. 395 ( 0.00%) if span.lo() <= stmt_span.lo() && stmt_span.lo() <= span.hi() { 764 ( 0.00%) return span.with_lo(stmt_span.lo()); . } . } . } . span 153,909 ( 0.01%) } . } . . 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 { 280,836 ( 0.01%) pub fn record_scope_parent(&mut self, child: Scope, parent: Option<(Scope, ScopeDepth)>) { . debug!("{:?}.parent = {:?}", child, parent); . 93,612 ( 0.00%) if let Some(p) = parent { . let prev = self.parent_map.insert(child, p); 46,673 ( 0.00%) assert!(prev.is_none()); . } . . // Record the destruction scopes for later so we can query them. 93,612 ( 0.00%) if let ScopeData::Destruction = child.data { . self.destruction_scopes.insert(child.item_local_id(), child); . } 184,596 ( 0.01%) } . 78,946 ( 0.00%) pub fn opt_destruction_scope(&self, n: hir::ItemLocalId) -> Option { . self.destruction_scopes.get(&n).cloned() 78,946 ( 0.00%) } . . pub fn record_var_scope(&mut self, var: hir::ItemLocalId, lifetime: Scope) { . debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime); 234 ( 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); 36 ( 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` 672 ( 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)) 672 ( 0.00%) } . . /// Returns the scope when the temp created by `expr_id` will be cleaned up. 547,596 ( 0.02%) pub fn temporary_scope(&self, expr_id: hir::ItemLocalId) -> Option { . // Check for a designated rvalue scope. 60 ( 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. 78,208 ( 0.00%) let mut id = Scope { id: expr_id, data: ScopeData::Node }; . 2,192,571 ( 0.09%) while let Some(&(p, _)) = self.parent_map.get(&id) { 726,245 ( 0.03%) match p.data { . ScopeData::Destruction => { . debug!("temporary_scope({:?}) = {:?} [enclosing]", expr_id, id); . return Some(id); . } 246,189 ( 0.01%) _ => id = p, . } . } . . debug!("temporary_scope({:?}) = None", expr_id); . None 625,824 ( 0.02%) } . . /// 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 ---------------------------------------- 1,531,689 ( 0.06%) -------------------------------------------------------------------------------- -- 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, . { 1,028,402 ( 0.04%) 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. 21 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd)] 1,154 ( 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 2,967 ( 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> { 8 ( 0.00%) encoder.emit_enum(|encoder| match *self { . RealFileName::LocalPath(ref local_path) => { 32 ( 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. 4 ( 0.00%) pub fn into_local_path(self) -> Option { 4 ( 0.00%) match self { . RealFileName::LocalPath(p) => Some(p), . RealFileName::Remapped { local_path: p, virtual_name: _ } => p, . } 6 ( 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 { 2,360 ( 0.00%) match self { . RealFileName::LocalPath(p) . | RealFileName::Remapped { local_path: _, virtual_name: p } => &p, . } 5 ( 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 { 4 ( 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> { 4 ( 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. 6,100 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)] 7,011 ( 0.00%) #[derive(Decodable, Encodable)] . pub enum FileName { . Real(RealFileName), . /// Call to `quote!`. . QuoteExpansion(u64), . /// Command line. . Anon(u64), . /// Hack in `src/librustc_ast/parse.rs`. . // FIXME(jseyfried) -- line 281 ---------------------------------------- -- 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 { 28 ( 0.00%) fn from(p: PathBuf) -> Self { 8 ( 0.00%) assert!(!p.to_string_lossy().ends_with('>')); 24 ( 0.00%) FileName::Real(RealFileName::LocalPath(p)) 28 ( 0.00%) } . } . 2 ( 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<'_> { 16 ( 0.00%) fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { . use FileName::*; 24 ( 0.00%) match *self.inner { . Real(ref name) => { 24 ( 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, ""), . } 20 ( 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::*; 1,176 ( 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. 4 ( 0.00%) pub fn prefer_local(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local } 8 ( 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 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 { 9 ( 0.00%) pub lo: BytePos, 9 ( 0.00%) pub hi: BytePos, . /// Information about where the macro came from, if this piece of . /// code was created by a macro expansion. 21 ( 0.00%) pub ctxt: SyntaxContext, 7 ( 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 { 538,354 ( 0.02%) self.lo.0 == 0 && self.hi.0 == 0 . } . /// Returns `true` if `self` fully encloses `other`. . pub fn contains(self, other: Self) -> bool { 168 ( 0.00%) 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 . // 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 { 17,784 ( 0.00%) fn partial_cmp(&self, rhs: &Self) -> Option { 13,338 ( 0.00%) PartialOrd::partial_cmp(&self.data(), &rhs.data()) 17,784 ( 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] 155,403 ( 0.01%) pub fn with_lo(self, lo: BytePos) -> Span { . self.data().with_lo(lo) 103,602 ( 0.00%) } . #[inline] 448 ( 0.00%) pub fn hi(self) -> BytePos { . self.data().hi 448 ( 0.00%) } . #[inline] 2,070 ( 0.00%) pub fn with_hi(self, hi: BytePos) -> Span { . self.data().with_hi(hi) 1,380 ( 0.00%) } . #[inline] . pub fn ctxt(self) -> SyntaxContext { . self.data_untracked().ctxt . } . #[inline] 455 ( 0.00%) pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span { . self.data_untracked().with_ctxt(ctxt) 273 ( 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 600 ---------------------------------------- . /// Returns a new span representing an empty span at the beginning of this span. . #[inline] . pub fn shrink_to_lo(self) -> Span { . let span = self.data_untracked(); . span.with_hi(span.lo) . } . /// Returns a new span representing an empty span at the end of this span. . #[inline] 138 ( 0.00%) pub fn shrink_to_hi(self) -> Span { . let span = self.data_untracked(); . span.with_lo(span.hi) 92 ( 0.00%) } . . #[inline] . /// Returns `true` if `hi == lo`. . pub fn is_empty(self) -> bool { . let span = self.data_untracked(); . span.hi == span.lo . } . . /// Returns `self` if `self` is not the dummy span, and `other` otherwise. . pub fn substitute_dummy(self, other: Span) -> Span { . if self.is_dummy() { other } else { self } . } . . /// Returns `true` if `self` fully encloses `other`. 504 ( 0.00%) pub fn contains(self, other: Span) -> bool { . let span = self.data(); . let other = other.data(); . span.contains(other) 336 ( 0.00%) } . . /// Returns `true` if `self` touches `other`. . pub fn overlaps(self, other: Span) -> bool { . let span = self.data(); . let other = other.data(); . span.lo < other.hi && other.lo < span.hi . } . -- line 638 ---------------------------------------- -- line 650 ---------------------------------------- . pub fn trim_start(self, other: Span) -> Option { . let span = self.data(); . let other = other.data(); . if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None } . } . . /// Returns the source span -- this is either the supplied span, or the span for . /// the macro callsite that expanded to it. 10 ( 0.00%) pub fn source_callsite(self) -> Span { . let expn_data = self.ctxt().outer_expn_data(); 4 ( 0.00%) if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self } 8 ( 0.00%) } . . /// The `Span` for the tokens in the previous macro expansion from which `self` was generated, . /// if any. . pub fn parent_callsite(self) -> Option { . let expn_data = self.ctxt().outer_expn_data(); . if !expn_data.is_root() { Some(expn_data.call_site) } else { None } . } . . /// Walk down the expansion ancestors to find a span that's contained within `outer`. 230 ( 0.00%) pub fn find_ancestor_inside(mut self, outer: Span) -> Option { 115 ( 0.00%) while !outer.contains(self) { . self = self.parent_callsite()?; . } . Some(self) 253 ( 0.00%) } . . /// Edition of the crate from which this span came. 44,628 ( 0.00%) pub fn edition(self) -> edition::Edition { . self.ctxt().edition() 29,752 ( 0.00%) } . . #[inline] . pub fn rust_2015(self) -> bool { 14,421 ( 0.00%) self.edition() == edition::Edition::Edition2015 . } . . #[inline] . pub fn rust_2018(self) -> bool { 518 ( 0.00%) self.edition() >= edition::Edition::Edition2018 . } . . #[inline] . pub fn rust_2021(self) -> bool { 448 ( 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]`). 45 ( 0.00%) pub fn allows_unstable(self, feature: Symbol) -> bool { 9 ( 0.00%) self.ctxt() . .outer_expn_data() . .allow_internal_unstable . .map_or(false, |features| features.iter().any(|&f| f == feature)) 36 ( 0.00%) } . . /// Checks if this span arises from a compiler desugaring of kind `kind`. 83,727 ( 0.00%) pub fn is_desugaring(self, kind: DesugaringKind) -> bool { 71,766 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => k == kind, . _ => false, . } 59,805 ( 0.00%) } . . /// Returns the compiler desugaring that created this span, or `None` . /// if this span is not from a desugaring. 110 ( 0.00%) pub fn desugaring_kind(self) -> Option { 132 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => Some(k), . _ => None, . } 88 ( 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 . /// ^^^^^^^^^^^^^^^^^^^^ . /// ``` 1,037,201 ( 0.04%) 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. 188,487 ( 0.01%) if span_data.ctxt != end_data.ctxt { 90 ( 0.00%) if span_data.ctxt == SyntaxContext::root() { . return end; 77 ( 0.00%) } 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 }, 659,477 ( 0.03%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 848,619 ( 0.03%) } . . /// Returns a `Span` between the end of `self` to the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^ . /// ``` 132 ( 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 }, 84 ( 0.00%) if span.parent == end.parent { span.parent } else { None }, . ) 96 ( 0.00%) } . . /// Returns a `Span` from the beginning of `self` until the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^ . /// ``` 451 ( 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. 82 ( 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 }, 287 ( 0.00%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 369 ( 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 { 124 ( 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 { 4 ( 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). 768 ( 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)) 448 ( 0.00%) } . . #[inline] . pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { . let span = self.data(); 360 ( 0.00%) span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency)) . } . . #[inline] . pub fn remove_mark(&mut self) -> ExpnId { . let mut span = self.data(); . let mark = span.ctxt.remove_mark(); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark -- line 897 ---------------------------------------- -- 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] 321,642 ( 0.01%) pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option { 214,428 ( 0.01%) let mut span = self.data(); 178,658 ( 0.01%) let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id); 321,642 ( 0.01%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark 357,348 ( 0.01%) } . . #[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 . } . . #[inline] . pub fn reverse_glob_adjust( . &mut self, . expn_id: ExpnId, . glob_span: Span, . ) -> Option> { 32 ( 0.00%) let mut span = self.data(); 64 ( 0.00%) let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span); 128 ( 0.00%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } . . #[inline] 120,960 ( 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()) 105,840 ( 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 { 295 ( 0.00%) MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] } . } . . pub fn from_spans(mut vec: Vec) -> MultiSpan { . vec.sort(); 10 ( 0.00%) 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() 19 ( 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 { 295 ( 0.00%) fn from(span: Span) -> MultiSpan { . MultiSpan::from_span(span) 295 ( 0.00%) } . } . . impl From> for MultiSpan { 10 ( 0.00%) fn from(spans: Vec) -> MultiSpan { 8 ( 0.00%) MultiSpan::from_spans(spans) 10 ( 0.00%) } . } . . /// Identifies an offset of a multi-byte character in a `SourceFile`. 33 ( 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`. 328 ( 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), . } -- line 1176 ---------------------------------------- -- line 1201 ---------------------------------------- . } . } . } . . impl Add for NonNarrowChar { . type Output = Self; . . fn add(self, rhs: BytePos) -> Self { 552 ( 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; . 164 ( 0.00%) fn sub(self, rhs: BytePos) -> Self { 552 ( 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), . } 492 ( 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, . } . 12 ( 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 1257 ---------------------------------------- . AbsentOk, . /// A failed attempt has been made to load the external source. . AbsentErr, . Unneeded, . } . . impl ExternalSource { . pub fn get_source(&self) -> Option<&Lrc> { 4 ( 0.00%) match self { . ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src), . _ => None, . } . } . } . . #[derive(Debug)] . pub struct OffsetOverflowError; . 1,168 ( 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. 24 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Debug)] 2,336 ( 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 => { 12 ( 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 { 12 ( 0.00%) match self.kind { . SourceFileHashAlgorithm::Md5 => 16, . SourceFileHashAlgorithm::Sha1 => 20, . SourceFileHashAlgorithm::Sha256 => 32, . } . } . } . . /// A single source in the [`SourceMap`]. 232 ( 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. 4 ( 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. 4 ( 0.00%) pub name_hash: u128, . /// Indicates which crate this `SourceFile` was imported from. 4 ( 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)?; . 16 ( 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 { 8 ( 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); . 8 ( 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))?; 12 ( 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))?; 44 ( 0.00%) s.emit_struct_field("cnum", false, |s| self.cnum.encode(s)) . }) . } . } . . impl Decodable for SourceFile { 5,256 ( 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); 584 ( 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 { 967,430 ( 0.04%) 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)); 1,168 ( 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)); 6,424 ( 0.00%) SourceFile { 4,672 ( 0.00%) name, . start_pos, . end_pos, . src: None, 2,336 ( 0.00%) src_hash, . // Unused - the metadata decoder will construct . // a new SourceFile, filling in `external_src` properly . external_src: Lock::new(ExternalSource::Unneeded), 2,336 ( 0.00%) lines, 2,336 ( 0.00%) multibyte_chars, 2,336 ( 0.00%) non_narrow_chars, 2,336 ( 0.00%) normalized_pos, . name_hash, . cnum, . } . }) 5,256 ( 0.00%) } . } . . impl fmt::Debug for SourceFile { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(fmt, "SourceFile({:?})", self.name) . } . } . . impl SourceFile { 44 ( 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); 12 ( 0.00%) let normalized_pos = normalize_src(&mut src, start_pos); . . let name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 8 ( 0.00%) name.hash(&mut hasher); . hasher.finish::() . }; 8 ( 0.00%) let end_pos = start_pos.to_usize() + src.len(); 12 ( 0.00%) assert!(end_pos <= u32::MAX as usize); . 48 ( 0.00%) let (lines, multibyte_chars, non_narrow_chars) = 8 ( 0.00%) analyze_source_file::analyze_source_file(&src, start_pos); . 68 ( 0.00%) SourceFile { . name, . src: Some(Lrc::new(src)), 44 ( 0.00%) src_hash, . external_src: Lock::new(ExternalSource::Unneeded), . start_pos, . end_pos: Pos::from_usize(end_pos), 16 ( 0.00%) lines, 16 ( 0.00%) multibyte_chars, 16 ( 0.00%) non_narrow_chars, 16 ( 0.00%) normalized_pos, . name_hash, . cnum: LOCAL_CRATE, . } 36 ( 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. 266 ( 0.00%) pub fn add_external_src(&self, get_src: F) -> bool . where . F: FnOnce() -> Option, . { 38 ( 0.00%) if matches!( 76 ( 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 { 38 ( 0.00%) self.src.is_some() || self.external_src.borrow().get_source().is_some() . } 342 ( 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() 588 ( 0.00%) } . . pub fn is_imported(&self) -> bool { . self.src.is_none() 89,316 ( 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 { 12,371 ( 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 { 34,587 ( 0.00%) if self.is_empty() { . return self.start_pos..self.end_pos; . } . 23,110 ( 0.00%) assert!(line_index < self.lines.len()); 34,353 ( 0.00%) if line_index == (self.lines.len() - 1) { 18 ( 0.00%) self.lines[line_index]..self.end_pos . } else { 22,888 ( 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`. 4 ( 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; . 12 ( 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; . } . } . 24 ( 0.00%) assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32()); 20 ( 0.00%) CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize) 8 ( 0.00%) } . . /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a . /// given `BytePos`. 14 ( 0.00%) pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) { 4 ( 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 2 ( 0.00%) let linebpos = self.lines[a]; 4 ( 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); 2 ( 0.00%) assert!(chpos >= linechpos); . (line, col) . } . None => (0, chpos), . } 16 ( 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`. 16 ( 0.00%) pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) { 6 ( 0.00%) let (line, col_or_chpos) = self.lookup_file_pos(pos); 4 ( 0.00%) if line > 0 { . let col = col_or_chpos; 2 ( 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); . 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(); 10 ( 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) . } 14 ( 0.00%) } . } . . /// Normalizes the source code and records the normalizations. 40 ( 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 36 ( 0.00%) } . . /// Removes UTF-8 BOM, if any. . fn remove_bom(src: &mut String, normalized_pos: &mut Vec) { 4 ( 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) { 4 ( 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])* 186,911 ( 0.01%) $vis struct $ident($inner_vis $inner_ty); . . impl Pos for $ident { . #[inline(always)] . fn from_usize(n: usize) -> $ident { 14,263 ( 0.00%) $ident(n as $inner_ty) . } . . #[inline(always)] . fn to_usize(&self) -> usize { 386,909 ( 0.02%) 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 { 2,238,114 ( 0.09%) $ident(self.0 + rhs.0) . } . } . . impl Sub for $ident { . type Output = $ident; . . #[inline(always)] . fn sub(self, rhs: $ident) -> $ident { 3,240,264 ( 0.13%) $ident(self.0 - rhs.0) . } . } . )* . }; . } . . impl_pos! { . /// A byte offset. -- line 1931 ---------------------------------------- -- line 1946 ---------------------------------------- . impl Encodable for BytePos { . fn encode(&self, s: &mut S) -> Result<(), S::Error> { . s.emit_u32(self.0) . } . } . . impl Decodable for BytePos { . fn decode(d: &mut D) -> BytePos { 103,878 ( 0.00%) 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. 956,095 ( 0.04%) 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; . 138,485 ( 0.01%) if !ctx.hash_spans() { . return; . } . 817,610 ( 0.03%) let span = self.data_untracked(); 404,067 ( 0.02%) span.ctxt.hash_stable(ctx, hasher); 409,755 ( 0.02%) span.parent.hash_stable(ctx, hasher); . 273,389 ( 0.01%) if span.is_dummy() { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . 272,732 ( 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. 545,464 ( 0.02%) let (file, line_lo, col_lo, line_hi, col_hi) = match ctx.span_data_to_lines_and_cols(&span) . { 272,732 ( 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. . 136,366 ( 0.01%) 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; 136,366 ( 0.01%) let len = (span.hi - span.lo).0; . Hash::hash(&col_line, hasher); . Hash::hash(&len, hasher); 1,092,680 ( 0.04%) } . } 3,616,962 ( 0.14%) -------------------------------------------------------------------------------- -- 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> { 272,067 ( 0.01%) ptr: NonZeroUsize, 492,588 ( 0.02%) 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; . 52,448 ( 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> { 13,890 ( 0.00%) fn pack(self) -> GenericArg<'tcx> { 13,890 ( 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) . } . }; . 35,808 ( 0.00%) GenericArg { ptr: unsafe { NonZeroUsize::new_unchecked(ptr | tag) }, marker: PhantomData } 13,890 ( 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> { 16,500 ( 0.00%) fn from(r: ty::Region<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Lifetime(r).pack() 16,500 ( 0.00%) } . } . . impl<'tcx> From> for GenericArg<'tcx> { 250,371 ( 0.01%) fn from(ty: Ty<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Type(ty).pack() 250,371 ( 0.01%) } . } . . impl<'tcx> From<&'tcx ty::Const<'tcx>> for GenericArg<'tcx> { 310 ( 0.00%) fn from(c: &'tcx ty::Const<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Const(c).pack() 310 ( 0.00%) } . } . . impl<'tcx> GenericArg<'tcx> { . #[inline] . pub fn unpack(self) -> GenericArgKind<'tcx> { . let ptr = self.ptr.get(); . unsafe { 3,021,856 ( 0.12%) match ptr & TAG_MASK { 13,028 ( 0.00%) REGION_TAG => GenericArgKind::Lifetime(&*((ptr & !TAG_MASK) as *const _)), 714,918 ( 0.03%) TYPE_TAG => GenericArgKind::Type(&*((ptr & !TAG_MASK) as *const _)), 285 ( 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"), . } 49,216 ( 0.00%) } . . /// Unpack the `GenericArg` as a const when it is known certainly to be a const. . pub fn expect_const(self) -> &'tcx ty::Const<'tcx> { . match self.unpack() { . GenericArgKind::Const(c) => c, . _ => bug!("expected a const, but found another kind"), . } . } -- line 140 ---------------------------------------- -- line 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> { 336 ( 0.00%) self.unpack().encode(e) . } . } . . impl<'tcx, D: TyDecoder<'tcx>> Decodable for GenericArg<'tcx> { 69,450 ( 0.00%) fn decode(d: &mut D) -> GenericArg<'tcx> { 69,450 ( 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. 409 ( 0.00%) pub fn as_closure(&'a self) -> ClosureSubsts<'a> { . ClosureSubsts { substs: self } 409 ( 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. 2,070 ( 0.00%) pub fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: DefId) -> SubstsRef<'tcx> { 344 ( 0.00%) Self::for_item(tcx, def_id, |param, _| tcx.mk_param_from_def(param)) 1,863 ( 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. 85,182 ( 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); 29,358 ( 0.00%) Self::fill_item(&mut substs, tcx, defs, &mut mk_kind); 19,000 ( 0.00%) tcx.intern_substs(&substs) 85,599 ( 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)) . }) . } . 99,636 ( 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>, . { 40,251 ( 0.00%) if let Some(def_id) = defs.parent { . let parent_defs = tcx.generics_of(def_id); 1,168 ( 0.00%) Self::fill_item(substs, tcx, parent_defs, mk_kind); . } . Self::fill_single(substs, defs, mk_kind) 79,624 ( 0.00%) } . 16 ( 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); 61,984 ( 0.00%) assert_eq!(param.index as usize, substs.len()); . substs.push(kind); . } 16 ( 0.00%) } . . #[inline] . pub fn types(&'a self) -> impl DoubleEndedIterator> + 'a { . self.iter() . .filter_map(|k| if let GenericArgKind::Type(ty) = k.unpack() { Some(ty) } else { None }) . } . . #[inline] -- line 284 ---------------------------------------- -- line 302 ---------------------------------------- . self.iter().filter_map(|k| match k.unpack() { . GenericArgKind::Lifetime(_) => None, . generic => Some(generic), . }) . } . . #[inline] . pub fn type_at(&self, i: usize) -> Ty<'tcx> { 147,201 ( 0.01%) if let GenericArgKind::Type(ty) = self[i].unpack() { . ty . } else { . bug!("expected type for param #{} in {:?}", i, self); . } . } . . #[inline] . pub fn region_at(&self, i: usize) -> ty::Region<'tcx> { -- line 318 ---------------------------------------- -- line 350 ---------------------------------------- . /// impl X for U { fn f() {} } . /// ``` . /// . /// * If `self` is `[Self, S, T]`: the identity substs of `f` in the trait. . /// * If `source_ancestor` is the def_id of the trait. . /// * If `target_substs` is `[U]`, the substs for the impl. . /// * Then we will return `[U, T]`, the subst for `f` in the impl that . /// are needed for it to match the trait. 1,645 ( 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); 470 ( 0.00%) tcx.mk_substs(target_substs.iter().chain(self.iter().skip(defs.params.len()))) 1,880 ( 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> { 3,633 ( 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`. 671,874 ( 0.03%) match self.len() { . 1 => { 29,880 ( 0.00%) let param0 = self[0].try_fold_with(folder)?; 95,743 ( 0.00%) if param0 == self[0] { Ok(self) } else { Ok(folder.tcx().intern_substs(&[param0])) } . } . 2 => { 88,073 ( 0.00%) let param0 = self[0].try_fold_with(folder)?; 251,823 ( 0.01%) let param1 = self[1].try_fold_with(folder)?; 317,259 ( 0.01%) if param0 == self[0] && param1 == self[1] { . Ok(self) . } else { 386,006 ( 0.02%) Ok(folder.tcx().intern_substs(&[param0, param1])) . } . } . 0 => Ok(self), . _ => { . let params: SmallVec<[_; 8]> = 3,334 ( 0.00%) self.iter().map(|k| k.try_fold_with(folder)).collect::>()?; 287 ( 0.00%) if params[..] == self[..] { . Ok(self) . } else { 553 ( 0.00%) Ok(folder.tcx().intern_substs(¶ms)) . } . } . } 7,575 ( 0.00%) } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { 44,293 ( 0.00%) 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 { 1,468,200 ( 0.06%) 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> { 17,341 ( 0.00%) self.tcx . } . . fn fold_binder>( . &mut self, . t: ty::Binder<'tcx, T>, . ) -> ty::Binder<'tcx, T> { 40,194 ( 0.00%) self.binders_passed += 1; 2,594 ( 0.00%) let t = t.super_fold_with(self); 40,194 ( 0.00%) self.binders_passed -= 1; . t . } . 36,162 ( 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()`. 12,054 ( 0.00%) match *r { 10,884 ( 0.00%) ty::ReEarlyBound(data) => { 10,884 ( 0.00%) let rk = self.substs.get(data.index as usize).map(|k| k.unpack()); . match rk { 5,442 ( 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, . } 42,189 ( 0.00%) } . 858,663 ( 0.03%) fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 286,221 ( 0.01%) if !t.needs_subst() { . return t; . } . 57,296 ( 0.00%) match *t.kind() { 93,990 ( 0.00%) ty::Param(p) => self.ty_for_param(p, t), 59,100 ( 0.00%) _ => t.super_fold_with(self), . } 1,381,855 ( 0.05%) } . 151,102 ( 0.01%) fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 44,362 ( 0.00%) if let ty::ConstKind::Param(p) = c.val { . self.const_for_param(p, c) . } else { 192,132 ( 0.01%) c.super_fold_with(self) . } 1,904 ( 0.00%) } . . #[inline] . fn fold_mir_const(&mut self, c: mir::ConstantKind<'tcx>) -> mir::ConstantKind<'tcx> { . c.super_fold_with(self) . } . } . . impl<'a, 'tcx> SubstFolder<'a, 'tcx> { . fn ty_for_param(&self, p: ty::ParamTy, source_ty: Ty<'tcx>) -> Ty<'tcx> { . // Look up the type in the substitutions. It really should be in there. 37,596 ( 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 562 ---------------------------------------- . } . . fn const_for_param( . &self, . p: ParamConst, . source_ct: &'tcx ty::Const<'tcx>, . ) -> &'tcx ty::Const<'tcx> { . // Look up the const in the substitutions. It really should be in there. 476 ( 0.00%) let opt_ct = self.substs.get(p.index as usize).map(|k| k.unpack()); . let ct = match opt_ct { . Some(GenericArgKind::Const(ct)) => ct, . Some(kind) => { . let span = self.span.unwrap_or(DUMMY_SP); . span_bug!( . span, . "expected const for `{:?}` ({:?}/{}) but found {:?} \ . when substituting substs={:?}", -- line 578 ---------------------------------------- -- line 645 ---------------------------------------- . fn shift_vars_through_binders>(&self, val: T) -> T { . debug!( . "shift_vars(val={:?}, binders_passed={:?}, has_escaping_bound_vars={:?})", . val, . self.binders_passed, . val.has_escaping_bound_vars() . ); . 69,516 ( 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> { 11,703 ( 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)] 622 ( 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. 140 ( 0.00%) pub user_self_ty: Option>, . } . . /// Specifies the user-given self type. In the case of a path that . /// refers to a member in an inherent impl, this self type is . /// sometimes needed to constrain the type parameters on the impl. For . /// example, in this code: . /// . /// ``` -- line 689 ---------------------------------------- -- line 696 ---------------------------------------- . /// self type `Foo`. Then we can instantiate the parameters of . /// the impl (with the substs from `UserSubsts`) and apply those to . /// the self type, giving `Foo`. Finally, we unify that with . /// the self type here, which contains `?A` to be `&'static u32` . #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] . #[derive(HashStable, TypeFoldable, Lift)] . pub struct UserSelfTy<'tcx> { . pub impl_def_id: DefId, 57 ( 0.00%) pub self_ty: Ty<'tcx>, . } 899,294 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs -------------------------------------------------------------------------------- Ir -- line 48 ---------------------------------------- . // . // FIXME: we have to do something for moving slice patterns. . fn place_contents_drop_state_cannot_differ<'tcx>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . place: mir::Place<'tcx>, . ) -> bool { . let ty = place.ty(body, tcx).ty; 827,406 ( 0.03%) match ty.kind() { . ty::Array(..) => { . debug!( . "place_contents_drop_state_cannot_differ place: {:?} ty: {:?} => false", . place, ty . ); . false . } . ty::Slice(..) | ty::Ref(..) | ty::RawPtr(..) => { . debug!( . "place_contents_drop_state_cannot_differ place: {:?} ty: {:?} refd => true", . place, ty . ); . true . } 1,016,145 ( 0.04%) ty::Adt(def, _) if (def.has_dtor(tcx) && !def.is_box()) || def.is_union() => { . debug!( . "place_contents_drop_state_cannot_differ place: {:?} ty: {:?} Drop => true", . place, ty . ); . true . } . _ => false, . } -- line 79 ---------------------------------------- -- line 83 ---------------------------------------- . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . lookup_result: LookupResult, . each_child: F, . ) where . F: FnMut(MovePathIndex), . { 1,734 ( 0.00%) match lookup_result { . LookupResult::Parent(..) => { . // access to untracked value - do not touch children . } . LookupResult::Exact(e) => on_all_children_bits(tcx, body, move_data, e, each_child), . } . } . . pub fn on_all_children_bits<'tcx, F>( -- line 99 ---------------------------------------- -- line 100 ---------------------------------------- . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . move_path_index: MovePathIndex, . mut each_child: F, . ) where . F: FnMut(MovePathIndex), . { 1,112,560 ( 0.04%) fn is_terminal_path<'tcx>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . path: MovePathIndex, . ) -> bool { 278,140 ( 0.01%) place_contents_drop_state_cannot_differ(tcx, body, move_data.move_paths[path].place) 1,112,560 ( 0.04%) } . 1,300,334 ( 0.05%) fn on_all_children_bits<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . move_path_index: MovePathIndex, . each_child: &mut F, . ) where . F: FnMut(MovePathIndex), . { 67,690 ( 0.00%) each_child(move_path_index); . 973,490 ( 0.04%) if is_terminal_path(tcx, body, move_data, move_path_index) { . return; . } . 135,504 ( 0.01%) let mut next_child_index = move_data.move_paths[move_path_index].first_child; 272,711 ( 0.01%) while let Some(child_index) = next_child_index { 3,372 ( 0.00%) on_all_children_bits(tcx, body, move_data, child_index, each_child); 562 ( 0.00%) next_child_index = move_data.move_paths[child_index].next_sibling; . } 1,049,448 ( 0.04%) } 829,547 ( 0.03%) on_all_children_bits(tcx, body, move_data, move_path_index, &mut each_child); . } . . pub fn on_all_drop_children_bits<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . ctxt: &MoveDataParamEnv<'tcx>, . path: MovePathIndex, . mut each_child: F, -- line 146 ---------------------------------------- -- line 156 ---------------------------------------- . if erased_ty.needs_drop(tcx, ctxt.param_env) { . each_child(child); . } else { . debug!("on_all_drop_children_bits - skipping") . } . }) . } . 2,127 ( 0.00%) pub fn drop_flag_effects_for_function_entry<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . ctxt: &MoveDataParamEnv<'tcx>, . mut callback: F, . ) where . F: FnMut(MovePathIndex, DropFlagState), . { . let move_data = &ctxt.move_data; 192 ( 0.00%) for arg in body.args_iter() { 340 ( 0.00%) let place = mir::Place::from(arg); 510 ( 0.00%) let lookup_result = move_data.rev_lookup.find(place.as_ref()); . on_lookup_result_bits(tcx, body, move_data, lookup_result, |mpi| { 186 ( 0.00%) callback(mpi, DropFlagState::Present) . }); . } 1,536 ( 0.00%) } . 757,512 ( 0.03%) pub fn drop_flag_effects_for_location<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . ctxt: &MoveDataParamEnv<'tcx>, . loc: Location, . mut callback: F, . ) where . F: FnMut(MovePathIndex, DropFlagState), . { . let move_data = &ctxt.move_data; . debug!("drop_flag_effects_for_location({:?})", loc); . . // first, move out of the RHS 15,699 ( 0.00%) for mi in &move_data.loc_map[loc] { 265,659 ( 0.01%) let path = mi.move_path_index(move_data); . debug!("moving out of path {:?}", move_data.move_paths[path]); . 70,420 ( 0.00%) on_all_children_bits(tcx, body, move_data, path, |mpi| callback(mpi, DropFlagState::Absent)) . } . . debug!("drop_flag_effects: assignment for location({:?})", loc); . 67,690 ( 0.00%) for_location_inits(tcx, body, move_data, loc, |mpi| callback(mpi, DropFlagState::Present)); 631,480 ( 0.02%) } . . pub fn for_location_inits<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . loc: Location, . mut callback: F, . ) where . F: FnMut(MovePathIndex), . { 15,699 ( 0.00%) for ii in &move_data.init_loc_map[loc] { 272,048 ( 0.01%) let init = move_data.inits[*ii]; 137,560 ( 0.01%) match init.kind { . InitKind::Deep => { . let path = init.path; . . on_all_children_bits(tcx, body, move_data, path, &mut callback) . } . InitKind::Shallow => { . let mpi = init.path; . callback(mpi); -- line 226 ---------------------------------------- -- line 230 ---------------------------------------- . } . } . . /// Calls `handle_inactive_variant` for each descendant move path of `enum_place` that contains a . /// `Downcast` to a variant besides the `active_variant`. . /// . /// NOTE: If there are no move paths corresponding to an inactive variant, . /// `handle_inactive_variant` will not be called for that variant. 2,304 ( 0.00%) pub(crate) fn on_all_inactive_variants<'tcx>( . tcx: TyCtxt<'tcx>, . body: &mir::Body<'tcx>, . move_data: &MoveData<'tcx>, . enum_place: mir::Place<'tcx>, . active_variant: VariantIdx, . mut handle_inactive_variant: impl FnMut(MovePathIndex), . ) { 960 ( 0.00%) let enum_mpi = match move_data.rev_lookup.find(enum_place.as_ref()) { . LookupResult::Exact(mpi) => mpi, . LookupResult::Parent(_) => return, . }; . . let enum_path = &move_data.move_paths[enum_mpi]; 537 ( 0.00%) for (variant_mpi, variant_path) in enum_path.children(&move_data.move_paths) { . // Because of the way we build the `MoveData` tree, each child should have exactly one more . // projection than `enum_place`. This additional projection must be a downcast since the . // base is an enum. 6 ( 0.00%) let (downcast, base_proj) = variant_path.place.projection.split_last().unwrap(); 24 ( 0.00%) assert_eq!(enum_place.projection.len(), base_proj.len()); . 18 ( 0.00%) let variant_idx = match *downcast { . mir::ProjectionElem::Downcast(_, idx) => idx, . _ => unreachable!(), . }; . 6 ( 0.00%) if variant_idx != active_variant { . on_all_children_bits(tcx, body, move_data, variant_mpi, |mpi| { 6 ( 0.00%) handle_inactive_variant(mpi) . }); . } . } 1,536 ( 0.00%) } 1,107,204 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/md-5-0.9.1/src/utils.rs -------------------------------------------------------------------------------- Ir . #![allow(clippy::many_single_char_names)] . use crate::consts::RC; . use core::convert::TryInto; . . #[inline(always)] . fn op_f(w: u32, x: u32, y: u32, z: u32, m: u32, c: u32, s: u32) -> u32 { 1,118,257 ( 0.04%) ((x & y) | (!x & z)) . .wrapping_add(w) . .wrapping_add(m) . .wrapping_add(c) . .rotate_left(s) . .wrapping_add(x) . } . #[inline(always)] . fn op_g(w: u32, x: u32, y: u32, z: u32, m: u32, c: u32, s: u32) -> u32 { 1,066,002 ( 0.04%) ((x & z) | (y & !z)) . .wrapping_add(w) . .wrapping_add(m) . .wrapping_add(c) . .rotate_left(s) . .wrapping_add(x) . } . . #[inline(always)] . fn op_h(w: u32, x: u32, y: u32, z: u32, m: u32, c: u32, s: u32) -> u32 { 522,550 ( 0.02%) (x ^ y ^ z) . .wrapping_add(w) . .wrapping_add(m) . .wrapping_add(c) . .rotate_left(s) . .wrapping_add(x) . } . . #[inline(always)] . fn op_i(w: u32, x: u32, y: u32, z: u32, m: u32, c: u32, s: u32) -> u32 { 668,864 ( 0.03%) (y ^ (x | !z)) . .wrapping_add(w) . .wrapping_add(m) . .wrapping_add(c) . .rotate_left(s) . .wrapping_add(x) . } . . #[inline] 94,059 ( 0.00%) pub fn compress(state: &mut [u32; 4], input: &[u8; 64]) { 20,902 ( 0.00%) let mut a = state[0]; 10,451 ( 0.00%) let mut b = state[1]; 10,451 ( 0.00%) let mut c = state[2]; 10,451 ( 0.00%) let mut d = state[3]; . . let mut data = [0u32; 16]; . for (o, chunk) in data.iter_mut().zip(input.chunks_exact(4)) { 261,275 ( 0.01%) *o = u32::from_le_bytes(chunk.try_into().unwrap()); . } . . // round 1 . a = op_f(a, b, c, d, data[0], RC[0], 7); . d = op_f(d, a, b, c, data[1], RC[1], 12); . c = op_f(c, d, a, b, data[2], RC[2], 17); . b = op_f(b, c, d, a, data[3], RC[3], 22); . -- line 61 ---------------------------------------- -- line 132 ---------------------------------------- . c = op_i(c, d, a, b, data[6], RC[58], 15); . b = op_i(b, c, d, a, data[13], RC[59], 21); . . a = op_i(a, b, c, d, data[4], RC[60], 6); . d = op_i(d, a, b, c, data[11], RC[61], 10); . c = op_i(c, d, a, b, data[2], RC[62], 15); . b = op_i(b, c, d, a, data[9], RC[63], 21); . 20,902 ( 0.00%) state[0] = state[0].wrapping_add(a); 10,451 ( 0.00%) state[1] = state[1].wrapping_add(b); 10,451 ( 0.00%) state[2] = state[2].wrapping_add(c); 10,451 ( 0.00%) state[3] = state[3].wrapping_add(d); 83,608 ( 0.00%) } -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/undo_log.rs -------------------------------------------------------------------------------- Ir -- line 28 ---------------------------------------- . PushRegionObligation, . } . . macro_rules! impl_from { . ($($ctor: ident ($ty: ty),)*) => { . $( . impl<'tcx> From<$ty> for UndoLog<'tcx> { . fn from(x: $ty) -> Self { 400 ( 0.00%) UndoLog::$ctor(x.into()) . } . } . )* . } . } . . // Upcast from a single kind of "undoable action" to the general enum . impl_from! { -- line 44 ---------------------------------------- -- line 57 ---------------------------------------- . ConstUnificationTable(sv::UndoLog>>), . . RegionUnificationTable(sv::UndoLog>>), . ProjectionCache(traits::UndoLog<'tcx>), . } . . /// The Rollback trait defines how to rollback a particular action. . impl<'tcx> Rollback> for InferCtxtInner<'tcx> { 526,194 ( 0.02%) fn reverse(&mut self, undo: UndoLog<'tcx>) { 876,990 ( 0.03%) match undo { 1,631,480 ( 0.06%) UndoLog::TypeVariables(undo) => self.type_variable_storage.reverse(undo), 290 ( 0.00%) UndoLog::ConstUnificationTable(undo) => self.const_unification_storage.reverse(undo), 3,820 ( 0.00%) UndoLog::IntUnificationTable(undo) => self.int_unification_storage.reverse(undo), . UndoLog::FloatUnificationTable(undo) => self.float_unification_storage.reverse(undo), . UndoLog::RegionConstraintCollector(undo) => { 36,659 ( 0.00%) self.region_constraint_storage.as_mut().unwrap().reverse(undo) . } . UndoLog::RegionUnificationTable(undo) => { 9,648 ( 0.00%) self.region_constraint_storage.as_mut().unwrap().unification_table.reverse(undo) . } . UndoLog::ProjectionCache(undo) => self.projection_cache.reverse(undo), . UndoLog::PushRegionObligation => { . self.region_obligations.pop(); . } . } 701,592 ( 0.03%) } . } . . /// The combined undo log for all the various unification tables. For each change to the storage . /// for any kind of inference variable, we record an UndoLog entry in the vector here. . pub(crate) struct InferCtxtUndoLogs<'tcx> { . logs: Vec>, . num_open_snapshots: usize, . } . . impl Default for InferCtxtUndoLogs<'_> { . fn default() -> Self { 7,314 ( 0.00%) Self { logs: Default::default(), num_open_snapshots: Default::default() } . } . } . . /// The UndoLogs trait defines how we undo a particular kind of action (of type T). We can undo any . /// action that is convertable into an UndoLog (per the From impls above). . impl<'tcx, T> UndoLogs for InferCtxtUndoLogs<'tcx> . where . UndoLog<'tcx>: From, -- line 102 ---------------------------------------- -- line 103 ---------------------------------------- . { . #[inline] . fn num_open_snapshots(&self) -> usize { . self.num_open_snapshots . } . . #[inline] . fn push(&mut self, undo: T) { 42,864 ( 0.00%) if self.in_snapshot() { 3,200 ( 0.00%) self.logs.push(undo.into()) . } . } . . fn clear(&mut self) { . self.logs.clear(); . self.num_open_snapshots = 0; . } . -- line 120 ---------------------------------------- -- line 125 ---------------------------------------- . { . if self.in_snapshot() { . self.logs.extend(undos.into_iter().map(UndoLog::from)) . } . } . } . . impl<'tcx> InferCtxtInner<'tcx> { 334,848 ( 0.01%) pub fn rollback_to(&mut self, snapshot: Snapshot<'tcx>) { . debug!("rollback_to({})", snapshot.undo_len); . self.undo_log.assert_open_snapshot(&snapshot); . 637,810 ( 0.03%) while self.undo_log.logs.len() > snapshot.undo_len { . let undo = self.undo_log.logs.pop().unwrap(); 2,104,776 ( 0.08%) self.reverse(undo); . } . 145,327 ( 0.01%) if self.undo_log.num_open_snapshots == 1 { . // The root snapshot. It's safe to clear the undo log because . // there's no snapshot further out that we might need to roll back . // to. 33,228 ( 0.00%) assert!(snapshot.undo_len == 0); . self.undo_log.logs.clear(); . } . 184,038 ( 0.01%) self.undo_log.num_open_snapshots -= 1; 390,656 ( 0.02%) } . . pub fn commit(&mut self, snapshot: Snapshot<'tcx>) { . debug!("commit({})", snapshot.undo_len); . 554,799 ( 0.02%) if self.undo_log.num_open_snapshots == 1 { . // The root snapshot. It's safe to clear the undo log because . // there's no snapshot further out that we might need to roll back . // to. 113,128 ( 0.00%) assert!(snapshot.undo_len == 0); . self.undo_log.logs.clear(); . } . 611,363 ( 0.02%) self.undo_log.num_open_snapshots -= 1; . } . } . . impl<'tcx> InferCtxtUndoLogs<'tcx> { . pub fn start_snapshot(&mut self) -> Snapshot<'tcx> { 962,964 ( 0.04%) self.num_open_snapshots += 1; . Snapshot { undo_len: self.logs.len(), _marker: PhantomData } . } . . pub(crate) fn region_constraints_in_snapshot( . &self, . s: &Snapshot<'tcx>, . ) -> impl Iterator> + Clone { 7,392 ( 0.00%) self.logs[s.undo_len..].iter().filter_map(|log| match log { . UndoLog::RegionConstraintCollector(log) => Some(log), . _ => None, . }) . } . . pub(crate) fn region_constraints( . &self, . ) -> impl Iterator> + Clone { 110 ( 0.00%) self.logs.iter().filter_map(|log| match log { . UndoLog::RegionConstraintCollector(log) => Some(log), . _ => None, . }) . } . . fn assert_open_snapshot(&self, snapshot: &Snapshot<'tcx>) { . // Failures here may indicate a failure to follow a stack discipline. 167,424 ( 0.01%) assert!(self.logs.len() >= snapshot.undo_len); 167,424 ( 0.01%) assert!(self.num_open_snapshots > 0); . } . } . . impl<'tcx> std::ops::Index for InferCtxtUndoLogs<'tcx> { . type Output = UndoLog<'tcx>; . . fn index(&self, key: usize) -> &Self::Output { . &self.logs[key] -- line 204 ---------------------------------------- 265,948 ( 0.01%) -------------------------------------------------------------------------------- -- 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)] 916,680 ( 0.04%) fn intern_ty(&self, kind: TyKind<'tcx>) -> Ty<'tcx> { . self.type_ 572,925 ( 0.02%) .intern(kind, |kind| { 21,594 ( 0.00%) let flags = super::flags::FlagComputation::for_kind(&kind); . . let ty_struct = TyS { 43,188 ( 0.00%) kind, . flags: flags.flags, . outer_exclusive_binder: flags.outer_exclusive_binder, . }; . . Interned(self.arena.alloc(ty_struct)) . }) . .0 1,031,265 ( 0.04%) } . . #[inline(never)] 693,464 ( 0.03%) fn intern_predicate( . &self, . kind: Binder<'tcx, PredicateKind<'tcx>>, . ) -> &'tcx PredicateInner<'tcx> { . self.predicate 606,781 ( 0.02%) .intern(kind, |kind| { 30,462 ( 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 780,147 ( 0.03%) } . } . . 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) { 809,634 ( 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) . } . 537,011 ( 0.02%) pub fn get(&self, id: hir::HirId) -> Option<&V> { 107,404 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); 107,404 ( 0.00%) self.data.get(&id.local_id) 429,660 ( 0.02%) } . . 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; . 318 ( 0.00%) fn index(&self, key: hir::HirId) -> &V { . self.get(key).expect("LocalTableInContext: key not found") 212 ( 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> { 1,164 ( 0.00%) pub fn new(hir_owner: LocalDefId) -> TypeckResults<'tcx> { 13,774 ( 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(), . } 1,164 ( 0.00%) } . . /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node. 97,908 ( 0.00%) pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res { 65,272 ( 0.00%) match *qpath { 193,590 ( 0.01%) hir::QPath::Resolved(_, ref path) => path.res, . hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self . .type_dependent_def(id) 2,226 ( 0.00%) .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), . } 163,180 ( 0.01%) } . 34 ( 0.00%) pub fn type_dependent_defs( . &self, . ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorReported>> { 6,352 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.type_dependent_defs } 34 ( 0.00%) } . 647 ( 0.00%) pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> { 1,403 ( 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()) 1,294 ( 0.00%) } . 1,540 ( 0.00%) pub fn type_dependent_def_id(&self, id: HirId) -> Option { . self.type_dependent_def(id).map(|(_, def_id)| def_id) 1,540 ( 0.00%) } . 46,353 ( 0.00%) pub fn type_dependent_defs_mut( . &mut self, . ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorReported>> { 46,353 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.type_dependent_defs } 46,353 ( 0.00%) } . . pub fn field_indices(&self) -> LocalTableInContext<'_, usize> { 35,650 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.field_indices } 138 ( 0.00%) } . . pub fn field_indices_mut(&mut self) -> LocalTableInContextMut<'_, usize> { 105,852 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.field_indices } 52,926 ( 0.00%) } . . pub fn user_provided_types(&self) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> { 28,954 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.user_provided_types } 14,477 ( 0.00%) } . . pub fn user_provided_types_mut( . &mut self, . ) -> LocalTableInContextMut<'_, CanonicalUserType<'tcx>> { 96 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.user_provided_types } 48 ( 0.00%) } . . pub fn node_types(&self) -> LocalTableInContext<'_, Ty<'tcx>> { 93,220 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.node_types } 46,610 ( 0.00%) } . . pub fn node_types_mut(&mut self) -> LocalTableInContextMut<'_, Ty<'tcx>> { 183,902 ( 0.01%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_types } 91,951 ( 0.00%) } . 1,072,476 ( 0.04%) pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> { 178,746 ( 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))) . }) 893,730 ( 0.04%) } . 224,182 ( 0.01%) pub fn node_type_opt(&self, id: hir::HirId) -> Option> { 224,182 ( 0.01%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_types.get(&id.local_id).cloned() 448,364 ( 0.02%) } . . pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> { 1,338 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_substs } 669 ( 0.00%) } . 63,052 ( 0.00%) pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> { 63,052 ( 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()) 126,104 ( 0.00%) } . 45,566 ( 0.00%) pub fn node_substs_opt(&self, id: hir::HirId) -> Option> { 45,566 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_substs.get(&id.local_id).cloned() 91,132 ( 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> { 900 ( 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> { 252,299 ( 0.01%) self.node_type(expr.hir_id) . } . . pub fn expr_ty_opt(&self, expr: &hir::Expr<'_>) -> Option> { 181,109 ( 0.01%) self.node_type_opt(expr.hir_id) . } . . pub fn adjustments(&self) -> LocalTableInContext<'_, Vec>> { 91,024 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.adjustments } 45,512 ( 0.00%) } . . pub fn adjustments_mut( . &mut self, . ) -> LocalTableInContextMut<'_, Vec>> { 93,732 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.adjustments } 46,866 ( 0.00%) } . 84,410 ( 0.00%) pub fn expr_adjustments(&self, expr: &hir::Expr<'_>) -> &[ty::adjustment::Adjustment<'tcx>] { 168,820 ( 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[..]) 168,820 ( 0.01%) } . . /// Returns the type of `expr`, considering any `Adjustment` . /// entry recorded for that expression. 595 ( 0.00%) pub fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> { 119 ( 0.00%) self.expr_adjustments(expr).last().map_or_else(|| self.expr_ty(expr), |adj| adj.target) 200 ( 0.00%) } . 210 ( 0.00%) pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr<'_>) -> Option> { 42 ( 0.00%) self.expr_adjustments(expr).last().map(|adj| adj.target).or_else(|| self.expr_ty_opt(expr)) 124 ( 0.00%) } . 6,318 ( 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. 12,636 ( 0.00%) if let hir::ExprKind::Path(_) = expr.kind { . return false; . } . 12,772 ( 0.00%) matches!(self.type_dependent_defs().get(expr.hir_id), Some(Ok((DefKind::AssocFn, _)))) 12,636 ( 0.00%) } . 2,121 ( 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 . }) 2,828 ( 0.00%) } . . pub fn pat_binding_modes(&self) -> LocalTableInContext<'_, BindingMode> { 1,831 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_binding_modes } 562 ( 0.00%) } . . pub fn pat_binding_modes_mut(&mut self) -> LocalTableInContextMut<'_, BindingMode> { 936 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_binding_modes } 468 ( 0.00%) } . . pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec>> { 2,748 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_adjustments } 1,374 ( 0.00%) } . . pub fn pat_adjustments_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { 854 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_adjustments } 427 ( 0.00%) } . . /// For a given closure, returns the iterator of `ty::CapturedPlace`s that are captured . /// by the closure. 480 ( 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() 600 ( 0.00%) } . . pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, HirPlace<'tcx>)> { 110 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.closure_kind_origins } 55 ( 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>> { 322 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.liberated_fn_sigs } 161 ( 0.00%) } . . pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<'_, ty::FnSig<'tcx>> { 212 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.liberated_fn_sigs } 106 ( 0.00%) } . . pub fn fru_field_types(&self) -> LocalTableInContext<'_, Vec>> { 110 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.fru_field_types } 55 ( 0.00%) } . . pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { . LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.fru_field_types } . } . 51 ( 0.00%) pub fn is_coercion_cast(&self, hir_id: hir::HirId) -> bool { 17 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, hir_id); . self.coercion_casts.contains(&hir_id.local_id) 34 ( 0.00%) } . . pub fn set_coercion_cast(&mut self, id: ItemLocalId) { . self.coercion_casts.insert(id); . } . . pub fn coercion_casts(&self) -> &ItemLocalSet { 55 ( 0.00%) &self.coercion_casts 55 ( 0.00%) } . } . . impl<'a, 'tcx> HashStable> for TypeckResults<'tcx> { . fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { . let ty::TypeckResults { . hir_owner, . ref type_dependent_defs, . ref field_indices, -- line 764 ---------------------------------------- -- line 819 ---------------------------------------- . const START_INDEX = 0, . } . } . . /// Mapping of type annotation indices to canonical user type annotations. . pub type CanonicalUserTypeAnnotations<'tcx> = . IndexVec>; . 58 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)] . pub struct CanonicalUserTypeAnnotation<'tcx> { . pub user_ty: CanonicalUserType<'tcx>, . pub span: Span, 29 ( 0.00%) pub inferred_ty: Ty<'tcx>, . } . . /// Canonicalized user type annotation. . pub type CanonicalUserType<'tcx> = Canonical<'tcx, UserType<'tcx>>; . . impl<'tcx> CanonicalUserType<'tcx> { . /// Returns `true` if this represents a substitution of the form `[?0, ?1, ?2]`, . /// i.e., each thing is mapped to a canonical variable with the same index. 159 ( 0.00%) pub fn is_identity(&self) -> bool { 318 ( 0.00%) match self.value { . UserType::Ty(_) => false, . UserType::TypeOf(_, user_substs) => { 159 ( 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() { 386 ( 0.00%) GenericArgKind::Type(ty) => match ty.kind() { . ty::Bound(debruijn, b) => { . // We only allow a `ty::INNERMOST` index in substitutions. 193 ( 0.00%) assert_eq!(*debruijn, ty::INNERMOST); . cvar == b.var . } . _ => false, . }, . 28 ( 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, . }, . } . }) . } . } 318 ( 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. 174 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, TyEncodable, TyDecodable)] 1,709 ( 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> { 2,940 ( 0.00%) pub fn typeck_opt_const_arg( . self, . def: ty::WithOptConstParam, . ) -> &'tcx TypeckResults<'tcx> { 1,176 ( 0.00%) if let Some(param_did) = def.const_param_did { . self.typeck_const_arg((def.did, param_did)) . } else { . self.typeck(def.did) . } 2,352 ( 0.00%) } . 198 ( 0.00%) pub fn alloc_steal_thir(self, thir: Thir<'tcx>) -> &'tcx Steal> { 66 ( 0.00%) self.arena.alloc(Steal::new(thir)) 264 ( 0.00%) } . 1,055 ( 0.00%) pub fn alloc_steal_mir(self, mir: Body<'tcx>) -> &'tcx Steal> { 211 ( 0.00%) self.arena.alloc(Steal::new(mir)) 1,477 ( 0.00%) } . 264 ( 0.00%) pub fn alloc_steal_promoted( . self, . promoted: IndexVec>, . ) -> &'tcx Steal>> { 66 ( 0.00%) self.arena.alloc(Steal::new(promoted)) 330 ( 0.00%) } . 405 ( 0.00%) pub fn alloc_adt_def( . self, . did: DefId, . kind: AdtKind, . variants: IndexVec, . repr: ReprOptions, . ) -> &'tcx ty::AdtDef { 720 ( 0.00%) self.intern_adt_def(ty::AdtDef::new(self, did, kind, variants, repr)) 180 ( 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? 111,848 ( 0.00%) pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound, Bound) { 55,924 ( 0.00%) let attrs = self.get_attrs(def_id); 237,677 ( 0.01%) let get = |name| { 55,924 ( 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); . if let Some( . &[ . ast::NestedMetaItem::Literal(ast::Lit { . kind: ast::LitKind::Int(a, _), .. -- line 1111 ---------------------------------------- -- line 1114 ---------------------------------------- . ) = 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 . } 279,620 ( 0.01%) }; 83,886 ( 0.00%) ( 83,886 ( 0.00%) get(sym::rustc_layout_scalar_valid_range_start), 41,943 ( 0.00%) get(sym::rustc_layout_scalar_valid_range_end), . ) 111,848 ( 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 }) . } . 56 ( 0.00%) pub fn consider_optimizing String>(self, msg: T) -> bool { 8 ( 0.00%) let cname = self.crate_name(LOCAL_CRATE); 64 ( 0.00%) self.sess.consider_optimizing(cname.as_str(), msg) 64 ( 0.00%) } . . /// Obtain all lang items of this crate and all dependencies (recursively) 1,854,461 ( 0.07%) pub fn lang_items(self) -> &'tcx rustc_hir::lang_items::LanguageItems { . self.get_lang_items(()) 2,384,307 ( 0.09%) } . . /// 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. 21 ( 0.00%) pub fn get_diagnostic_item(self, name: Symbol) -> Option { . self.all_diagnostic_items(()).name_to_id.get(&name).copied() 24 ( 0.00%) } . . /// Obtain the diagnostic item's name 125,510 ( 0.00%) pub fn get_diagnostic_name(self, id: DefId) -> Option { . self.diagnostic_items(id.krate).id_to_name.get(&id).copied() 143,440 ( 0.01%) } . . /// Check whether the diagnostic item with the given `name` has the given `DefId`. 4,207 ( 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) 4,808 ( 0.00%) } . 994 ( 0.00%) pub fn stability(self) -> &'tcx stability::Index<'tcx> { . self.stability_index(()) 1,278 ( 0.00%) } . 520,023 ( 0.02%) pub fn features(self) -> &'tcx rustc_feature::Features { . self.features_query(()) 594,312 ( 0.02%) } . . pub fn def_key(self, id: DefId) -> rustc_hir::definitions::DefKey { . // Accessing the DefKey is ok, since it is part of DefPathHash. 146,154 ( 0.01%) if let Some(id) = id.as_local() { . self.untracked_resolutions.definitions.def_key(id) . } else { 2,080 ( 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. 568 ( 0.00%) if let Some(def_id) = def_id.as_local() { . self.untracked_resolutions.definitions.def_path_hash(def_id) . } else { 116 ( 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 { 45,598 ( 0.00%) &*self.untracked_resolutions.cstore 22,799 ( 0.00%) } . . /// Note that this is *untracked* and should only be used within the query . /// system if the result is otherwise tracked through queries . pub fn definitions_untracked(self) -> &'tcx hir::definitions::Definitions { . &self.untracked_resolutions.definitions . } . . #[inline(always)] . pub fn create_stable_hashing_context(self) -> StableHashingContext<'tcx> { 14 ( 0.00%) let resolutions = &self.gcx.untracked_resolutions; 69 ( 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.) 110 ( 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=...` . 165 ( 0.00%) if self.features().nll { . return BorrowckMode::Mir; . } . 55 ( 0.00%) self.sess.opts.borrowck_mode 220 ( 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")`). 561 ( 0.00%) pub fn article_and_description(self, def_id: DefId) -> (&'static str, &'static str) { 408 ( 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"), . }, 918 ( 0.00%) def_kind => (def_kind.article(), def_kind.descr(def_id)), . } 459 ( 0.00%) } . . pub fn type_length_limit(self) -> Limit { . self.limits(()).type_length_limit . } . 264,313 ( 0.01%) pub fn recursion_limit(self) -> Limit { . self.limits(()).recursion_limit 302,072 ( 0.01%) } . . pub fn move_size_limit(self) -> Limit { . self.limits(()).move_size_limit . } . 133 ( 0.00%) pub fn const_eval_limit(self) -> Limit { . self.limits(()).const_eval_limit 152 ( 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`. 1 ( 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(); 34,330 ( 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(); 148,992 ( 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 { 73,911 ( 0.00%) assert!(ptr_eq(context.tcx.gcx, tcx.gcx)); . let context: &ImplicitCtxt<'_, '_> = mem::transmute(context); 73,870 ( 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> { 105,390 ( 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)`. 42,996 ( 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>> { 82,164 ( 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)`. 7,164 ( 0.00%) self.0.kind.hash(s) . } . } . . impl<'tcx, T> Borrow<[T]> for Interned<'tcx, List> { . fn borrow<'a>(&'a self) -> &'a [T] { 200,403 ( 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)`. 16,485 ( 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 { 87,252 ( 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)`. 32,574 ( 0.00%) self.0.hash(s) . } . } . . impl<'tcx> TyCtxt<'tcx> { 799,808 ( 0.03%) pub fn $method(self, v: $ty) -> &'tcx $ty { 356,871 ( 0.01%) self.interners.$name.intern(v, |v| { 7,296 ( 0.00%) Interned(self.interners.arena.alloc(v)) . }).0 835,938 ( 0.03%) } . })+ . } . } . . 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> { 2,164,072 ( 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 1,913,805 ( 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> { 11,972 ( 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> { 785,362 ( 0.03%) self.interners.intern_ty(st) . } . . #[inline] . pub fn mk_predicate(self, binder: Binder<'tcx, PredicateKind<'tcx>>) -> Predicate<'tcx> { 965,659 ( 0.04%) let inner = self.interners.intern_predicate(binder); . Predicate { inner } . } . . #[inline] 103,224 ( 0.00%) pub fn reuse_or_mk_predicate( . self, . pred: Predicate<'tcx>, . binder: Binder<'tcx, PredicateKind<'tcx>>, . ) -> Predicate<'tcx> { 6,990 ( 0.00%) if pred.kind() != binder { self.mk_predicate(binder) } else { pred } 103,224 ( 0.00%) } . . pub fn mk_mach_int(self, tm: IntTy) -> Ty<'tcx> { 950 ( 0.00%) match tm { . IntTy::Isize => self.types.isize, . IntTy::I8 => self.types.i8, . IntTy::I16 => self.types.i16, . IntTy::I32 => self.types.i32, . IntTy::I64 => self.types.i64, . IntTy::I128 => self.types.i128, . } 950 ( 0.00%) } . . pub fn mk_mach_uint(self, tm: UintTy) -> Ty<'tcx> { 1,072 ( 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, . } 1,072 ( 0.00%) } . . pub fn mk_mach_float(self, tm: FloatTy) -> Ty<'tcx> { . match tm { . FloatTy::F32 => self.types.f32, . FloatTy::F64 => self.types.f64, . } . } . . #[inline] . pub fn mk_static_str(self) -> Ty<'tcx> { 64 ( 0.00%) self.mk_imm_ref(self.lifetimes.re_static, self.types.str_) . } . . #[inline] . pub fn mk_adt(self, def: &'tcx AdtDef, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . // Take a copy of substs so that we own the vectors inside. . self.mk_ty(Adt(def, substs)) . } . -- line 2259 ---------------------------------------- -- line 2329 ---------------------------------------- . } . . #[inline] . pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> { . self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Not }) . } . . #[inline] 92 ( 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))) 96 ( 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> { 588 ( 0.00%) let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect(); 987 ( 0.00%) self.mk_ty(Tuple(self.intern_substs(&kinds))) . } . . pub fn mk_tup], Ty<'tcx>>>(self, iter: I) -> I::Output { 3,020 ( 0.00%) iter.intern_with(|ts| { 21,854 ( 0.00%) let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect(); 32,561 ( 0.00%) self.mk_ty(Tuple(self.intern_substs(&kinds))) 2,718 ( 0.00%) }) . } . . #[inline] . pub fn mk_unit(self) -> Ty<'tcx> { 207 ( 0.00%) self.types.unit . } . . #[inline] . pub fn mk_diverging_default(self) -> Ty<'tcx> { . if self.features().never_type_fallback { self.types.never } else { self.types.unit } . } . . #[inline] . pub fn mk_fn_def(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . self.mk_ty(FnDef(def_id, substs)) . } . . #[inline] . pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> { 170 ( 0.00%) self.mk_ty(FnPtr(fty)) . } . . #[inline] . pub fn mk_dynamic( . self, . obj: &'tcx List>>, . reg: ty::Region<'tcx>, . ) -> Ty<'tcx> { -- line 2384 ---------------------------------------- -- line 2412 ---------------------------------------- . . #[inline] . pub fn mk_ty_var(self, v: TyVid) -> Ty<'tcx> { . self.mk_ty_infer(TyVar(v)) . } . . #[inline] . pub fn mk_const_var(self, v: ConstVid<'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> { 882 ( 0.00%) self.mk_const(ty::Const { val: ty::ConstKind::Infer(InferConst::Var(v)), ty }) . } . . #[inline] . pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> { . self.mk_ty_infer(IntVar(v)) . } . . #[inline] -- line 2428 ---------------------------------------- -- line 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 }) . } . 686 ( 0.00%) pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 432 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { 174 ( 0.00%) self.mk_region(ty::ReEarlyBound(param.to_early_bound_region_data())).into() . } 138 ( 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() . } . } 686 ( 0.00%) } . . #[inline] . pub fn mk_opaque(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . self.mk_ty(Opaque(def_id, substs)) . } . 27,225 ( 0.00%) pub fn mk_place_field(self, place: Place<'tcx>, f: Field, ty: Ty<'tcx>) -> Place<'tcx> { 27,225 ( 0.00%) self.mk_place_elem(place, PlaceElem::Field(f, ty)) 54,450 ( 0.00%) } . . pub fn mk_place_deref(self, place: Place<'tcx>) -> Place<'tcx> { . self.mk_place_elem(place, PlaceElem::Deref) . } . 8,054 ( 0.00%) pub fn mk_place_downcast( . self, . place: Place<'tcx>, . adt_def: &'tcx AdtDef, . variant_index: VariantIdx, . ) -> Place<'tcx> { 8,054 ( 0.00%) self.mk_place_elem( . place, 16,108 ( 0.00%) PlaceElem::Downcast(Some(adt_def.variants[variant_index].name), variant_index), . ) 16,108 ( 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. 317,511 ( 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) } 352,790 ( 0.01%) } . 357 ( 0.00%) pub fn intern_poly_existential_predicates( . self, . eps: &[ty::Binder<'tcx, ExistentialPredicate<'tcx>>], . ) -> &'tcx List>> { 51 ( 0.00%) assert!(!eps.is_empty()); . assert!( . eps.array_windows() 70 ( 0.00%) .all(|[a, b]| a.skip_binder().stable_cmp(self, &b.skip_binder()) . != Ordering::Greater) . ); 204 ( 0.00%) self._intern_poly_existential_predicates(eps) 408 ( 0.00%) } . . pub fn intern_predicates(self, preds: &[Predicate<'tcx>]) -> &'tcx List> { . // FIXME consider asking the input slice to be sorted to avoid . // re-interning permutations, in which case that would be asserted . // here. 2,449 ( 0.00%) if preds.is_empty() { . // The macro-generated method below asserts we don't intern an empty slice. . List::empty() . } else { 209 ( 0.00%) self._intern_predicates(preds) . } 4,480 ( 0.00%) } . . pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List> { 7,508 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_type_list(ts) } 88 ( 0.00%) } . . pub fn intern_substs(self, ts: &[GenericArg<'tcx>]) -> &'tcx List> { 327,782 ( 0.01%) if ts.is_empty() { List::empty() } else { self._intern_substs(ts) } 51,996 ( 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> { 72,472 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_place_elems(ts) } 1,112 ( 0.00%) } . . pub fn intern_canonical_var_infos( . self, . ts: &[CanonicalVarInfo<'tcx>], . ) -> CanonicalVarInfos<'tcx> { 3,263 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_canonical_var_infos(ts) } 74 ( 0.00%) } . . pub fn intern_bound_variable_kinds( . self, . ts: &[ty::BoundVariableKind], . ) -> &'tcx List { 1,216 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_bound_variable_kinds(ts) } 1,826 ( 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 { 495 ( 0.00%) inputs_and_output: self.intern_type_list(xs), 82 ( 0.00%) c_variadic, 115 ( 0.00%) unsafety, 98 ( 0.00%) abi, 110 ( 0.00%) }) . } . . pub fn mk_poly_existential_predicates< . I: InternAs< . [ty::Binder<'tcx, ExistentialPredicate<'tcx>>], . &'tcx List>>, . >, . >( . self, . iter: I, . ) -> I::Output { 184 ( 0.00%) iter.intern_with(|xs| self.intern_poly_existential_predicates(xs)) . } . . pub fn mk_predicates], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 2 ( 0.00%) iter.intern_with(|xs| self.intern_predicates(xs)) . } . . pub fn mk_type_list], &'tcx List>>>(self, iter: I) -> I::Output { 920 ( 0.00%) iter.intern_with(|xs| self.intern_type_list(xs)) . } . . pub fn mk_substs], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 274,522 ( 0.01%) iter.intern_with(|xs| self.intern_substs(xs)) . } . . pub fn mk_place_elems], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { . iter.intern_with(|xs| self.intern_place_elems(xs)) . } . 65,893 ( 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())) 131,786 ( 0.01%) } . . pub fn mk_bound_variable_kinds< . I: InternAs<[ty::BoundVariableKind], &'tcx List>, . >( . self, . iter: I, . ) -> I::Output { 7,901 ( 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. 549,766 ( 0.02%) pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId { 549,766 ( 0.02%) let hir = self.hir(); . loop { 776,094 ( 0.03%) if id == bound { . return bound; . } . 901,120 ( 0.04%) 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); 540,480 ( 0.02%) if next == id { . bug!("lint traversal reached the root of the crate"); . } . id = next; . } 785,380 ( 0.03%) } . 1,000 ( 0.00%) pub fn lint_level_at_node( . self, . lint: &'static Lint, . mut id: hir::HirId, . ) -> (Level, LintLevelSource) { . let sets = self.lint_levels(()); . loop { 5,395 ( 0.00%) if let Some(pair) = sets.level_and_source(lint, id, self.sess) { . return pair; . } 405 ( 0.00%) let next = self.hir().get_parent_node(id); 1,215 ( 0.00%) if next == id { . bug!("lint traversal reached the root of the crate"); . } . id = next; . } 1,000 ( 0.00%) } . 28 ( 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>), . ) { 158 ( 0.00%) let (level, src) = self.lint_level_at_node(lint, hir_id); 41 ( 0.00%) struct_lint_level(self.sess, lint, level, src, Some(span.into()), decorate); 16 ( 0.00%) } . . pub fn struct_lint_node( . self, . lint: &'static Lint, . id: HirId, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { . let (level, src) = self.lint_level_at_node(lint, id); . struct_lint_level(self.sess, lint, level, src, None, decorate); . } . 1,099 ( 0.00%) pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx [TraitCandidate]> { 314 ( 0.00%) let map = self.in_scope_traits_map(id.owner)?; . let candidates = map.get(&id.local_id)?; 314 ( 0.00%) Some(&*candidates) 1,256 ( 0.00%) } . 1,267 ( 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()) 1,629 ( 0.00%) } . 171 ( 0.00%) pub fn is_late_bound(self, id: HirId) -> bool { . self.is_late_bound_map(id.owner) 14 ( 0.00%) .map_or(false, |(owner, set)| owner == id.owner && set.contains(&id.local_id)) 152 ( 0.00%) } . 1,239 ( 0.00%) pub fn object_lifetime_defaults(self, id: HirId) -> Option> { . self.object_lifetime_defaults_map(id.owner) 1,593 ( 0.00%) } . 657 ( 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(), . ) 657 ( 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 120 ( 0.00%) pub fn is_const_fn(self, def_id: DefId) -> bool { 12 ( 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 . } 108 ( 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; 80,152 ( 0.00%) fn intern_with(self, f: F) -> Self::Output . where . F: FnOnce(&[T]) -> R, . { 871,728 ( 0.03%) E::intern_with(self, f) 82,116 ( 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; 263,804 ( 0.01%) 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`. 411,586 ( 0.02%) match iter.size_hint() { . (0, Some(0)) => { 3 ( 0.00%) assert!(iter.next().is_none()); . f(&[]) . } . (1, Some(1)) => { . let t0 = iter.next().unwrap(); 4 ( 0.00%) assert!(iter.next().is_none()); 44,200 ( 0.00%) f(&[t0]) . } . (2, Some(2)) => { . let t0 = iter.next().unwrap(); . let t1 = iter.next().unwrap(); 44 ( 0.00%) assert!(iter.next().is_none()); 63,475 ( 0.00%) f(&[t0, t1]) . } 152 ( 0.00%) _ => f(&iter.collect::>()), . } 324,609 ( 0.01%) } . } . . impl<'a, T, R> InternIteratorElement for &'a T . where . T: Clone + 'a, . { . type Output = R; 508 ( 0.00%) fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output { . // This code isn't hot. 44 ( 0.00%) f(&iter.cloned().collect::>()) 446 ( 0.00%) } . } . . impl InternIteratorElement for Result { . type Output = Result; 144,319 ( 0.01%) 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. 101,238 ( 0.00%) Ok(match iter.size_hint() { . (0, Some(0)) => { . assert!(iter.next().is_none()); . f(&[]) . } . (1, Some(1)) => { 102 ( 0.00%) let t0 = iter.next().unwrap()?; . assert!(iter.next().is_none()); 2,326 ( 0.00%) f(&[t0]) . } . (2, Some(2)) => { 118 ( 0.00%) let t0 = iter.next().unwrap()?; 118 ( 0.00%) let t1 = iter.next().unwrap()?; 177 ( 0.00%) assert!(iter.next().is_none()); 6,370 ( 0.00%) f(&[t0, t1]) . } 354 ( 0.00%) _ => f(&iter.collect::, _>>()?), . }) 162,954 ( 0.01%) } . } . . // 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 { 73,911 ( 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 = 1,120 ( 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| { . assert_eq!(cnum, LOCAL_CRATE); . tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::panic_runtime) . }; 2 ( 0.00%) providers.is_compiler_builtins = |tcx, cnum| { . assert_eq!(cnum, LOCAL_CRATE); . 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()) . }; . } 1,603,308 ( 0.06%) -------------------------------------------------------------------------------- -- 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> { 163,148 ( 0.01%) fn reverse(&mut self, undo: UndoLog<'tcx>) { 687,338 ( 0.03%) match undo { 128,402 ( 0.01%) UndoLog::EqRelation(undo) => self.eq_relations.reverse(undo), 69,640 ( 0.00%) UndoLog::SubRelation(undo) => self.sub_relations.reverse(undo), 128,254 ( 0.01%) UndoLog::Values(undo) => self.values.reverse(undo), . } 326,296 ( 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, . } . 367,724 ( 0.01%) #[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> { 175,120 ( 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> { 10,971 ( 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 { 91 ( 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()); 476 ( 0.00%) self.eq_relations().union(a, b); 408 ( 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()); 257 ( 0.00%) self.sub_relations().union(a, b); . } . . /// Instantiates `vid` with the type `ty`. . /// . /// Precondition: `vid` must not have been previously instantiated. 154,350 ( 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) . ); 216,090 ( 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); 154,350 ( 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. 217,518 ( 0.01%) pub fn new_var( . &mut self, . universe: ty::UniverseIndex, . origin: TypeVariableOrigin, . ) -> ty::TyVid { 326,277 ( 0.01%) let eq_key = self.eq_relations().new_key(TypeVariableValue::Unknown { universe }); . 181,265 ( 0.01%) let sub_key = self.sub_relations().new_key(()); 36,253 ( 0.00%) assert_eq!(eq_key.vid, sub_key); . 326,277 ( 0.01%) let index = self.values().push(TypeVariableData { origin }); 145,012 ( 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 253,771 ( 0.01%) } . . /// Returns the number of type variables created thus far. . pub fn num_vars(&self) -> usize { 11,861 ( 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 { 95,787 ( 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) 22 ( 0.00%) pub fn sub_root_var(&mut self, vid: ty::TyVid) -> ty::TyVid { 92,910 ( 0.00%) self.sub_relations().find(vid) 44 ( 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. 764,390 ( 0.03%) pub fn probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> { . self.inlined_probe(vid) 764,390 ( 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> { 333,344 ( 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> { 242,522 ( 0.01%) match *t.kind() { 217,267 ( 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>> { 674,924 ( 0.03%) self.storage.eq_relations.with_log(self.undo_log) . } . . #[inline] . fn sub_relations(&mut self) -> super::UnificationTable<'_, 'tcx, ty::TyVid> { 67,443 ( 0.00%) self.storage.sub_relations.with_log(self.undo_log) . } . . /// Returns a range of the type variables created during the snapshot. 59,305 ( 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()); 71,166 ( 0.00%) ( . range.start..range.end, . (range.start.as_usize()..range.end.as_usize()) . .map(|index| self.storage.values.get(index).origin) . .collect(), . ) 71,166 ( 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); 9,844 ( 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: 258,438 ( 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 { 123,820 ( 0.00%) 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? . ( 68 ( 0.00%) &TypeVariableValue::Unknown { universe: universe1 }, 68 ( 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); 272 ( 0.00%) Ok(TypeVariableValue::Unknown { universe }) . } . } . } . } 90,398 ( 0.00%) -------------------------------------------------------------------------------- -- 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> { 65 ( 0.00%) pub fn new( . sess: &'s Session, . warn_about_weird_lints: bool, . store: &'s LintStore, . registered_tools: &'s RegisteredTools, . ) -> Self { 55 ( 0.00%) let mut builder = LintLevelsBuilder { . sess, 5 ( 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); 15 ( 0.00%) assert_eq!(builder.sets.list.len(), 1); . builder 45 ( 0.00%) } . . pub(crate) fn sess(&self) -> &Session { 1,681 ( 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(); 10 ( 0.00%) self.sets.lint_cap = sess.opts.lint_cap.unwrap_or(Level::Forbid); . 10 ( 0.00%) for &(ref lint_name, level) in &sess.opts.lint_opts { 50 ( 0.00%) store.check_lint_name_cmdline(sess, &lint_name, level, self.registered_tools); . let orig_level = level; 20 ( 0.00%) let lint_flag_val = Symbol::intern(lint_name); . 50 ( 0.00%) let ids = match store.find_lints(&lint_name) { 40 ( 0.00%) Ok(ids) => ids, . Err(_) => continue, // errors handled in check_lint_name_cmdline above . }; 30 ( 0.00%) for id in ids { . // ForceWarn and Forbid cannot be overriden . if let Some((Level::ForceWarn | Level::Forbid, _)) = specs.get(&id) { . continue; . } . 40 ( 0.00%) self.check_gated_lint(id, DUMMY_SP); . let src = LintLevelSource::CommandLine(lint_flag_val, orig_level); 20 ( 0.00%) specs.insert(id, (level, src)); . } . } . 40 ( 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`. 264 ( 0.00%) fn insert_spec( . &mut self, . specs: &mut FxHashMap, . id: LintId, 144 ( 0.00%) (level, src): LevelAndSource, . ) { 120 ( 0.00%) let (old_level, old_src) = 168 ( 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. 24 ( 0.00%) if level != Level::Forbid { 96 ( 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 { 96 ( 0.00%) specs.insert(id, (level, src)); . } 192 ( 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`! 883,192 ( 0.03%) pub(crate) fn push(&mut self, attrs: &[ast::Attribute], is_crate_node: bool) -> BuilderPush { . let mut specs = FxHashMap::default(); 220,798 ( 0.01%) let sess = self.sess; 110,399 ( 0.00%) let bad_attr = |span| struct_span_err!(sess, span, E0452, "malformed lint attribute input"); . for attr in attrs { 2,401 ( 0.00%) let Some(level) = Level::from_symbol(attr.name_or_empty()) else { . continue . }; . 297 ( 0.00%) let Some(mut metas) = attr.meta_item_list() else { . continue . }; . 33 ( 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; 33 ( 0.00%) let tail_li = &metas[metas.len() - 1]; 99 ( 0.00%) if let Some(item) = tail_li.meta_item() { 165 ( 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(); . } . } . } . 726 ( 0.00%) for li in metas { 132 ( 0.00%) let sp = li.span(); 66 ( 0.00%) let mut meta_item = match li { 594 ( 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; . } . }; 99 ( 0.00%) let tool_ident = if meta_item.path.segments.len() > 1 { 36 ( 0.00%) Some(meta_item.path.segments.remove(0).ident) . } else { 24 ( 0.00%) None . }; 33 ( 0.00%) let tool_name = tool_ident.map(|ident| ident.name); 99 ( 0.00%) let name = pprust::path_to_string(&meta_item.path); . let lint_result = 165 ( 0.00%) self.store.check_lint_name(&name, tool_name, self.registered_tools); 135 ( 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, . ); 72 ( 0.00%) for &id in *ids { 120 ( 0.00%) self.check_gated_lint(id, attr.span); 288 ( 0.00%) self.insert_spec(&mut specs, id, (level, src)); . } . } . . CheckLintNameResult::Tool(result) => { 45 ( 0.00%) match *result { . Ok(ids) => { . let complete_name = . &format!("{}::{}", tool_ident.unwrap().name, name); . let src = LintLevelSource::Node( . Symbol::intern(complete_name), . sp, . reason, . ); -- line 340 ---------------------------------------- -- 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. 165 ( 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); . } . } 132 ( 0.00%) } . } . 220,798 ( 0.01%) if !is_crate_node { 48 ( 0.00%) for (id, &(level, ref src)) in specs.iter() { 72 ( 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; . } . } . 110,399 ( 0.00%) let prev = self.cur; 110,399 ( 0.00%) if !specs.is_empty() { 144 ( 0.00%) self.cur = self.sets.list.push(LintSet { specs, parent: prev }); . } . . BuilderPush { prev, changed: prev != self.cur } 993,591 ( 0.04%) } . . /// Checks if the lint is gated on a feature that is not enabled. 238 ( 0.00%) fn check_gated_lint(&self, lint_id: LintId, span: Span) { 102 ( 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(); . } . } 272 ( 0.00%) } . . /// Called after `push` when the scope of a set of attributes are exited. . pub fn pop(&mut self, push: BuilderPush) { 129,799 ( 0.01%) self.cur = push.prev; 65,111 ( 0.00%) } . . /// Find the lint level for a lint. 48 ( 0.00%) pub fn lint_level(&self, lint: &'static Lint) -> (Level, LintLevelSource) { 176 ( 0.00%) self.sets.get_lint_level(lint, self.cur, None, self.sess) 72 ( 0.00%) } . . /// Used to emit a lint-related diagnostic based on the current state of . /// this lint context. 264 ( 0.00%) pub fn struct_lint( . &self, . lint: &'static Lint, . span: Option, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { 192 ( 0.00%) let (level, src) = self.lint_level(lint); 24 ( 0.00%) struct_lint_level(self.sess, lint, level, src, span, decorate) 168 ( 0.00%) } . . /// Registers the ID provided with the current set of lints stored in . /// this context. . pub fn register_id(&mut self, id: HirId) { 25 ( 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; 268,441 ( 0.01%) let attrs = self.tcx.hir().attrs(id); 268,548 ( 0.01%) let push = self.levels.push(attrs, is_crate_hir); 44,767 ( 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 { 173 ( 0.00%) self.tcx.hir() . } . . fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) { 148 ( 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>) { 79 ( 0.00%) self.with_lint_attrs(it.hir_id(), |builder| { 237 ( 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. 834 ( 0.00%) intravisit::walk_stmt(self, e); . } . 468 ( 0.00%) fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) { 88,701 ( 0.00%) self.with_lint_attrs(e.hir_id, |builder| { 153,126 ( 0.01%) intravisit::walk_expr(builder, e); . }) 416 ( 0.00%) } . . fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) { 108 ( 0.00%) self.with_lint_attrs(s.hir_id, |builder| { . intravisit::walk_field_def(builder, s); . }) . } . . fn visit_variant( . &mut self, . v: &'tcx hir::Variant<'tcx>, . g: &'tcx hir::Generics<'tcx>, . item_id: hir::HirId, . ) { 16 ( 0.00%) 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>) { 170 ( 0.00%) self.with_lint_attrs(l.hir_id, |builder| { 340 ( 0.00%) intravisit::walk_local(builder, l); . }) . } . . fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) { 212 ( 0.00%) self.with_lint_attrs(a.hir_id, |builder| { 424 ( 0.00%) intravisit::walk_arm(builder, a); . }) . } . . fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) { . self.with_lint_attrs(trait_item.hir_id(), |builder| { . intravisit::walk_trait_item(builder, trait_item); . }); . } . . fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) { 28 ( 0.00%) self.with_lint_attrs(impl_item.hir_id(), |builder| { 84 ( 0.00%) intravisit::walk_impl_item(builder, impl_item); . }); . } . } . . pub fn provide(providers: &mut Providers) { 2 ( 0.00%) providers.lint_levels = lint_levels; . } 110,824 ( 0.00%) -------------------------------------------------------------------------------- -- 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 { 306,781 ( 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, ()> { 666 ( 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> { . vec![] . } . . fn simple<'tcx>(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec> { 198 ( 0.00%) move |target| vec![Adjustment { kind, target }] . } . . /// This always returns `Ok(...)`. . fn success<'tcx>( . adj: Vec>, . target: Ty<'tcx>, . obligations: traits::PredicateObligations<'tcx>, . ) -> CoerceResult<'tcx> { 84,480 ( 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 { 224,797 ( 0.01%) Coerce { fcx, cause, allow_two_phase, use_lub: false } . } . 612,194 ( 0.02%) 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(|_| { 111,308 ( 0.00%) if self.use_lub { 98 ( 0.00%) self.at(&self.cause, self.fcx.param_env).lub(b, a) . } else { 111,210 ( 0.00%) self.at(&self.cause, self.fcx.param_env) . .sup(b, a) . .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations }) . } . }) 445,232 ( 0.02%) } . . /// Unify two types (using sub or lub) and produce a specific coercion. 111,596 ( 0.00%) fn unify_and(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F) -> CoerceResult<'tcx> . where . F: FnOnce(Ty<'tcx>) -> Vec>, . { 138,453 ( 0.01%) self.unify(&a, &b) 110,432 ( 0.00%) .and_then(|InferOk { value: ty, obligations }| success(f(ty), ty, obligations)) 83,697 ( 0.00%) } . 590,478 ( 0.02%) #[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): 28,118 ( 0.00%) let a = self.shallow_resolve(a); 28,118 ( 0.00%) let b = self.shallow_resolve(b); . debug!("Coerce.tys({:?} => {:?})", a, b); . . // Just ignore error types. 56,236 ( 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: 28,118 ( 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. 28,214 ( 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)); 112,084 ( 0.00%) match unsize { . Ok(_) => { . debug!("coerce: unsize successful"); 120 ( 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. 139,871 ( 0.01%) match *b.kind() { . ty::RawPtr(mt_b) => { . return self.coerce_unsafe_ptr(a, b, mt_b.mutbl); . } 214 ( 0.00%) ty::Ref(r_b, _, mutbl_b) => { 642 ( 0.00%) return self.coerce_borrowed_pointer(a, b, r_b, mutbl_b); . } . _ => {} . } . 195,370 ( 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. . 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) . } 33 ( 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. 88 ( 0.00%) self.coerce_closure_to_fn(a, closure_def_id_a, substs_a, b) . } . _ => { . // Otherwise, just use unification rules. 139,495 ( 0.01%) self.unify_and(a, b, identity) . } . } 56,236 ( 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>, . make_adjustments: impl FnOnce(Ty<'tcx>) -> Vec>, . ) -> CoerceResult<'tcx> { . debug!("coerce_from_inference_variable(a={:?}, b={:?})", a, b); 27 ( 0.00%) assert!(a.is_ty_var() && self.infcx.shallow_resolve(a) == a); 27 ( 0.00%) assert!(self.infcx.shallow_resolve(b) == b); . 29 ( 0.00%) if b.is_ty_var() { . // Two unresolved type variables: create a `Coerce` predicate. 3 ( 0.00%) let target_ty = if self.use_lub { . self.infcx.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::LatticeVariable, . span: self.cause.span, . }) . } else { . b . }; . . let mut obligations = Vec::with_capacity(2); . for &source_ty in &[a, b] { 2 ( 0.00%) if source_ty != target_ty { . obligations.push(Obligation::new( . self.cause.clone(), 1 ( 0.00%) self.param_env, 4 ( 0.00%) ty::Binder::dummy(ty::PredicateKind::Coerce(ty::CoercePredicate { . a: source_ty, . b: target_ty, . })) . .to_predicate(self.tcx()), . )); . } . } . . debug!( . "coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}", . target_ty, obligations . ); . let adjustments = make_adjustments(target_ty); 6 ( 0.00%) InferResult::Ok(InferOk { value: (adjustments, target_ty), obligations }) . } else { . // One unresolved type variable: just apply subtyping, we may be able . // 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. 1,070 ( 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. . 214 ( 0.00%) let (r_a, mt_a) = match *a.kind() { 321 ( 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), . }; . 214 ( 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; . 434 ( 0.00%) for (referent_ty, autoderefs) in autoderef.by_ref() { 434 ( 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. 220 ( 0.00%) let r = if !self.use_lub { . r_b // [2] above 6 ( 0.00%) } else if autoderefs == 1 { . r_a // [3] above . } else { 1 ( 0.00%) if r_borrow_var.is_none() { . // create var lazily, at most once . let coercion = Coercion(span); 5 ( 0.00%) let r = self.next_region_var(coercion); . r_borrow_var = Some(r); // [4] above . } . r_borrow_var.unwrap() . }; 110 ( 0.00%) let derefd_ty_a = self.tcx.mk_ref( . r, . TypeAndMut { . ty: referent_ty, . mutbl: mutbl_b, // [1] above . }, . ); 770 ( 0.00%) match self.unify(derefd_ty_a, b) { . Ok(ok) => { 428 ( 0.00%) found = Some(ok); . break; . } 9 ( 0.00%) Err(err) => { 3 ( 0.00%) if first_error.is_none() { 15 ( 0.00%) 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. 856 ( 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); . } . }; . 137 ( 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. 12 ( 0.00%) assert_eq!(mutbl_b, hir::Mutability::Not); // can only coerce &T -> &U 24 ( 0.00%) return success(vec![], ty, obligations); . } . 707 ( 0.00%) let InferOk { value: mut adjustments, obligations: o } = 101 ( 0.00%) self.adjust_steps_as_infer_ok(&autoderef); . obligations.extend(o); 1,919 ( 0.00%) obligations.extend(autoderef.into_obligations()); . . // Now apply the autoref. We have to extract the region out of . // the final ref type we got. 202 ( 0.00%) let r_borrow = match ty.kind() { . ty::Ref(r_borrow, _, _) => r_borrow, . _ => span_bug!(span, "expected a ref type, got {:?}", ty), . }; 404 ( 0.00%) let mutbl = match mutbl_b { . hir::Mutability::Not => AutoBorrowMutability::Not, . hir::Mutability::Mut => { . AutoBorrowMutability::Mut { allow_two_phase_borrow: self.allow_two_phase } . } . }; . adjustments.push(Adjustment { 101 ( 0.00%) kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)), . target: ty, . }); . . debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}", ty, adjustments); . 808 ( 0.00%) success(adjustments, ty, obligations) 856 ( 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. 28,133 ( 0.00%) if source.is_ty_var() { . debug!("coerce_unsized: source is a TyVar, bailing out"); . return Err(TypeError::Mismatch); . } 28,861 ( 0.00%) if target.is_ty_var() { . debug!("coerce_unsized: target is a TyVar, bailing out"); . return Err(TypeError::Mismatch); . } . . let traits = 331,296 ( 0.01%) (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait()); 110,432 ( 0.00%) 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`. 55,561 ( 0.00%) let reborrow = match (source.kind(), target.kind()) { 345 ( 0.00%) (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => { . coerce_mutbls(mutbl_a, mutbl_b)?; . 115 ( 0.00%) let coercion = Coercion(self.cause.span); 575 ( 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)), 115 ( 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, 27,608 ( 0.00%) span: self.cause.span, . }; 138,040 ( 0.01%) let coerce_target = self.next_ty_var(origin); 110,432 ( 0.00%) let mut coercion = self.unify_and(coerce_target, target, |target| { . let unsize = Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target }; 55,216 ( 0.00%) match reborrow { 137,465 ( 0.01%) None => vec![unsize], 1,610 ( 0.00%) Some((ref deref, ref autoref)) => vec![deref.clone(), autoref.clone(), unsize], . } . })?; . 27,608 ( 0.00%) let mut selcx = traits::SelectionContext::new(self); . . // Create an obligation for `Source: CoerceUnsized`. . let cause = ObligationCause::new( 55,216 ( 0.00%) self.cause.span, 55,216 ( 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. 386,512 ( 0.02%) let mut queue: SmallVec<[_; 4]> = smallvec![traits::predicate_for_trait_def( 55,216 ( 0.00%) self.tcx, 27,608 ( 0.00%) self.fcx.param_env, 138,040 ( 0.01%) cause, . coerce_unsized_did, . 0, . coerce_source, 138,040 ( 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]; 55,644 ( 0.00%) while !queue.is_empty() { . let obligation = queue.remove(0); . debug!("coerce_unsized resolve step: {:?}", obligation); 27,814 ( 0.00%) let bound_predicate = obligation.predicate.kind(); 139,070 ( 0.01%) let trait_pred = match bound_predicate.skip_binder() { 166,410 ( 0.01%) ty::PredicateKind::Trait(trait_pred) if traits.contains(&trait_pred.def_id()) => { 249,507 ( 0.01%) if unsize_did == trait_pred.def_id() { 690 ( 0.00%) let self_ty = trait_pred.self_ty(); 460 ( 0.00%) let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty(); 575 ( 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; . } . } 690 ( 0.00%) if let ty::Tuple(..) = unsize_ty.kind() { . debug!("coerce_unsized: found unsized tuple coercion"); . has_unsized_tuple_coercion = true; . } . } 55,446 ( 0.00%) bound_predicate.rebind(trait_pred) . } . _ => { 546 ( 0.00%) coercion.obligations.push(obligation); . continue; . } . }; 304,953 ( 0.01%) match selcx.select(&obligation.with(trait_pred)) { . // Uncertain or unimplemented. . Ok(None) => { 156 ( 0.00%) if trait_pred.def_id() == unsize_did { 72 ( 0.00%) let trait_pred = self.resolve_vars_if_possible(trait_pred); 24 ( 0.00%) let self_ty = trait_pred.skip_binder().self_ty(); 72 ( 0.00%) let unsize_ty = trait_pred.skip_binder().trait_ref.substs[1].expect_ty(); . debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred); 24 ( 0.00%) match (&self_ty.kind(), &unsize_ty.kind()) { . (ty::Infer(ty::TyVar(v)), ty::Dynamic(..)) . if self.type_var_is_sized(*v) => . { . debug!("coerce_unsized: have sized infer {:?}", v); . coercion.obligations.push(obligation); . // `$0: Unsize` where we know that `$0: Sized`, try going . // for unsizing. . } -- line 671 ---------------------------------------- -- 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"); 165,528 ( 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. . } . 2,337 ( 0.00%) Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()), . } 55,200 ( 0.00%) } . 16 ( 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(); . } . 16 ( 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(); . } . 88 ( 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 819 ---------------------------------------- . . obligations.extend(o2); . Ok(InferOk { value, obligations }) . } . _ => self.unify_and(a, b, identity), . } . } . 154 ( 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); . 22 ( 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), . } 88 ( 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. 392,966 ( 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>> { 84,207 ( 0.00%) let source = self.resolve_vars_with_obligations(expr_ty); . debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target); . . let cause = 28,069 ( 0.00%) cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable)); . let coerce = Coerce::new(self, cause, allow_two_phase); 336,743 ( 0.01%) let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?; . 112,208 ( 0.00%) let (adjustments, _) = self.register_infer_ok_obligations(ok); 280,520 ( 0.01%) self.apply_adjustments(expr, adjustments); 84,156 ( 0.00%) Ok(if expr_ty.references_error() { self.tcx.ty_error() } else { target }) 252,621 ( 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. 130,702 ( 0.01%) 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, . { 60,324 ( 0.00%) let prev_ty = self.resolve_vars_with_obligations(prev_ty); 30,162 ( 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. 10,054 ( 0.00%) if prev_ty == new_ty { 9,971 ( 0.00%) return Ok(prev_ty); . } . . // Special-case that coercion alone cannot handle: . // Function items or non-capturing closures of differing IDs or InternalSubsts. 392 ( 0.00%) let (a_sig, b_sig) = { 392 ( 0.00%) let is_capturing_closure = |ty| { 196 ( 0.00%) if let &ty::Closure(closure_def_id, _substs) = ty { . self.tcx.upvars_mentioned(closure_def_id.expect_local()).is_some() . } else { . false . } 392 ( 0.00%) }; 588 ( 0.00%) if is_capturing_closure(prev_ty.kind()) || is_capturing_closure(new_ty.kind()) { . (None, None) . } else { 294 ( 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), . } . } . }; 196 ( 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); 49 ( 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; 392 ( 0.00%) if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) { 28,510 ( 0.00%) let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty)); 98 ( 0.00%) match result { . Ok(ok) => { 392 ( 0.00%) let (adjustments, target) = self.register_infer_ok_obligations(ok); 392 ( 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, . ); 98 ( 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) . } . } 90,486 ( 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 { 756 ( 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 . /// type-checking each of the alternative expressions whose types . /// we are trying to merge. . pub fn expected_ty(&self) -> Ty<'tcx> { 10 ( 0.00%) self.expected_ty . } . . /// Returns the current "merged type", representing our best-guess . /// at the LUB of the expressions we've seen so far (if any). This . /// isn't *final* until you call `self.final()`, which will return . /// the merged type. . pub fn merged_ty(&self) -> Ty<'tcx> { . 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. 119,388 ( 0.00%) pub fn coerce<'a>( . &mut self, . fcx: &FnCtxt<'a, 'tcx>, . cause: &ObligationCause<'tcx>, . expression: &'tcx hir::Expr<'tcx>, . expression_ty: Ty<'tcx>, . ) { 2,216 ( 0.00%) self.coerce_inner(fcx, cause, Some(expression), expression_ty, None, false) 79,592 ( 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 1310 ---------------------------------------- . /// removing a `;`). . pub fn coerce_forced_unit<'a>( . &mut self, . fcx: &FnCtxt<'a, 'tcx>, . cause: &ObligationCause<'tcx>, . augment_error: &mut dyn FnMut(&mut DiagnosticBuilder<'_>), . label_unit_as_expected: bool, . ) { 888 ( 0.00%) self.coerce_inner( . fcx, . cause, . None, 99 ( 0.00%) fcx.tcx.mk_unit(), . 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`. 10,143 ( 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. 10,498 ( 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. 41,728 ( 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. 1,449 ( 0.00%) let result = if let Some(expression) = expression { 30,999 ( 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 2,511 ( 0.00%) fcx.try_coerce( . expression, . expression_ty, . self.expected_ty, . AllowTwoPhase::No, 1,116 ( 0.00%) Some(cause.clone()), . ) . } else { 20,108 ( 0.00%) match self.expressions { 104 ( 0.00%) Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub( . cause, . exprs, . self.merged_ty(), . expression, . expression_ty, . ), 60,069 ( 0.00%) Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub( . cause, 30,006 ( 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 1394 ---------------------------------------- . // . // we wind up with a second match arm that is like `_ => . // ()`. That is the case we are considering here. We take . // a different path to get the right "expected, found" . // message and so forth (and because we know that . // `expression_ty` will be unit). . // . // Another example is `break` with no argument expression. 99 ( 0.00%) assert!(expression_ty.is_unit(), "if let hack without unit type"); 198 ( 0.00%) 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 . }) . }; . 20,874 ( 0.00%) match result { 10,531 ( 0.00%) Ok(v) => { 10,333 ( 0.00%) self.final_ty = Some(v); . if let Some(e) = expression { 20,666 ( 0.00%) match self.expressions { . Expressions::Dynamic(ref mut buffer) => buffer.push(e), 20,320 ( 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 40,429 ( 0.00%) assert_eq!( 30,480 ( 0.00%) coercion_sites[self.pushed].as_coercion_site().hir_id, . e.hir_id . ); . } . } 41,505 ( 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 . } . 512 ( 0.00%) pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> { 1,116 ( 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 `!`. 86 ( 0.00%) assert_eq!(self.pushed, 0); 43 ( 0.00%) fcx.tcx.types.never . } 640 ( 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<'_> { 105 ( 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<'_> { 212 ( 0.00%) &self.body . } . } 1,103,826 ( 0.04%) -------------------------------------------------------------------------------- -- 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. 275,403 ( 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. 1,087,572 ( 0.04%) 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`. 25 ( 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 { 15,571 ( 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 { 392,707 ( 0.02%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 326,110 ( 0.01%) assume(!self.end.is_null()); . } 38,455,924 ( 1.52%) if is_empty!(self) { . None . } else { . Some(next_unchecked!(self)) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 1,160,257 ( 0.05%) let exact = len!(self); . (exact, Some(exact)) . } . . #[inline] . fn count(self) -> usize { . len!(self) . } . . #[inline] . fn nth(&mut self, n: usize) -> Option<$elem> { 3,096 ( 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() { 685 ( 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, . { 155 ( 0.00%) while let Some(x) = self.next() { 4,305 ( 0.00%) if !f(x) { . return false; . } . } . true . } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] 8 ( 0.00%) fn any(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 1,081,573 ( 0.04%) while let Some(x) = self.next() { 1,209,123 ( 0.05%) if f(x) { . return true; . } . } . false 8 ( 0.00%) } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn find

(&mut self, mut predicate: P) -> Option . where . Self: Sized, . P: FnMut(&Self::Item) -> bool, . { 84,266 ( 0.00%) while let Some(x) = self.next() { 75,855 ( 0.00%) if predicate(&x) { . return Some(x); . } . } . None 1,155 ( 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, . { 8,014 ( 0.00%) while let Some(x) = self.next() { 335,190 ( 0.01%) if let Some(y) = f(x) { 60,257 ( 0.00%) return Some(y); . } . } . None 596 ( 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() { 186,199 ( 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,807 ( 0.00%) while let Some(x) = self.next_back() { 27,083 ( 0.00%) i -= 1; 20,047 ( 0.00%) 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` 26,762 ( 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 349 ---------------------------------------- . fn next_back(&mut self) -> Option<$elem> { . // could be implemented with slices, but this avoids bounds checks . . // SAFETY: `assume` calls are safe since a slice's start pointer must be non-null, . // and slices over non-ZSTs must also have a non-null end pointer. . // The call to `next_back_unchecked!` is safe since we check if the iterator is . // empty first. . unsafe { 1 ( 0.00%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 26 ( 0.00%) assume(!self.end.is_null()); . } 822,249 ( 0.03%) if is_empty!(self) { . None . } else { . Some(next_back_unchecked!(self)) . } . } . } . . #[inline] -- line 369 ---------------------------------------- 9,344,307 ( 0.37%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs -------------------------------------------------------------------------------- Ir -- line 18 ---------------------------------------- . }; . use crate::ty; . . /// This type represents an Allocation in the Miri/CTFE core engine. . /// . /// Its public API is rather low-level, working directly with allocation offsets and a custom error . /// type to account for the lack of an AllocId on this level. The Miri/CTFE core engine `memory` . /// module provides higher-level access. 3,256 ( 0.00%) #[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub struct Allocation { . /// The actual bytes of the allocation. . /// Note that the bytes of a pointer represent the offset of the pointer. 331 ( 0.00%) bytes: Box<[u8]>, . /// Maps from byte addresses to extra data for each pointer. . /// Only the first byte of a pointer is inserted into the map; i.e., . /// every entry in this map applies to `pointer_size` consecutive bytes starting . /// at the given offset. 2 ( 0.00%) relocations: Relocations, . /// Denotes which part of this allocation is initialized. . init_mask: InitMask, . /// The alignment of the allocation to detect unaligned reads. . /// (`Align` guarantees that this is a power of two.) 8 ( 0.00%) pub align: Align, . /// `true` if the allocation is mutable. . /// Also used by codegen to determine if a static should be put into mutable memory, . /// which happens for `static mut` and `static` with interior mutability. 4 ( 0.00%) pub mutability: Mutability, . /// Extra state for the machine. . pub extra: Extra, . } . . /// We have our own error type that does not know about the `AllocId`; that information . /// is added when converting to `InterpError`. . #[derive(Debug)] . pub enum AllocError { -- line 53 ---------------------------------------- -- line 91 ---------------------------------------- . impl AllocRange { . #[inline(always)] . pub fn end(self) -> Size { . self.start + self.size // This does overflow checking. . } . . /// Returns the `subrange` within this range; panics if it is not a subrange. . #[inline] 119,631 ( 0.00%) pub fn subrange(self, subrange: AllocRange) -> AllocRange { . let sub_start = self.start + subrange.start; . let range = alloc_range(sub_start, subrange.size); 119,631 ( 0.00%) assert!(range.end() <= self.end(), "access outside the bounds for given AllocRange"); . range 358,893 ( 0.01%) } . } . . // The constructors are all without extra; the extra gets added by a machine hook later. . impl Allocation { . /// Creates an allocation initialized by the given bytes . pub fn from_bytes<'a>( . slice: impl Into>, . align: Align, . mutability: Mutability, . ) -> Self { . let bytes = Box::<[u8]>::from(slice.into()); . let size = Size::from_bytes(bytes.len()); 256 ( 0.00%) Self { . bytes, . relocations: Relocations::new(), 96 ( 0.00%) init_mask: InitMask::new(size, true), . align, . mutability, . extra: (), . } . } . . pub fn from_bytes_byte_aligned_immutable<'a>(slice: impl Into>) -> Self { . Allocation::from_bytes(slice, Align::ONE, Mutability::Not) . } . . /// Try to create an Allocation of `size` bytes, failing if there is not enough memory . /// available to the compiler to do so. 173,558 ( 0.01%) pub fn uninit(size: Size, align: Align, panic_on_fail: bool) -> InterpResult<'static, Self> { . let bytes = Box::<[u8]>::try_new_zeroed_slice(size.bytes_usize()).map_err(|_| { . // This results in an error that can happen non-deterministically, since the memory . // available to the compiler can change between runs. Normally queries are always . // deterministic. However, we can be non-determinstic here because all uses of const . // evaluation (including ConstProp!) will make compilation fail (via hard error . // or ICE) upon encountering a `MemoryExhausted` error. . if panic_on_fail { . panic!("Allocation::uninit called with panic_on_fail had allocation failure") -- line 141 ---------------------------------------- -- line 142 ---------------------------------------- . } . ty::tls::with(|tcx| { . tcx.sess.delay_span_bug(DUMMY_SP, "exhausted memory during interpreation") . }); . InterpError::ResourceExhaustion(ResourceExhaustionInfo::MemoryExhausted) . })?; . // SAFETY: the box was zero-allocated, which is a valid initial value for Box<[u8]> . let bytes = unsafe { bytes.assume_init() }; 220,892 ( 0.01%) Ok(Allocation { . bytes, . relocations: Relocations::new(), 47,334 ( 0.00%) init_mask: InitMask::new(size, false), . align, . mutability: Mutability::Mut, . extra: (), . }) 142,002 ( 0.01%) } . } . . impl Allocation { . /// Convert Tag and add Extra fields . pub fn convert_tag_add_extra( . self, . cx: &impl HasDataLayout, . extra: Extra, -- line 166 ---------------------------------------- -- line 194 ---------------------------------------- . . /// Raw accessors. Provide access to otherwise private bytes. . impl Allocation { . pub fn len(&self) -> usize { . self.bytes.len() . } . . pub fn size(&self) -> Size { 157,503 ( 0.01%) Size::from_bytes(self.len()) . } . . /// Looks at a slice which may describe uninitialized bytes or describe a relocation. This differs . /// from `get_bytes_with_uninit_and_ptr` in that it does no relocation checks (even on the . /// edges) at all. . /// This must not be used for reads affecting the interpreter execution. . pub fn inspect_with_uninit_and_ptr_outside_interpreter(&self, range: Range) -> &[u8] { . &self.bytes[range] -- line 210 ---------------------------------------- -- line 227 ---------------------------------------- . /// or pointer bytes. You should never call this, call `get_bytes` or . /// `get_bytes_with_uninit_and_ptr` instead, . /// . /// This function also guarantees that the resulting pointer will remain stable . /// even when new allocations are pushed to the `HashMap`. `copy_repeatedly` relies . /// on that. . /// . /// It is the caller's responsibility to check bounds and alignment beforehand. 1,205,160 ( 0.05%) fn get_bytes_internal( . &self, . cx: &impl HasDataLayout, . range: AllocRange, . check_init_and_ptr: bool, . ) -> AllocResult<&[u8]> { 200,860 ( 0.01%) if check_init_and_ptr { 8 ( 0.00%) self.check_init(range)?; . self.check_relocations(cx, range)?; . } else { . // We still don't want relocations on the *edges*. . self.check_relocation_edges(cx, range)?; . } . 401,720 ( 0.02%) Ok(&self.bytes[range.start.bytes_usize()..range.end().bytes_usize()]) 903,870 ( 0.04%) } . . /// Checks that these bytes are initialized and not pointer bytes, and then return them . /// as a slice. . /// . /// It is the caller's responsibility to check bounds and alignment beforehand. . /// Most likely, you want to use the `PlaceTy` and `OperandTy`-based methods . /// on `InterpCx` instead. . #[inline] . pub fn get_bytes(&self, cx: &impl HasDataLayout, range: AllocRange) -> AllocResult<&[u8]> { 4 ( 0.00%) self.get_bytes_internal(cx, range, true) . } . . /// It is the caller's responsibility to handle uninitialized and pointer bytes. . /// However, this still checks that there are no relocations on the *edges*. . /// . /// It is the caller's responsibility to check bounds and alignment beforehand. . #[inline] . pub fn get_bytes_with_uninit_and_ptr( . &self, . cx: &impl HasDataLayout, . range: AllocRange, . ) -> AllocResult<&[u8]> { 270,251 ( 0.01%) self.get_bytes_internal(cx, range, false) . } . . /// Just calling this already marks everything as defined and removes relocations, . /// so be sure to actually put data there! . /// . /// It is the caller's responsibility to check bounds and alignment beforehand. . /// Most likely, you want to use the `PlaceTy` and `OperandTy`-based methods . /// on `InterpCx` instead. 363,902 ( 0.01%) pub fn get_bytes_mut( . &mut self, . cx: &impl HasDataLayout, . range: AllocRange, . ) -> AllocResult<&mut [u8]> { . self.mark_init(range, true); 165,410 ( 0.01%) self.clear_relocations(cx, range)?; . 132,328 ( 0.01%) Ok(&mut self.bytes[range.start.bytes_usize()..range.end().bytes_usize()]) 264,656 ( 0.01%) } . . /// A raw pointer variant of `get_bytes_mut` that avoids invalidating existing aliases into this memory. 152,669 ( 0.01%) pub fn get_bytes_mut_ptr( . &mut self, . cx: &impl HasDataLayout, . range: AllocRange, . ) -> AllocResult<*mut [u8]> { . self.mark_init(range, true); 69,395 ( 0.00%) self.clear_relocations(cx, range)?; . 27,758 ( 0.00%) assert!(range.end().bytes_usize() <= self.bytes.len()); // need to do our own bounds-check . let begin_ptr = self.bytes.as_mut_ptr().wrapping_add(range.start.bytes_usize()); 27,758 ( 0.00%) let len = range.end().bytes_usize() - range.start.bytes_usize(); 55,516 ( 0.00%) Ok(ptr::slice_from_raw_parts_mut(begin_ptr, len)) 111,032 ( 0.00%) } . } . . /// Reading and writing. . impl Allocation { . /// Validates that `ptr.offset` and `ptr.offset + size` do not point to the middle of a . /// relocation. If `allow_uninit_and_ptr` is `false`, also enforces that the memory in the . /// given range contains neither relocations nor uninitialized bytes. . pub fn check_bytes( -- line 314 ---------------------------------------- -- line 329 ---------------------------------------- . . /// Reads a *non-ZST* scalar. . /// . /// ZSTs can't be read because in order to obtain a `Pointer`, we need to check . /// for ZSTness anyway due to integer pointers being valid for ZSTs. . /// . /// It is the caller's responsibility to check bounds and alignment beforehand. . /// Most likely, you want to call `InterpCx::read_scalar` instead of this method. 1,125,137 ( 0.04%) pub fn read_scalar( . &self, . cx: &impl HasDataLayout, . range: AllocRange, . ) -> AllocResult> { . // `get_bytes_with_uninit_and_ptr` tests relocation edges. . // We deliberately error when loading data that partially has provenance, or partially . // initialized data (that's the check below), into a scalar. The LLVM semantics of this are . // unclear so we are conservative. See for -- line 345 ---------------------------------------- -- line 348 ---------------------------------------- . // Uninit check happens *after* we established that the alignment is correct. . // We must not return `Ok()` for unaligned pointers! . if self.is_init(range).is_err() { . // This inflates uninitialized bytes to the entire scalar, even if only a few . // bytes are uninitialized. . return Ok(ScalarMaybeUninit::Uninit); . } . // Now we do the actual reading. 86,549 ( 0.00%) let bits = read_target_uint(cx.data_layout().endian, bytes).unwrap(); . // See if we got a pointer. 86,549 ( 0.00%) if range.size != cx.data_layout().pointer_size { . // Not a pointer. . // *Now*, we better make sure that the inside is free of relocations too. . self.check_relocations(cx, range)?; . } else { . // Maybe a pointer. . if let Some(&prov) = self.relocations.get(&range.start) { . let ptr = Pointer::new(prov, Size::from_bytes(bits)); 75 ( 0.00%) return Ok(ScalarMaybeUninit::from_pointer(ptr, cx)); . } . } . // We don't. Just return the bits. 519,204 ( 0.02%) Ok(ScalarMaybeUninit::Scalar(Scalar::from_uint(bits, range.size))) 778,941 ( 0.03%) } . . /// Writes a *non-ZST* scalar. . /// . /// ZSTs can't be read because in order to obtain a `Pointer`, we need to check . /// for ZSTness anyway due to integer pointers being valid for ZSTs. . /// . /// It is the caller's responsibility to check bounds and alignment beforehand. . /// Most likely, you want to call `InterpCx::write_scalar` instead of this method. 231,574 ( 0.01%) pub fn write_scalar( . &mut self, . cx: &impl HasDataLayout, . range: AllocRange, . val: ScalarMaybeUninit, . ) -> AllocResult { 33,082 ( 0.00%) assert!(self.mutability == Mutability::Mut); . 99,246 ( 0.00%) let val = match val { . ScalarMaybeUninit::Scalar(scalar) => scalar, . ScalarMaybeUninit::Uninit => { . self.mark_init(range, false); . return Ok(()); . } . }; . . // `to_bits_or_ptr_internal` is the right method because we just want to store this data . // as-is into memory. 132,328 ( 0.01%) let (bytes, provenance) = match val.to_bits_or_ptr_internal(range.size) { . Err(val) => { . let (provenance, offset) = val.into_parts(); . (u128::from(offset.bytes()), Some(provenance)) . } . Ok(data) => (data, None), . }; . 99,246 ( 0.00%) let endian = cx.data_layout().endian; 99,246 ( 0.00%) let dst = self.get_bytes_mut(cx, range)?; . write_target_uint(endian, dst, bytes).unwrap(); . . // See if we have to also write a relocation. 99,240 ( 0.00%) if let Some(provenance) = provenance { 24 ( 0.00%) self.relocations.0.insert(range.start, provenance); . } . . Ok(()) 297,738 ( 0.01%) } . } . . /// Relocations. . impl Allocation { . /// Returns all relocations overlapping with the given pointer-offset pair. 1,003,032 ( 0.04%) pub fn get_relocations(&self, cx: &impl HasDataLayout, range: AllocRange) -> &[(Size, Tag)] { . // We have to go back `pointer_size - 1` bytes, as that one would still overlap with . // the beginning of this range. 1,044,669 ( 0.04%) let start = range.start.bytes().saturating_sub(cx.data_layout().pointer_size.bytes() - 1); . self.relocations.range(Size::from_bytes(start)..range.end()) 1,337,376 ( 0.05%) } . . /// Checks that there are no relocations overlapping with the given range. . #[inline(always)] . fn check_relocations(&self, cx: &impl HasDataLayout, range: AllocRange) -> AllocResult { 1,724,298 ( 0.07%) if self.get_relocations(cx, range).is_empty() { . Ok(()) . } else { . Err(AllocError::ReadPointerAsBytes) . } . } . . /// Removes all relocations inside the given range. . /// If there are relocations overlapping with the edges, they . /// are removed as well *and* the bytes they cover are marked as . /// uninitialized. This is a somewhat odd "spooky action at a distance", . /// but it allows strictly more code to run than if we would just error . /// immediately in that case. 516,571 ( 0.02%) fn clear_relocations(&mut self, cx: &impl HasDataLayout, range: AllocRange) -> AllocResult . where . Tag: Provenance, . { . // Find the start and end of the given range and its outermost relocations. . let (first, last) = { . // Find all relocations overlapping the given range. 234,805 ( 0.01%) let relocations = self.get_relocations(cx, range); 46,961 ( 0.00%) if relocations.is_empty() { . return Ok(()); . } . . ( . relocations.first().unwrap().0, . relocations.last().unwrap().0 + cx.data_layout().pointer_size, . ) . }; -- line 461 ---------------------------------------- -- line 478 ---------------------------------------- . } . self.init_mask.set_range(end, last, false); . } . . // Forget all the relocations. . self.relocations.0.remove_range(first..last); . . Ok(()) 328,727 ( 0.01%) } . . /// Errors if there are relocations overlapping with the edges of the . /// given memory range. . #[inline] . fn check_relocation_edges(&self, cx: &impl HasDataLayout, range: AllocRange) -> AllocResult { . self.check_relocations(cx, alloc_range(range.start, Size::ZERO))?; . self.check_relocations(cx, alloc_range(range.end(), Size::ZERO))?; . Ok(()) -- line 494 ---------------------------------------- -- line 496 ---------------------------------------- . } . . /// "Relocations" stores the provenance information of pointers stored in memory. . #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] . pub struct Relocations(SortedMap); . . impl Relocations { . pub fn new() -> Self { 31,620 ( 0.00%) Relocations(SortedMap::new()) . } . . // The caller must guarantee that the given relocations are already sorted . // by address and contain no duplicates. . pub fn from_presorted(r: Vec<(Size, Tag)>) -> Self { . Relocations(SortedMap::from_presorted_elements(r)) . } . } -- line 512 ---------------------------------------- -- line 520 ---------------------------------------- . } . . /// A partial, owned list of relocations to transfer into another allocation. . pub struct AllocationRelocations { . relative_relocations: Vec<(Size, Tag)>, . } . . impl Allocation { 138,790 ( 0.01%) pub fn prepare_relocation_copy( . &self, . cx: &impl HasDataLayout, . src: AllocRange, . dest: Size, . count: u64, . ) -> AllocationRelocations { . let relocations = self.get_relocations(cx, src); 13,879 ( 0.00%) if relocations.is_empty() { 27,758 ( 0.00%) return AllocationRelocations { relative_relocations: Vec::new() }; . } . . let size = src.size; . let mut new_relocations = Vec::with_capacity(relocations.len() * (count as usize)); . . for i in 0..count { . new_relocations.extend(relocations.iter().map(|&(offset, reloc)| { . // compute offset for current repetition -- line 545 ---------------------------------------- -- line 548 ---------------------------------------- . // shift offsets from source allocation to destination allocation . (offset + dest_offset) - src.start, // `Size` operations . reloc, . ) . })); . } . . AllocationRelocations { relative_relocations: new_relocations } 124,911 ( 0.00%) } . . /// Applies a relocation copy. . /// The affected range, as defined in the parameters to `prepare_relocation_copy` is expected . /// to be clear of relocations. 97,153 ( 0.00%) pub fn mark_relocation_range(&mut self, relocations: AllocationRelocations) { 55,516 ( 0.00%) self.relocations.0.insert_presorted(relocations.relative_relocations); 111,032 ( 0.00%) } . } . . //////////////////////////////////////////////////////////////////////////////// . // Uninitialized byte tracking . //////////////////////////////////////////////////////////////////////////////// . . type Block = u64; . -- line 571 ---------------------------------------- -- line 582 ---------------------------------------- . pub const BLOCK_SIZE: u64 = 64; . . #[inline] . fn bit_index(bits: Size) -> (usize, usize) { . // BLOCK_SIZE is the number of bits that can fit in a `Block`. . // Each bit in a `Block` represents the initialization state of one byte of an allocation, . // so we use `.bytes()` here. . let bits = bits.bytes(); 548,552 ( 0.02%) let a = bits / InitMask::BLOCK_SIZE; 157,744 ( 0.01%) let b = bits % InitMask::BLOCK_SIZE; . (usize::try_from(a).unwrap(), usize::try_from(b).unwrap()) . } . . #[inline] . fn size_from_bit_index(block: impl TryInto, bit: impl TryInto) -> Size { . let block = block.try_into().ok().unwrap(); . let bit = bit.try_into().ok().unwrap(); 53,395 ( 0.00%) Size::from_bytes(block * InitMask::BLOCK_SIZE + bit) . } . 63,240 ( 0.00%) pub fn new(size: Size, state: bool) -> Self { 31,620 ( 0.00%) let mut m = InitMask { blocks: vec![], len: Size::ZERO }; 15,810 ( 0.00%) m.grow(size, state); . m 79,050 ( 0.00%) } . 375,688 ( 0.01%) pub fn set_range(&mut self, start: Size, end: Size, new_state: bool) { 93,922 ( 0.00%) let len = self.len; 46,961 ( 0.00%) if end > len { . self.grow(end - len, new_state); . } 469,610 ( 0.02%) self.set_range_inbounds(start, end, new_state); . } . 315,488 ( 0.01%) pub fn set_range_inbounds(&mut self, start: Size, end: Size, new_state: bool) { . let (blocka, bita) = Self::bit_index(start); . let (blockb, bitb) = Self::bit_index(end); 157,744 ( 0.01%) if blocka == blockb { . // First set all bits except the first `bita`, . // then unset the last `64 - bitb` bits. 155,726 ( 0.01%) let range = if bitb == 0 { . u64::MAX << bita . } else { 545,041 ( 0.02%) (u64::MAX << bita) & (u64::MAX >> (64 - bitb)) . }; 155,726 ( 0.01%) if new_state { 59,995 ( 0.00%) self.blocks[blocka] |= range; . } else { 35,736 ( 0.00%) self.blocks[blocka] &= !range; . } . return; . } . // across block boundaries 2,018 ( 0.00%) if new_state { . // Set `bita..64` to `1`. 2,628 ( 0.00%) self.blocks[blocka] |= u64::MAX << bita; . // Set `0..bitb` to `1`. 1,752 ( 0.00%) if bitb != 0 { 5 ( 0.00%) self.blocks[blockb] |= u64::MAX >> (64 - bitb); . } . // Fill in all the other blocks (much faster than one bit at a time). . for block in (blocka + 1)..blockb { 199 ( 0.00%) self.blocks[block] = u64::MAX; . } . } else { . // Set `bita..64` to `0`. 532 ( 0.00%) self.blocks[blocka] &= !(u64::MAX << bita); . // Set `0..bitb` to `0`. 266 ( 0.00%) if bitb != 0 { 12 ( 0.00%) self.blocks[blockb] &= !(u64::MAX >> (64 - bitb)); . } . // Fill in all the other blocks (much faster than one bit at a time). . for block in (blocka + 1)..blockb { 736 ( 0.00%) self.blocks[block] = 0; . } . } 157,744 ( 0.01%) } . . #[inline] . pub fn get(&self, i: Size) -> bool { . let (block, bit) = Self::bit_index(i); 97,153 ( 0.00%) (self.blocks[block] & (1 << bit)) != 0 . } . . #[inline] . pub fn set(&mut self, i: Size, new_state: bool) { . let (block, bit) = Self::bit_index(i); . self.set_bit(block, bit, new_state); . } . -- line 671 ---------------------------------------- -- line 673 ---------------------------------------- . fn set_bit(&mut self, block: usize, bit: usize, new_state: bool) { . if new_state { . self.blocks[block] |= 1 << bit; . } else { . self.blocks[block] &= !(1 << bit); . } . } . 94,860 ( 0.00%) pub fn grow(&mut self, amount: Size, new_state: bool) { 31,620 ( 0.00%) if amount.bytes() == 0 { . return; . } . let unused_trailing_bits = 126,472 ( 0.01%) u64::try_from(self.blocks.len()).unwrap() * Self::BLOCK_SIZE - self.len.bytes(); 31,618 ( 0.00%) if amount.bytes() > unused_trailing_bits { 47,427 ( 0.00%) let additional_blocks = amount.bytes() / Self::BLOCK_SIZE + 1; . self.blocks.extend( . // FIXME(oli-obk): optimize this by repeating `new_state as Block`. . iter::repeat(0).take(usize::try_from(additional_blocks).unwrap()), . ); . } 15,809 ( 0.00%) let start = self.len; . self.len += amount; 142,281 ( 0.01%) self.set_range_inbounds(start, start + amount, new_state); // `Size` operation 7 ( 0.00%) } . . /// Returns the index of the first bit in `start..end` (end-exclusive) that is equal to is_init. 205,306 ( 0.01%) fn find_bit(&self, start: Size, end: Size, is_init: bool) -> Option { . /// A fast implementation of `find_bit`, . /// which skips over an entire block at a time if it's all 0s (resp. 1s), . /// and finds the first 1 (resp. 0) bit inside a block using `trailing_zeros` instead of a loop. . /// . /// Note that all examples below are written with 8 (instead of 64) bit blocks for simplicity, . /// and with the least significant bit (and lowest block) first: . /// . /// 00000000|00000000 -- line 708 ---------------------------------------- -- line 728 ---------------------------------------- . // start_bit = 3 . // is_init = false . // Note that, for the examples in this function, the most significant bit is written first, . // which is backwards compared to the comments in `find_bit`/`find_bit_fast`. . . // Invert bits so we're always looking for the first set bit. . // ! 0b00111011 . // bits = 0b11000100 410,612 ( 0.02%) let bits = if is_init { bits } else { !bits }; . // Mask off unused start bits. . // 0b11000100 . // & 0b11111000 . // bits = 0b11000000 307,959 ( 0.01%) let bits = bits & (!0 << start_bit); . // Find set bit, if any. . // bit = trailing_zeros(0b11000000) . // bit = 6 205,711 ( 0.01%) if bits == 0 { . None . } else { . let bit = bits.trailing_zeros(); . Some(InitMask::size_from_bit_index(block, bit)) . } . } . 102,653 ( 0.00%) if start >= end { . return None; . } . . // Convert `start` and `end` to block indexes and bit indexes within each block. . // We must convert `end` to an inclusive bound to handle block boundaries correctly. . // . // For example: . // -- line 761 ---------------------------------------- -- line 819 ---------------------------------------- . // The block marked (3) in this example is the first block that will be handled by this loop, . // and it will be skipped for that reason: . // . // (3) . // -------- . // (e) 01000000|00000000|00000001 . // ^~~~~~~~~~~~~~~~~~^ . // start end 98,520 ( 0.00%) if start_block < end_block_inclusive { . // This loop is written in a specific way for performance. . // Notably: `..end_block_inclusive + 1` is used for an inclusive range instead of `..=end_block_inclusive`, . // and `.zip(start_block + 1..)` is used to track the index instead of `.enumerate().skip().take()`, . // because both alternatives result in significantly worse codegen. . // `end_block_inclusive + 1` is guaranteed not to wrap, because `end_block_inclusive <= end / BLOCK_SIZE`, . // and `BLOCK_SIZE` (the number of bits per block) will always be at least 8 (1 byte). 1 ( 0.00%) for (&bits, block) in init_mask.blocks[start_block + 1..end_block_inclusive + 1] . .iter() . .zip(start_block + 1..) . { . if let Some(i) = search_block(bits, block, 0, is_init) { . // If this is the last block, we may find a matching bit after `end`. . // . // For example, we shouldn't successfully find bit (4), because it's after `end`: . // -- line 842 ---------------------------------------- -- line 879 ---------------------------------------- . "optimized implementation of find_bit is wrong for start={:?} end={:?} is_init={} init_mask={:#?}", . start, . end, . is_init, . self . ); . . result 205,306 ( 0.01%) } . } . . /// A contiguous chunk of initialized or uninitialized memory. . pub enum InitChunk { . Init(Range), . Uninit(Range), . } . -- line 895 ---------------------------------------- -- line 913 ---------------------------------------- . . impl InitMask { . /// Checks whether the range `start..end` (end-exclusive) is entirely initialized. . /// . /// Returns `Ok(())` if it's initialized. Otherwise returns a range of byte . /// indexes for the first contiguous span of the uninitialized access. . #[inline] . pub fn is_range_initialized(&self, start: Size, end: Size) -> Result<(), Range> { 86,553 ( 0.00%) if end > self.len { . return Err(self.len..end); . } . 432,755 ( 0.02%) let uninit_start = self.find_bit(start, end, false); . 173,102 ( 0.01%) match uninit_start { . Some(uninit_start) => { . let uninit_end = self.find_bit(uninit_start, end, true).unwrap_or(end); . Err(uninit_start..uninit_end) . } . None => Ok(()), . } . } . -- line 935 ---------------------------------------- -- line 938 ---------------------------------------- . /// . /// The iterator guarantees the following: . /// - Chunks are nonempty. . /// - Chunks are adjacent (each range's start is equal to the previous range's end). . /// - Chunks span exactly `start..end` (the first starts at `start`, the last ends at `end`). . /// - Chunks alternate between [`InitChunk::Init`] and [`InitChunk::Uninit`]. . #[inline] . pub fn range_as_init_chunks(&self, start: Size, end: Size) -> InitChunkIter<'_> { 13,879 ( 0.00%) assert!(end <= self.len); . 13,879 ( 0.00%) let is_init = if start < end { . self.get(start) . } else { . // `start..end` is empty: there are no chunks, so use some arbitrary value . false . }; . . InitChunkIter { init_mask: self, is_init, start, end } . } -- line 956 ---------------------------------------- -- line 968 ---------------------------------------- . end: Size, . } . . impl<'a> Iterator for InitChunkIter<'a> { . type Item = InitChunk; . . #[inline] . fn next(&mut self) -> Option { 16,102 ( 0.00%) if self.start >= self.end { . return None; . } . . let end_of_chunk = 84,956 ( 0.00%) self.init_mask.find_bit(self.start, self.end, !self.is_init).unwrap_or(self.end); . let range = self.start..end_of_chunk; . . let ret = 62,185 ( 0.00%) Some(if self.is_init { InitChunk::Init(range) } else { InitChunk::Uninit(range) }); . . self.is_init = !self.is_init; . self.start = end_of_chunk; . . ret . } . } . -- line 993 ---------------------------------------- -- line 998 ---------------------------------------- . /// Returns `Ok(())` if it's initialized. Otherwise returns the range of byte . /// indexes of the first contiguous uninitialized access. . fn is_init(&self, range: AllocRange) -> Result<(), Range> { . self.init_mask.is_range_initialized(range.start, range.end()) // `Size` addition . } . . /// Checks that a range of bytes is initialized. If not, returns the `InvalidUninitBytes` . /// error which will report the first range of bytes which is uninitialized. 18 ( 0.00%) fn check_init(&self, range: AllocRange) -> AllocResult { . self.is_init(range).map_err(|idx_range| { . AllocError::InvalidUninitBytes(Some(UninitBytesAccess { . access_offset: range.start, . access_size: range.size, . uninit_offset: idx_range.start, . uninit_size: idx_range.end - idx_range.start, // `Size` subtraction . })) . }) 16 ( 0.00%) } . . pub fn mark_init(&mut self, range: AllocRange, is_init: bool) { 93,922 ( 0.00%) if range.size.bytes() == 0 { . return; . } 46,961 ( 0.00%) assert!(self.mutability == Mutability::Mut); 187,844 ( 0.01%) self.init_mask.set_range(range.start, range.end(), is_init); . } . } . . /// Run-length encoding of the uninit mask. . /// Used to copy parts of a mask multiple times to another allocation. . pub struct InitMaskCompressed { . /// Whether the first range is initialized. . initial: bool, -- line 1030 ---------------------------------------- -- line 1032 ---------------------------------------- . /// The initialization state of the ranges alternate starting with `initial`. . ranges: smallvec::SmallVec<[u64; 1]>, . } . . impl InitMaskCompressed { . pub fn no_bytes_init(&self) -> bool { . // The `ranges` are run-length encoded and of alternating initialization state. . // So if `ranges.len() > 1` then the second block is an initialized range. 27,758 ( 0.00%) !self.initial && self.ranges.len() == 1 13,879 ( 0.00%) } . } . . /// Transferring the initialization mask to other allocations. . impl Allocation { . /// Creates a run-length encoding of the initialization mask; panics if range is empty. . /// . /// This is essentially a more space-efficient version of . /// `InitMask::range_as_init_chunks(...).collect::>()`. 97,153 ( 0.00%) pub fn compress_uninit_range(&self, range: AllocRange) -> InitMaskCompressed { . // Since we are copying `size` bytes from `src` to `dest + i * size` (`for i in 0..repeat`), . // a naive initialization mask copying algorithm would repeatedly have to read the initialization mask from . // the source and write it to the destination. Even if we optimized the memory accesses, . // we'd be doing all of this `repeat` times. . // Therefore we precompute a compressed version of the initialization mask of the source value and . // then write it back `repeat` times without computing any more information from the source. . . // A precomputed cache for ranges of initialized / uninitialized bits -- line 1058 ---------------------------------------- -- line 1062 ---------------------------------------- . . let mut ranges = smallvec::SmallVec::<[u64; 1]>::new(); . . let mut chunks = self.init_mask.range_as_init_chunks(range.start, range.end()).peekable(); . . let initial = chunks.peek().expect("range should be nonempty").is_init(); . . // Here we rely on `range_as_init_chunks` to yield alternating init/uninit chunks. 4,446 ( 0.00%) for chunk in chunks { 32,204 ( 0.00%) let len = chunk.range().end.bytes() - chunk.range().start.bytes(); . ranges.push(len); . } . 97,153 ( 0.00%) InitMaskCompressed { ranges, initial } 111,032 ( 0.00%) } . . /// Applies multiple instances of the run-length encoding to the initialization mask. 152,669 ( 0.01%) pub fn mark_compressed_init_range( . &mut self, . defined: &InitMaskCompressed, . range: AllocRange, . repeat: u64, . ) { . // An optimization where we can just overwrite an entire range of initialization . // bits if they are going to be uniformly `1` or `0`. 27,758 ( 0.00%) if defined.ranges.len() <= 1 { 116,560 ( 0.00%) self.init_mask.set_range_inbounds( . range.start, . range.start + range.size * repeat, // `Size` operations 11,656 ( 0.00%) defined.initial, . ); . return; . } . . for mut j in 0..repeat { 6,669 ( 0.00%) j *= range.size.bytes(); 4,446 ( 0.00%) j += range.start.bytes(); . let mut cur = defined.initial; . for range in &defined.ranges { . let old_j = j; . j += range; 13,338 ( 0.00%) self.init_mask.set_range_inbounds( . Size::from_bytes(old_j), . Size::from_bytes(j), 17,784 ( 0.00%) cur, . ); . cur = !cur; . } . } 17,784 ( 0.00%) } . } 1,860,008 ( 0.07%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/hygiene.rs -------------------------------------------------------------------------------- Ir -- line 40 ---------------------------------------- . use rustc_macros::HashStable_Generic; . use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; . use std::fmt; . use std::hash::Hash; . use tracing::*; . . /// A `SyntaxContext` represents a chain of pairs `(ExpnId, Transparency)` named "marks". . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] 579,679 ( 0.02%) pub struct SyntaxContext(u32); . 14,805 ( 0.00%) #[derive(Debug, Encodable, Decodable, Clone)] . pub struct SyntaxContextData { 9 ( 0.00%) outer_expn: ExpnId, 27 ( 0.00%) outer_transparency: Transparency, . parent: SyntaxContext, . /// This context, but with all transparent and semi-transparent expansions filtered away. . opaque: SyntaxContext, . /// This context, but with all transparent expansions filtered away. . opaque_and_semitransparent: SyntaxContext, . /// Name of the crate to which `$crate` with this context would resolve. . dollar_crate_name: Symbol, . } -- line 61 ---------------------------------------- -- line 65 ---------------------------------------- . pub struct ExpnIndex { . ENCODABLE = custom . } . } . . /// A unique ID associated with a macro invocation and expansion. . #[derive(Clone, Copy, PartialEq, Eq, Hash)] . pub struct ExpnId { 2,848 ( 0.00%) pub krate: CrateNum, 80,900 ( 0.00%) pub local_id: ExpnIndex, . } . . impl fmt::Debug for ExpnId { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . // Generate crate_::{{expn_}}. . write!(f, "{:?}::{{{{expn{}}}}}", self.krate, self.local_id.private) . } . } -- line 82 ---------------------------------------- -- line 106 ---------------------------------------- . // or ensure that this method is always invoked with the same . // `NodeIdHashingMode` . // . // Note that we require that `hash_spans` be set according to the global . // `-Z incremental-ignore-spans` option. Normally, this option is disabled, . // which will cause us to require that this method always be called with `Span` hashing . // enabled. . HashingControls { hash_spans, node_id_hashing_mode: _ } 3,192 ( 0.00%) if hash_spans == !ctx.debug_opts_incremental_ignore_spans() => {} . other => panic!("Attempted hashing of {msg} with non-default HashingControls: {:?}", other), . } . } . . /// A unique hash value associated to an expansion. . #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)] 892 ( 0.00%) pub struct ExpnHash(Fingerprint); . . impl ExpnHash { . /// Returns the [StableCrateId] identifying the crate this [ExpnHash] . /// originates from. . #[inline] . pub fn stable_crate_id(self) -> StableCrateId { . StableCrateId(self.0.as_value().0) . } -- line 129 ---------------------------------------- -- line 138 ---------------------------------------- . . #[inline] . pub fn is_root(self) -> bool { . self.0 == Fingerprint::ZERO . } . . /// Builds a new [ExpnHash] with the given [StableCrateId] and . /// `local_hash`, where `local_hash` must be unique within its crate. 252 ( 0.00%) fn new(stable_crate_id: StableCrateId, local_hash: u64) -> ExpnHash { . ExpnHash(Fingerprint::new(stable_crate_id.0, local_hash)) 126 ( 0.00%) } . } . . /// A property of a macro expansion that determines how identifiers . /// produced by that expansion are resolved. 4,142 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Hash, Debug, Encodable, Decodable)] . #[derive(HashStable_Generic)] . pub enum Transparency { . /// Identifier produced by a transparent expansion is always resolved at call-site. . /// Call-site spans in procedural macros, hygiene opt-out in `macro` should use this. . Transparent, . /// Identifier produced by a semi-transparent expansion may be resolved . /// either at call-site or at definition-site. . /// If it's a local variable, label or `$crate` then it's resolved at def-site. -- line 161 ---------------------------------------- -- line 169 ---------------------------------------- . } . . impl LocalExpnId { . /// The ID of the theoretical expansion that generates freshly parsed, unexpanded AST. . pub const ROOT: LocalExpnId = LocalExpnId::from_u32(0); . . pub fn from_raw(idx: ExpnIndex) -> LocalExpnId { . LocalExpnId::from_u32(idx.as_u32()) 2,838 ( 0.00%) } . . pub fn as_raw(self) -> ExpnIndex { . ExpnIndex::from_u32(self.as_u32()) 1,192 ( 0.00%) } . . pub fn fresh_empty() -> LocalExpnId { . HygieneData::with(|data| { . let expn_id = data.local_expn_data.push(None); . let _eid = data.local_expn_hashes.push(ExpnHash(Fingerprint::ZERO)); . debug_assert_eq!(expn_id, _eid); . expn_id . }) . } . . pub fn fresh(mut expn_data: ExpnData, ctx: impl HashStableContext) -> LocalExpnId { . debug_assert_eq!(expn_data.parent.krate, LOCAL_CRATE); 757 ( 0.00%) let expn_hash = update_disambiguator(&mut expn_data, ctx); . HygieneData::with(|data| { 1,070 ( 0.00%) let expn_id = data.local_expn_data.push(Some(expn_data)); . let _eid = data.local_expn_hashes.push(expn_hash); . debug_assert_eq!(expn_id, _eid); 214 ( 0.00%) let _old_id = data.expn_hash_to_expn_id.insert(expn_hash, expn_id.to_expn_id()); . debug_assert!(_old_id.is_none()); . expn_id . }) . } . . #[inline] . pub fn expn_hash(self) -> ExpnHash { . HygieneData::with(|data| data.local_expn_hash(self)) . } . . #[inline] . pub fn expn_data(self) -> ExpnData { 41 ( 0.00%) HygieneData::with(|data| data.local_expn_data(self).clone()) . } . . #[inline] . pub fn to_expn_id(self) -> ExpnId { 1,461 ( 0.00%) ExpnId { krate: LOCAL_CRATE, local_id: self.as_raw() } . } . . #[inline] . pub fn set_expn_data(self, mut expn_data: ExpnData, ctx: impl HashStableContext) { . debug_assert_eq!(expn_data.parent.krate, LOCAL_CRATE); 304 ( 0.00%) let expn_hash = update_disambiguator(&mut expn_data, ctx); . HygieneData::with(|data| { 38 ( 0.00%) let old_expn_data = &mut data.local_expn_data[self]; 38 ( 0.00%) assert!(old_expn_data.is_none(), "expansion data is reset for an expansion ID"); 190 ( 0.00%) *old_expn_data = Some(expn_data); . debug_assert_eq!(data.local_expn_hashes[self].0, Fingerprint::ZERO); 76 ( 0.00%) data.local_expn_hashes[self] = expn_hash; 57 ( 0.00%) let _old_id = data.expn_hash_to_expn_id.insert(expn_hash, self.to_expn_id()); . debug_assert!(_old_id.is_none()); . }); . } . . #[inline] . pub fn is_descendant_of(self, ancestor: LocalExpnId) -> bool { . self.to_expn_id().is_descendant_of(ancestor.to_expn_id()) . } -- line 238 ---------------------------------------- -- line 259 ---------------------------------------- . } . } . . impl ExpnId { . /// The ID of the theoretical expansion that generates freshly parsed, unexpanded AST. . /// Invariant: we do not create any ExpnId with local_id == 0 and krate != 0. . pub const fn root() -> ExpnId { . ExpnId { krate: LOCAL_CRATE, local_id: ExpnIndex::from_u32(0) } 10,374 ( 0.00%) } . . #[inline] . pub fn expn_hash(self) -> ExpnHash { . HygieneData::with(|data| data.expn_hash(self)) . } . . #[inline] . pub fn from_hash(hash: ExpnHash) -> Option { . HygieneData::with(|data| data.expn_hash_to_expn_id.get(&hash).copied()) . } . . #[inline] . pub fn as_local(self) -> Option { 4,029 ( 0.00%) if self.krate == LOCAL_CRATE { Some(LocalExpnId::from_raw(self.local_id)) } else { None } . } . . #[inline] . #[track_caller] . pub fn expect_local(self) -> LocalExpnId { . self.as_local().unwrap() . } . . #[inline] . pub fn expn_data(self) -> ExpnData { 153 ( 0.00%) HygieneData::with(|data| data.expn_data(self).clone()) . } . . #[inline] . pub fn is_descendant_of(self, ancestor: ExpnId) -> bool { . // a few "fast path" cases to avoid locking HygieneData . if ancestor == ExpnId::root() || ancestor == self { . return true; . } -- line 300 ---------------------------------------- -- line 301 ---------------------------------------- . if ancestor.krate != self.krate { . return false; . } . HygieneData::with(|data| data.is_descendant_of(self, ancestor)) . } . . /// `expn_id.outer_expn_is_descendant_of(ctxt)` is equivalent to but faster than . /// `expn_id.is_descendant_of(ctxt.outer_expn())`. 3,320 ( 0.00%) pub fn outer_expn_is_descendant_of(self, ctxt: SyntaxContext) -> bool { . HygieneData::with(|data| data.is_descendant_of(self, data.outer_expn(ctxt))) 1,660 ( 0.00%) } . . /// Returns span for the macro which originally caused this expansion to happen. . /// . /// Stops backtracing at include! boundary. . pub fn expansion_cause(mut self) -> Option { . let mut last_macro = None; . loop { . let expn_data = self.expn_data(); -- line 319 ---------------------------------------- -- line 348 ---------------------------------------- . /// This is used by `update_disambiguator` to keep track of which `ExpnData`s . /// would have collisions without a disambiguator. . /// The keys of this map are always computed with `ExpnData.disambiguator` . /// set to 0. . expn_data_disambiguators: FxHashMap, . } . . impl HygieneData { 10 ( 0.00%) crate fn new(edition: Edition) -> Self { . let root_data = ExpnData::default( . ExpnKind::Root, . DUMMY_SP, . edition, . Some(CRATE_DEF_ID.to_def_id()), . None, . ); . 50 ( 0.00%) HygieneData { . local_expn_data: IndexVec::from_elem_n(Some(root_data), 1), . local_expn_hashes: IndexVec::from_elem_n(ExpnHash(Fingerprint::ZERO), 1), . foreign_expn_data: FxHashMap::default(), . foreign_expn_hashes: FxHashMap::default(), . expn_hash_to_expn_id: std::iter::once((ExpnHash(Fingerprint::ZERO), ExpnId::root())) . .collect(), 8 ( 0.00%) syntax_context_data: vec![SyntaxContextData { . outer_expn: ExpnId::root(), . outer_transparency: Transparency::Opaque, . parent: SyntaxContext(0), . opaque: SyntaxContext(0), . opaque_and_semitransparent: SyntaxContext(0), . dollar_crate_name: kw::DollarCrate, . }], . syntax_context_map: FxHashMap::default(), . expn_data_disambiguators: FxHashMap::default(), . } 10 ( 0.00%) } . 9 ( 0.00%) pub fn with T>(f: F) -> T { 11,460 ( 0.00%) with_session_globals(|session_globals| f(&mut *session_globals.hygiene_data.borrow_mut())) 9 ( 0.00%) } . . #[inline] . fn local_expn_hash(&self, expn_id: LocalExpnId) -> ExpnHash { . self.local_expn_hashes[expn_id] . } . . #[inline] . fn expn_hash(&self, expn_id: ExpnId) -> ExpnHash { . match expn_id.as_local() { . Some(expn_id) => self.local_expn_hashes[expn_id], . None => self.foreign_expn_hashes[&expn_id], . } . } . 82 ( 0.00%) fn local_expn_data(&self, expn_id: LocalExpnId) -> &ExpnData { . self.local_expn_data[expn_id].as_ref().expect("no expansion data for an expansion ID") 82 ( 0.00%) } . 54,631 ( 0.00%) fn expn_data(&self, expn_id: ExpnId) -> &ExpnData { 163,893 ( 0.01%) if let Some(expn_id) = expn_id.as_local() { . self.local_expn_data[expn_id].as_ref().expect("no expansion data for an expansion ID") . } else { . &self.foreign_expn_data[&expn_id] . } 109,262 ( 0.00%) } . . fn is_descendant_of(&self, mut expn_id: ExpnId, ancestor: ExpnId) -> bool { . // a couple "fast path" cases to avoid traversing parents in the loop below 37,812 ( 0.00%) if ancestor == ExpnId::root() { . return true; . } 80 ( 0.00%) if expn_id.krate != ancestor.krate { . return false; . } . loop { 80 ( 0.00%) if expn_id == ancestor { . return true; . } 80 ( 0.00%) if expn_id == ExpnId::root() { . return false; . } . expn_id = self.expn_data(expn_id).parent; . } 34 ( 0.00%) } . 60,144 ( 0.00%) fn normalize_to_macros_2_0(&self, ctxt: SyntaxContext) -> SyntaxContext { 434,796 ( 0.02%) self.syntax_context_data[ctxt.0 as usize].opaque 60,144 ( 0.00%) } . 18,046 ( 0.00%) fn normalize_to_macro_rules(&self, ctxt: SyntaxContext) -> SyntaxContext { 47,139 ( 0.00%) self.syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent 18,046 ( 0.00%) } . 25,012 ( 0.00%) fn outer_expn(&self, ctxt: SyntaxContext) -> ExpnId { 474,786 ( 0.02%) self.syntax_context_data[ctxt.0 as usize].outer_expn 25,012 ( 0.00%) } . 2,688 ( 0.00%) fn outer_mark(&self, ctxt: SyntaxContext) -> (ExpnId, Transparency) { 1,421 ( 0.00%) let data = &self.syntax_context_data[ctxt.0 as usize]; 5,992 ( 0.00%) (data.outer_expn, data.outer_transparency) 4,109 ( 0.00%) } . . fn parent_ctxt(&self, ctxt: SyntaxContext) -> SyntaxContext { 203 ( 0.00%) self.syntax_context_data[ctxt.0 as usize].parent . } . . fn remove_mark(&self, ctxt: &mut SyntaxContext) -> (ExpnId, Transparency) { 34 ( 0.00%) let outer_mark = self.outer_mark(*ctxt); 172 ( 0.00%) *ctxt = self.parent_ctxt(*ctxt); . outer_mark . } . 640 ( 0.00%) fn marks(&self, mut ctxt: SyntaxContext) -> Vec<(ExpnId, Transparency)> { . let mut marks = Vec::new(); 157 ( 0.00%) while ctxt != SyntaxContext::root() { . debug!("marks: getting parent of {:?}", ctxt); . marks.push(self.outer_mark(ctxt)); . ctxt = self.parent_ctxt(ctxt); . } . marks.reverse(); . marks 720 ( 0.00%) } . . fn walk_chain(&self, mut span: Span, to: SyntaxContext) -> Span { . debug!("walk_chain({:?}, {:?})", span, to); . debug!("walk_chain: span ctxt = {:?}", span.ctxt()); . while span.from_expansion() && span.ctxt() != to { . let outer_expn = self.outer_expn(span.ctxt()); . debug!("walk_chain({:?}): outer_expn={:?}", span, outer_expn); . let expn_data = self.expn_data(outer_expn); . debug!("walk_chain({:?}): expn_data={:?}", span, expn_data); . span = expn_data.call_site; . } . span . } . 369,200 ( 0.01%) fn adjust(&self, ctxt: &mut SyntaxContext, expn_id: ExpnId) -> Option { . let mut scope = None; 110,760 ( 0.00%) while !self.is_descendant_of(expn_id, self.outer_expn(*ctxt)) { . scope = Some(self.remove_mark(ctxt).0); . } . scope 369,200 ( 0.01%) } . 1,890 ( 0.00%) fn apply_mark( . &mut self, . ctxt: SyntaxContext, . expn_id: ExpnId, . transparency: Transparency, . ) -> SyntaxContext { 420 ( 0.00%) assert_ne!(expn_id, ExpnId::root()); 210 ( 0.00%) if transparency == Transparency::Opaque { 372 ( 0.00%) return self.apply_mark_internal(ctxt, expn_id, transparency); . } . 1,036 ( 0.00%) let call_site_ctxt = self.expn_data(expn_id).call_site.ctxt(); 148 ( 0.00%) let mut call_site_ctxt = if transparency == Transparency::SemiTransparent { . self.normalize_to_macros_2_0(call_site_ctxt) . } else { . self.normalize_to_macro_rules(call_site_ctxt) . }; . 148 ( 0.00%) if call_site_ctxt == SyntaxContext::root() { 444 ( 0.00%) return self.apply_mark_internal(ctxt, expn_id, transparency); . } . . // Otherwise, `expn_id` is a macros 1.0 definition and the call site is in a . // macros 2.0 expansion, i.e., a macros 1.0 invocation is in a macros 2.0 definition. . // . // In this case, the tokens from the macros 1.0 definition inherit the hygiene . // at their invocation. That is, we pretend that the macros 1.0 definition . // was defined at its invocation (i.e., inside the macros 2.0 definition) -- line 519 ---------------------------------------- -- line 521 ---------------------------------------- . // . // See the example at `test/ui/hygiene/legacy_interaction.rs`. . for (expn_id, transparency) in self.marks(ctxt) { . call_site_ctxt = self.apply_mark_internal(call_site_ctxt, expn_id, transparency); . } . self.apply_mark_internal(call_site_ctxt, expn_id, transparency) . } . 1,680 ( 0.00%) fn apply_mark_internal( . &mut self, . ctxt: SyntaxContext, . expn_id: ExpnId, . transparency: Transparency, . ) -> SyntaxContext { . let syntax_context_data = &mut self.syntax_context_data; 1,260 ( 0.00%) let mut opaque = syntax_context_data[ctxt.0 as usize].opaque; . let mut opaque_and_semitransparent = 210 ( 0.00%) syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent; . 210 ( 0.00%) if transparency >= Transparency::Opaque { . let parent = opaque; 620 ( 0.00%) opaque = *self . .syntax_context_map . .entry((parent, expn_id, transparency)) . .or_insert_with(|| { 10 ( 0.00%) let new_opaque = SyntaxContext(syntax_context_data.len() as u32); . syntax_context_data.push(SyntaxContextData { . outer_expn: expn_id, . outer_transparency: transparency, . parent, . opaque: new_opaque, . opaque_and_semitransparent: new_opaque, . dollar_crate_name: kw::DollarCrate, . }); . new_opaque . }); . } . 256 ( 0.00%) if transparency >= Transparency::SemiTransparent { . let parent = opaque_and_semitransparent; 306 ( 0.00%) opaque_and_semitransparent = *self . .syntax_context_map . .entry((parent, expn_id, transparency)) . .or_insert_with(|| { . let new_opaque_and_semitransparent = 4 ( 0.00%) SyntaxContext(syntax_context_data.len() as u32); . syntax_context_data.push(SyntaxContextData { . outer_expn: expn_id, . outer_transparency: transparency, . parent, . opaque, . opaque_and_semitransparent: new_opaque_and_semitransparent, . dollar_crate_name: kw::DollarCrate, . }); . new_opaque_and_semitransparent . }); . } . . let parent = ctxt; 420 ( 0.00%) *self.syntax_context_map.entry((parent, expn_id, transparency)).or_insert_with(|| { . let new_opaque_and_semitransparent_and_transparent = 216 ( 0.00%) SyntaxContext(syntax_context_data.len() as u32); . syntax_context_data.push(SyntaxContextData { . outer_expn: expn_id, . outer_transparency: transparency, . parent, . opaque, . opaque_and_semitransparent, . dollar_crate_name: kw::DollarCrate, . }); . new_opaque_and_semitransparent_and_transparent . }) 1,680 ( 0.00%) } . } . . pub fn clear_syntax_context_map() { 5 ( 0.00%) HygieneData::with(|data| data.syntax_context_map = FxHashMap::default()); . } . . pub fn walk_chain(span: Span, to: SyntaxContext) -> Span { . HygieneData::with(|data| data.walk_chain(span, to)) . } . 126 ( 0.00%) pub fn update_dollar_crate_names(mut get_name: impl FnMut(SyntaxContext) -> Symbol) { . // The new contexts that need updating are at the end of the list and have `$crate` as a name. . let (len, to_update) = HygieneData::with(|data| { . ( 21 ( 0.00%) data.syntax_context_data.len(), . data.syntax_context_data . .iter() . .rev() . .take_while(|scdata| scdata.dollar_crate_name == kw::DollarCrate) . .count(), . ) . }); . // The callback must be called from outside of the `HygieneData` lock, . // since it will try to acquire it too. 63 ( 0.00%) let range_to_update = len - to_update..len; . let names: Vec<_> = . range_to_update.clone().map(|idx| get_name(SyntaxContext::from_u32(idx as u32))).collect(); . HygieneData::with(|data| { 42 ( 0.00%) range_to_update.zip(names).for_each(|(idx, name)| { 19 ( 0.00%) data.syntax_context_data[idx].dollar_crate_name = name; . }) . }) 126 ( 0.00%) } . . pub fn debug_hygiene_data(verbose: bool) -> String { . HygieneData::with(|data| { . if verbose { . format!("{:#?}", data) . } else { . let mut s = String::from(""); . s.push_str("Expansions:"); -- line 634 ---------------------------------------- -- line 674 ---------------------------------------- . } . . #[inline] . crate fn from_u32(raw: u32) -> SyntaxContext { . SyntaxContext(raw) . } . . /// Extend a syntax context with a given expansion and transparency. 240 ( 0.00%) crate fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> SyntaxContext { 208 ( 0.00%) HygieneData::with(|data| data.apply_mark(self, expn_id, transparency)) 80 ( 0.00%) } . . /// Pulls a single mark off of the syntax context. This effectively moves the . /// context up one macro definition level. That is, if we have a nested macro . /// definition as follows: . /// . /// ```rust . /// macro_rules! f { . /// macro_rules! g { -- line 692 ---------------------------------------- -- line 694 ---------------------------------------- . /// } . /// } . /// ``` . /// . /// and we have a SyntaxContext that is referring to something declared by an invocation . /// of g (call it g1), calling remove_mark will result in the SyntaxContext for the . /// invocation of f that created g1. . /// Returns the mark that was removed. 34 ( 0.00%) pub fn remove_mark(&mut self) -> ExpnId { . HygieneData::with(|data| data.remove_mark(self).0) . } . 320 ( 0.00%) pub fn marks(self) -> Vec<(ExpnId, Transparency)> { 160 ( 0.00%) HygieneData::with(|data| data.marks(self)) 320 ( 0.00%) } . . /// Adjust this context for resolution in a scope created by the given expansion. . /// For example, consider the following three resolutions of `f`: . /// . /// ```rust . /// mod foo { pub fn f() {} } // `f`'s `SyntaxContext` is empty. . /// m!(f); . /// macro m($f:ident) { -- line 716 ---------------------------------------- -- line 726 ---------------------------------------- . /// //| and it resolves to `::bar::f`. . /// bar::$f(); // `f`'s `SyntaxContext` is empty. . /// //^ Since `mod bar` is not outside this expansion, `adjust` does not change `$f`, . /// //| and it resolves to `::bar::$f`. . /// } . /// ``` . /// This returns the expansion whose definition scope we use to privacy check the resolution, . /// or `None` if we privacy check as usual (i.e., not w.r.t. a macro definition scope). 3,208 ( 0.00%) pub fn adjust(&mut self, expn_id: ExpnId) -> Option { 1,604 ( 0.00%) HygieneData::with(|data| data.adjust(self, expn_id)) 1,604 ( 0.00%) } . . /// Like `SyntaxContext::adjust`, but also normalizes `self` to macros 2.0. 142,952 ( 0.01%) pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option { . HygieneData::with(|data| { 71,476 ( 0.00%) *self = data.normalize_to_macros_2_0(*self); 107,214 ( 0.00%) data.adjust(self, expn_id) . }) 71,476 ( 0.00%) } . . /// Adjust this context for resolution in a scope created by the given expansion . /// via a glob import with the given `SyntaxContext`. . /// For example: . /// . /// ```rust . /// m!(f); . /// macro m($i:ident) { -- line 752 ---------------------------------------- -- line 787 ---------------------------------------- . . /// Undo `glob_adjust` if possible: . /// . /// ```rust . /// if let Some(privacy_checking_scope) = self.reverse_glob_adjust(expansion, glob_ctxt) { . /// assert!(self.glob_adjust(expansion, glob_ctxt) == Some(privacy_checking_scope)); . /// } . /// ``` 64 ( 0.00%) pub fn reverse_glob_adjust( . &mut self, . expn_id: ExpnId, . glob_span: Span, . ) -> Option> { . HygieneData::with(|data| { 112 ( 0.00%) if data.adjust(self, expn_id).is_some() { . return None; . } . 48 ( 0.00%) let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt()); . let mut marks = Vec::new(); . while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) { . marks.push(data.remove_mark(&mut glob_ctxt)); . } . . let scope = marks.last().map(|mark| mark.0); . while let Some((expn_id, transparency)) = marks.pop() { . *self = data.apply_mark(*self, expn_id, transparency); . } . Some(scope) . }) 32 ( 0.00%) } . 2,184 ( 0.00%) pub fn hygienic_eq(self, other: SyntaxContext, expn_id: ExpnId) -> bool { . HygieneData::with(|data| { 364 ( 0.00%) let mut self_normalized = data.normalize_to_macros_2_0(self); 1,820 ( 0.00%) data.adjust(&mut self_normalized, expn_id); 364 ( 0.00%) self_normalized == data.normalize_to_macros_2_0(other) . }) 728 ( 0.00%) } . . #[inline] . pub fn normalize_to_macros_2_0(self) -> SyntaxContext { 30,072 ( 0.00%) HygieneData::with(|data| data.normalize_to_macros_2_0(self)) . } . . #[inline] . pub fn normalize_to_macro_rules(self) -> SyntaxContext { 9,023 ( 0.00%) HygieneData::with(|data| data.normalize_to_macro_rules(self)) . } . . #[inline] . pub fn outer_expn(self) -> ExpnId { . HygieneData::with(|data| data.outer_expn(self)) . } . . /// `ctxt.outer_expn_data()` is equivalent to but faster than . /// `ctxt.outer_expn().expn_data()`. . #[inline] . pub fn outer_expn_data(self) -> ExpnData { 86,518 ( 0.00%) HygieneData::with(|data| data.expn_data(data.outer_expn(self)).clone()) . } . . #[inline] . pub fn outer_mark(self) -> (ExpnId, Transparency) { 2,472 ( 0.00%) HygieneData::with(|data| data.outer_mark(self)) . } . . pub fn dollar_crate_name(self) -> Symbol { . HygieneData::with(|data| data.syntax_context_data[self.0 as usize].dollar_crate_name) . } . 29,872 ( 0.00%) pub fn edition(self) -> Edition { 89,436 ( 0.00%) HygieneData::with(|data| data.expn_data(data.outer_expn(self)).edition) 29,872 ( 0.00%) } . } . . impl fmt::Debug for SyntaxContext { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(f, "#{}", self.0) . } . } . -- line 868 ---------------------------------------- -- line 877 ---------------------------------------- . } . . pub fn fresh_expansion_with_transparency( . self, . expn_data: ExpnData, . transparency: Transparency, . ctx: impl HashStableContext, . ) -> Span { 1,696 ( 0.00%) let expn_id = LocalExpnId::fresh(expn_data, ctx).to_expn_id(); . HygieneData::with(|data| { 636 ( 0.00%) self.with_ctxt(data.apply_mark(SyntaxContext::root(), expn_id, transparency)) . }) . } . . /// Reuses the span but adds information like the kind of the desugaring and features that are . /// allowed inside this span. 1,166 ( 0.00%) pub fn mark_with_reason( . self, . allow_internal_unstable: Option>, . reason: DesugaringKind, . edition: Edition, . ctx: impl HashStableContext, . ) -> Span { 1,696 ( 0.00%) let expn_data = ExpnData { 212 ( 0.00%) allow_internal_unstable, 954 ( 0.00%) ..ExpnData::default(ExpnKind::Desugaring(reason), self, edition, None, None) . }; . self.fresh_expansion(expn_data, ctx) 848 ( 0.00%) } . } . . /// A subset of properties from both macro definition and macro call available through global data. . /// Avoid using this if you have access to the original definition or call structures. 323,262 ( 0.01%) #[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)] . pub struct ExpnData { . // --- The part unique to each expansion. . /// The kind of this expansion - macro or compiler desugaring. . pub kind: ExpnKind, . /// The expansion that produced this expansion. 49,424 ( 0.00%) pub parent: ExpnId, . /// The location of the actual macro invocation or syntax sugar , e.g. . /// `let x = foo!();` or `if let Some(y) = x {}` . /// . /// This may recursively refer to other macro invocations, e.g., if . /// `foo!()` invoked `bar!()` internally, and there was an . /// expression inside `bar!`; the call_site of the expression in . /// the expansion would point to the `bar!` invocation; that . /// call_site span would have its own ExpnData, with the call_site -- line 924 ---------------------------------------- -- line 929 ---------------------------------------- . /// that have identical `ExpnData`s. This violates the contract of `HashStable` . /// - the two `ExpnId`s are not equal, but their `Fingerprint`s are equal . /// (since the numerical `ExpnId` value is not considered by the `HashStable` . /// implementation). . /// . /// The `disambiguator` field is set by `update_disambiguator` when two distinct . /// `ExpnId`s would end up with the same `Fingerprint`. Since `ExpnData` includes . /// a `krate` field, this value only needs to be unique within a single crate. 24,712 ( 0.00%) disambiguator: u32, . . // --- The part specific to the macro/desugaring definition. . // --- It may be reasonable to share this part between expansions with the same definition, . // --- but such sharing is known to bring some minor inconveniences without also bringing . // --- noticeable perf improvements (PR #62898). . /// The span of the macro definition (possibly dummy). . /// This span serves only informational purpose and is not used for resolution. . pub def_site: Span, . /// List of `#[unstable]`/feature-gated features that the macro is allowed to use . /// internally without forcing the whole crate to opt-in . /// to them. 1,128 ( 0.00%) pub allow_internal_unstable: Option>, . /// Whether the macro is allowed to use `unsafe` internally . /// even if the user crate has `#![forbid(unsafe_code)]`. . pub allow_internal_unsafe: bool, . /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) . /// for a given macro. . pub local_inner_macros: bool, . /// Edition of the crate in which the macro is defined. 24,712 ( 0.00%) pub edition: Edition, . /// The `DefId` of the macro being invoked, . /// if this `ExpnData` corresponds to a macro invocation 24,712 ( 0.00%) pub macro_def_id: Option, . /// The normal module (`mod`) in which the expanded macro was defined. . pub parent_module: Option, . } . . impl !PartialEq for ExpnData {} . impl !Hash for ExpnData {} . . impl ExpnData { 247 ( 0.00%) pub fn new( . kind: ExpnKind, . parent: ExpnId, . call_site: Span, . def_site: Span, . allow_internal_unstable: Option>, . allow_internal_unsafe: bool, . local_inner_macros: bool, . edition: Edition, . macro_def_id: Option, . parent_module: Option, . ) -> ExpnData { 266 ( 0.00%) ExpnData { . kind, . parent, . call_site, . def_site, . allow_internal_unstable, . allow_internal_unsafe, . local_inner_macros, . edition, . macro_def_id, . parent_module, . disambiguator: 0, . } 95 ( 0.00%) } . . /// Constructs expansion data with default properties. 318 ( 0.00%) pub fn default( . kind: ExpnKind, . call_site: Span, . edition: Edition, . macro_def_id: Option, . parent_module: Option, . ) -> ExpnData { 1,272 ( 0.00%) ExpnData { . kind, . parent: ExpnId::root(), . call_site, . def_site: DUMMY_SP, . allow_internal_unstable: None, . allow_internal_unsafe: false, . local_inner_macros: false, . edition, . macro_def_id, . parent_module, . disambiguator: 0, . } 106 ( 0.00%) } . 6 ( 0.00%) pub fn allow_unstable( . kind: ExpnKind, . call_site: Span, . edition: Edition, . allow_internal_unstable: Lrc<[Symbol]>, . macro_def_id: Option, . parent_module: Option, . ) -> ExpnData { 13 ( 0.00%) ExpnData { . allow_internal_unstable: Some(allow_internal_unstable), . ..ExpnData::default(kind, call_site, edition, macro_def_id, parent_module) . } 2 ( 0.00%) } . . #[inline] . pub fn is_root(&self) -> bool { 2 ( 0.00%) matches!(self.kind, ExpnKind::Root) . } . . #[inline] 1,134 ( 0.00%) fn hash_expn(&self, ctx: &mut impl HashStableContext) -> u64 { . let mut hasher = StableHasher::new(); . self.hash_stable(ctx, &mut hasher); . hasher.finish() 1,008 ( 0.00%) } . } . . /// Expansion kind. 254,012 ( 0.01%) #[derive(Clone, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub enum ExpnKind { . /// No expansion, aka root expansion. Only `ExpnId::root()` has this kind. . Root, . /// Expansion produced by a macro. 540 ( 0.00%) Macro(MacroKind, Symbol), . /// Transform done by the compiler on the AST. 47 ( 0.00%) AstPass(AstPass), . /// Desugaring done by the compiler during HIR lowering. 1,000 ( 0.00%) Desugaring(DesugaringKind), . /// MIR inlining . Inlined, . } . . impl ExpnKind { . pub fn descr(&self) -> String { . match *self { . ExpnKind::Root => kw::PathRoot.to_string(), -- line 1064 ---------------------------------------- -- line 1070 ---------------------------------------- . ExpnKind::AstPass(kind) => kind.descr().to_string(), . ExpnKind::Desugaring(kind) => format!("desugaring of {}", kind.descr()), . ExpnKind::Inlined => "inlined source".to_string(), . } . } . } . . /// The kind of macro invocation or definition. 2,385 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)] . #[derive(HashStable_Generic)] . pub enum MacroKind { . /// A bang macro `foo!()`. . Bang, . /// An attribute macro `#[foo]`. . Attr, . /// A derive macro `#[derive(Foo)]` . Derive, -- line 1086 ---------------------------------------- -- line 1106 ---------------------------------------- . match self { . MacroKind::Attr => "an", . _ => "a", . } . } . } . . /// The kind of AST transform. 5 ( 0.00%) #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub enum AstPass { . StdImports, . TestHarness, . ProcMacroHarness, . } . . impl AstPass { . pub fn descr(self) -> &'static str { -- line 1122 ---------------------------------------- -- line 1161 ---------------------------------------- . DesugaringKind::OpaqueTy => "`impl Trait`", . DesugaringKind::ForLoop => "`for` loop", . DesugaringKind::LetElse => "`let...else`", . DesugaringKind::WhileLoop => "`while` loop", . } . } . } . 7 ( 0.00%) #[derive(Default)] . pub struct HygieneEncodeContext { . /// All `SyntaxContexts` for which we have written `SyntaxContextData` into crate metadata. . /// This is `None` after we finish encoding `SyntaxContexts`, to ensure . /// that we don't accidentally try to encode any more `SyntaxContexts` . serialized_ctxts: Lock>, . /// The `SyntaxContexts` that we have serialized (e.g. as a result of encoding `Spans`) . /// in the most recent 'round' of serializnig. Serializing `SyntaxContextData` . /// may cause us to serialize more `SyntaxContext`s, so serialize in a loop -- line 1177 ---------------------------------------- -- line 1180 ---------------------------------------- . . serialized_expns: Lock>, . . latest_expns: Lock>, . } . . impl HygieneEncodeContext { . /// Record the fact that we need to serialize the corresponding `ExpnData`. 1,025 ( 0.00%) pub fn schedule_expn_data_for_encoding(&self, expn: ExpnId) { 410 ( 0.00%) if !self.serialized_expns.lock().contains(&expn) { 384 ( 0.00%) self.latest_expns.lock().insert(expn); . } 820 ( 0.00%) } . 8 ( 0.00%) pub fn encode( . &self, . encoder: &mut T, . mut encode_ctxt: impl FnMut(&mut T, u32, &SyntaxContextData) -> Result<(), R>, . mut encode_expn: impl FnMut(&mut T, ExpnId, &ExpnData, ExpnHash) -> Result<(), R>, . ) -> Result<(), R> { . // When we serialize a `SyntaxContextData`, we may end up serializing . // a `SyntaxContext` that we haven't seen before 5 ( 0.00%) while !self.latest_ctxts.lock().is_empty() || !self.latest_expns.lock().is_empty() { . debug!( . "encode_hygiene: Serializing a round of {:?} SyntaxContextDatas: {:?}", . self.latest_ctxts.lock().len(), . self.latest_ctxts . ); . . // Consume the current round of SyntaxContexts. . // Drop the lock() temporary early . let latest_ctxts = { std::mem::take(&mut *self.latest_ctxts.lock()) }; . . // It's fine to iterate over a HashMap, because the serialization . // of the table that we insert data into doesn't depend on insertion . // order . for_all_ctxts_in(latest_ctxts.into_iter(), |index, ctxt, data| { 18 ( 0.00%) if self.serialized_ctxts.lock().insert(ctxt) { . encode_ctxt(encoder, index, data)?; . } . Ok(()) . })?; . . let latest_expns = { std::mem::take(&mut *self.latest_expns.lock()) }; . . for_all_expns_in(latest_expns.into_iter(), |expn, data, hash| { 76 ( 0.00%) if self.serialized_expns.lock().insert(expn) { . encode_expn(encoder, expn, data, hash)?; . } . Ok(()) . })?; . } . debug!("encode_hygiene: Done serializing SyntaxContextData"); . Ok(()) 8 ( 0.00%) } . } . . #[derive(Default)] . /// Additional information used to assist in decoding hygiene data . pub struct HygieneDecodeContext { . // Maps serialized `SyntaxContext` ids to a `SyntaxContext` in the current . // global `HygieneData`. When we deserialize a `SyntaxContext`, we need to create . // a new id in the global `HygieneData`. This map tracks the ID we end up picking, -- line 1242 ---------------------------------------- -- line 1257 ---------------------------------------- . . let _old_id = hygiene_data.expn_hash_to_expn_id.insert(hash, expn_id); . debug_assert!(_old_id.is_none()); . expn_id . }) . } . . /// Register an expansion which has been decoded from the metadata of a foreign crate. 1,692 ( 0.00%) pub fn register_expn_id( . krate: CrateNum, . local_id: ExpnIndex, . data: ExpnData, . hash: ExpnHash, . ) -> ExpnId { . debug_assert!(data.parent == ExpnId::root() || krate == data.parent.krate); 1,692 ( 0.00%) let expn_id = ExpnId { krate, local_id }; . HygieneData::with(|hygiene_data| { 1,692 ( 0.00%) let _old_data = hygiene_data.foreign_expn_data.insert(expn_id, data); . debug_assert!(_old_data.is_none()); 2,820 ( 0.00%) let _old_hash = hygiene_data.foreign_expn_hashes.insert(expn_id, hash); . debug_assert!(_old_hash.is_none()); 2,256 ( 0.00%) let _old_id = hygiene_data.expn_hash_to_expn_id.insert(hash, expn_id); . debug_assert!(_old_id.is_none()); . }); . expn_id 2,256 ( 0.00%) } . . /// Decode an expansion from the metadata of a foreign crate. . pub fn decode_expn_id( . krate: CrateNum, . index: u32, . decode_data: impl FnOnce(ExpnId) -> (ExpnData, ExpnHash), . ) -> ExpnId { 2,966 ( 0.00%) if index == 0 { . debug!("decode_expn_id: deserialized root"); 638 ( 0.00%) return ExpnId::root(); . } . . let index = ExpnIndex::from_u32(index); . . // This function is used to decode metadata, so it cannot decode information about LOCAL_CRATE. . debug_assert_ne!(krate, LOCAL_CRATE); 2,328 ( 0.00%) let expn_id = ExpnId { krate, local_id: index }; . . // Fast path if the expansion has already been decoded. 2,328 ( 0.00%) if HygieneData::with(|hygiene_data| hygiene_data.foreign_expn_data.contains_key(&expn_id)) { 1,800 ( 0.00%) return expn_id; . } . . // Don't decode the data inside `HygieneData::with`, since we need to recursively decode . // other ExpnIds 3,948 ( 0.00%) let (expn_data, hash) = decode_data(expn_id); . 5,076 ( 0.00%) register_expn_id(krate, index, expn_data, hash) . } . . // Decodes `SyntaxContext`, using the provided `HygieneDecodeContext` . // to track which `SyntaxContext`s we have already decoded. . // The provided closure will be invoked to deserialize a `SyntaxContextData` . // if we haven't already seen the id of the `SyntaxContext` we are deserializing. . pub fn decode_syntax_context SyntaxContextData>( . d: &mut D, . context: &HygieneDecodeContext, . decode_data: F, . ) -> SyntaxContext { 13,246 ( 0.00%) let raw_id: u32 = Decodable::decode(d); 26,492 ( 0.00%) if raw_id == 0 { . debug!("decode_syntax_context: deserialized root"); . // The root is special . return SyntaxContext::root(); . } . . let outer_ctxts = &context.remapped_ctxts; . . // Ensure that the lock() temporary is dropped early . { 4,698 ( 0.00%) if let Some(ctxt) = outer_ctxts.lock().get(raw_id as usize).copied().flatten() { . return ctxt; . } . } . . // Allocate and store SyntaxContext id *before* calling the decoder function, . // as the SyntaxContextData may reference itself. 544 ( 0.00%) let new_ctxt = HygieneData::with(|hygiene_data| { 544 ( 0.00%) let new_ctxt = SyntaxContext(hygiene_data.syntax_context_data.len() as u32); . // Push a dummy SyntaxContextData to ensure that nobody else can get the . // same ID as us. This will be overwritten after call `decode_Data` . hygiene_data.syntax_context_data.push(SyntaxContextData { 544 ( 0.00%) outer_expn: ExpnId::root(), . outer_transparency: Transparency::Transparent, . parent: SyntaxContext::root(), . opaque: SyntaxContext::root(), . opaque_and_semitransparent: SyntaxContext::root(), . dollar_crate_name: kw::Empty, . }); . let mut ctxts = outer_ctxts.lock(); . let new_len = raw_id as usize + 1; 1,632 ( 0.00%) if ctxts.len() < new_len { . ctxts.resize(new_len, None); . } 1,088 ( 0.00%) ctxts[raw_id as usize] = Some(new_ctxt); . drop(ctxts); . new_ctxt . }); . . // Don't try to decode data while holding the lock, since we need to . // be able to recursively decode a SyntaxContext 1,088 ( 0.00%) let mut ctxt_data = decode_data(d, raw_id); . // Reset `dollar_crate_name` so that it will be updated by `update_dollar_crate_names` . // We don't care what the encoding crate set this to - we want to resolve it . // from the perspective of the current compilation session 1,088 ( 0.00%) ctxt_data.dollar_crate_name = kw::DollarCrate; . . // Overwrite the dummy data with our decoded SyntaxContextData . HygieneData::with(|hygiene_data| { . let dummy = std::mem::replace( 544 ( 0.00%) &mut hygiene_data.syntax_context_data[new_ctxt.as_u32() as usize], . ctxt_data, . ); . // Make sure nothing weird happening while `decode_data` was running 544 ( 0.00%) assert_eq!(dummy.dollar_crate_name, kw::Empty); . }); . 1,088 ( 0.00%) new_ctxt . } . . fn for_all_ctxts_in Result<(), E>>( . ctxts: impl Iterator, . mut f: F, . ) -> Result<(), E> { . let all_data: Vec<_> = HygieneData::with(|data| { 20 ( 0.00%) ctxts.map(|ctxt| (ctxt, data.syntax_context_data[ctxt.0 as usize].clone())).collect() . }); 81 ( 0.00%) for (ctxt, data) in all_data.into_iter() { . f(ctxt.0, ctxt, &data)?; . } . Ok(()) . } . . fn for_all_expns_in( . expns: impl Iterator, . mut f: impl FnMut(ExpnId, &ExpnData, ExpnHash) -> Result<(), E>, . ) -> Result<(), E> { . let all_data: Vec<_> = HygieneData::with(|data| { 342 ( 0.00%) expns.map(|expn| (expn, data.expn_data(expn).clone(), data.expn_hash(expn))).collect() . }); 295 ( 0.00%) for (expn, data, hash) in all_data.into_iter() { . f(expn, &data, hash)?; . } . Ok(()) . } . . impl Encodable for LocalExpnId { . fn encode(&self, e: &mut E) -> Result<(), E::Error> { . self.to_expn_id().encode(e) -- line 1411 ---------------------------------------- -- line 1430 ---------------------------------------- . } . } . . pub fn raw_encode_syntax_context( . ctxt: SyntaxContext, . context: &HygieneEncodeContext, . e: &mut E, . ) -> Result<(), E::Error> { 177,568 ( 0.01%) if !context.serialized_ctxts.lock().contains(&ctxt) { 88,725 ( 0.00%) context.latest_ctxts.lock().insert(ctxt); . } . ctxt.0.encode(e) . } . . impl Encodable for SyntaxContext { . default fn encode(&self, _: &mut E) -> Result<(), E::Error> { . panic!("cannot encode `SyntaxContext` with `{}`", std::any::type_name::()); . } -- line 1447 ---------------------------------------- -- line 1457 ---------------------------------------- . /// such that the `Fingerprint` of the `ExpnData` does not collide with . /// any other `ExpnIds`. . /// . /// This method is called only when an `ExpnData` is first associated . /// with an `ExpnId` (when the `ExpnId` is initially constructed, or via . /// `set_expn_data`). It is *not* called for foreign `ExpnId`s deserialized . /// from another crate's metadata - since `ExpnHash` includes the stable crate id, . /// collisions are only possible between `ExpnId`s within the same crate. 180 ( 0.00%) fn update_disambiguator(expn_data: &mut ExpnData, mut ctx: impl HashStableContext) -> ExpnHash { . // This disambiguator should not have been set yet. 252 ( 0.00%) assert_eq!( . expn_data.disambiguator, 0, . "Already set disambiguator for ExpnData: {:?}", . expn_data . ); 252 ( 0.00%) assert_default_hashing_controls(&ctx, "ExpnData (disambiguator)"); 524 ( 0.00%) let mut expn_hash = expn_data.hash_expn(&mut ctx); . . let disambiguator = HygieneData::with(|data| { . // If this is the first ExpnData with a given hash, then keep our . // disambiguator at 0 (the default u32 value) . let disambig = data.expn_data_disambiguators.entry(expn_hash).or_default(); 126 ( 0.00%) let disambiguator = *disambig; 504 ( 0.00%) *disambig += 1; . disambiguator . }); . 252 ( 0.00%) if disambiguator != 0 { . debug!("Set disambiguator for expn_data={:?} expn_hash={:?}", expn_data, expn_hash); . . expn_data.disambiguator = disambiguator; . expn_hash = expn_data.hash_expn(&mut ctx); . . // Verify that the new disambiguator makes the hash unique . #[cfg(debug_assertions)] . HygieneData::with(|data| { -- line 1492 ---------------------------------------- -- line 1493 ---------------------------------------- . assert_eq!( . data.expn_data_disambiguators.get(&expn_hash), . None, . "Hash collision after disambiguator update!", . ); . }); . } . 252 ( 0.00%) ExpnHash::new(ctx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(), expn_hash) 180 ( 0.00%) } . . impl HashStable for SyntaxContext { 1,077,400 ( 0.04%) fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { . const TAG_EXPANSION: u8 = 0; . const TAG_NO_EXPANSION: u8 = 1; . 271,270 ( 0.01%) if *self == SyntaxContext::root() { . TAG_NO_EXPANSION.hash_stable(ctx, hasher); . } else { . TAG_EXPANSION.hash_stable(ctx, hasher); 432 ( 0.00%) let (expn_id, transparency) = self.outer_mark(); 3,552 ( 0.00%) expn_id.hash_stable(ctx, hasher); . transparency.hash_stable(ctx, hasher); . } 1,069,176 ( 0.04%) } . } . . impl HashStable for ExpnId { 2,394 ( 0.00%) fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { . assert_default_hashing_controls(ctx, "ExpnId"); 5,880 ( 0.00%) let hash = if *self == ExpnId::root() { . // Avoid fetching TLS storage for a trivial often-used value. . Fingerprint::ZERO . } else { . self.expn_hash().0 . }; . . hash.hash_stable(ctx, hasher); 1,710 ( 0.00%) } . } 417,676 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs -------------------------------------------------------------------------------- Ir -- line 141 ---------------------------------------- . /// ``` . /// let a = [1, 2, 3]; . /// assert!(!a.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.39.0")] . #[inline] . pub const fn is_empty(&self) -> bool { 1,029,598 ( 0.04%) self.len() == 0 . } . . /// Returns the first element of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; -- line 157 ---------------------------------------- -- line 159 ---------------------------------------- . /// . /// let w: &[i32] = &[]; . /// assert_eq!(None, w.first()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn first(&self) -> Option<&T> { 6,659 ( 0.00%) if let [first, ..] = self { Some(first) } else { None } . } . . /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 175 ---------------------------------------- -- line 178 ---------------------------------------- . /// *first = 5; . /// } . /// assert_eq!(x, &[5, 1, 2]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")] . #[inline] . pub const fn first_mut(&mut self) -> Option<&mut T> { 480 ( 0.00%) if let [first, ..] = self { Some(first) } else { None } . } . . /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &[0, 1, 2]; -- line 194 ---------------------------------------- -- line 237 ---------------------------------------- . /// assert_eq!(last, &2); . /// assert_eq!(elements, &[0, 1]); . /// } . /// ``` . #[stable(feature = "slice_splits", since = "1.5.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn split_last(&self) -> Option<(&T, &[T])> { 20,081 ( 0.00%) if let [init @ .., last] = self { Some((last, init)) } else { None } . } . . /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 253 ---------------------------------------- -- line 276 ---------------------------------------- . /// . /// let w: &[i32] = &[]; . /// assert_eq!(None, w.last()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn last(&self) -> Option<&T> { 993,820 ( 0.04%) if let [.., last] = self { Some(last) } else { None } . } . . /// Returns a mutable pointer to the last item in the slice. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 292 ---------------------------------------- -- line 295 ---------------------------------------- . /// *last = 10; . /// } . /// assert_eq!(x, &[0, 1, 10]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")] . #[inline] . pub const fn last_mut(&mut self) -> Option<&mut T> { 76,084 ( 0.00%) if let [.., last] = self { Some(last) } else { None } . } . . /// Returns a reference to an element or subslice depending on the type of . /// index. . /// . /// - If given a position, returns a reference to the element at that . /// position or `None` if out of bounds. . /// - If given a range, returns the subslice corresponding to that range, -- line 311 ---------------------------------------- -- line 448 ---------------------------------------- . /// } . /// ``` . /// . /// [`as_mut_ptr`]: slice::as_mut_ptr . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")] . #[inline] . pub const fn as_ptr(&self) -> *const T { 795,781 ( 0.03%) self as *const [T] as *const T . } . . /// Returns an unsafe mutable pointer to the slice's buffer. . /// . /// The caller must ensure that the slice outlives the pointer this . /// function returns, or else it will end up pointing to garbage. . /// . /// Modifying the container referenced by this slice may cause its buffer -- line 464 ---------------------------------------- -- line 476 ---------------------------------------- . /// } . /// } . /// assert_eq!(x, &[3, 4, 6]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline] . pub const fn as_mut_ptr(&mut self) -> *mut T { 4 ( 0.00%) self as *mut [T] as *mut T . } . . /// Returns the two raw pointers spanning the slice. . /// . /// The returned range is half-open, which means that the end pointer . /// points *one past* the last element of the slice. This way, an empty . /// slice is represented by two equal pointers, and the difference between . /// the two pointers represents the size of the slice. -- line 492 ---------------------------------------- -- line 582 ---------------------------------------- . /// v.swap(2, 4); . /// assert!(v == ["a", "b", "e", "d", "c"]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] . #[inline] . #[track_caller] . pub const fn swap(&mut self, a: usize, b: usize) { 32,968 ( 0.00%) let _ = &self[a]; 37,610 ( 0.00%) let _ = &self[b]; . . // SAFETY: we just checked that both `a` and `b` are in bounds . unsafe { self.swap_unchecked(a, b) } . } . . /// Swaps two elements in the slice, without doing bounds checking. . /// . /// For a safe alternative see [`swap`]. -- line 599 ---------------------------------------- -- line 677 ---------------------------------------- . . // Because this function is first compiled in isolation, . // this check tells LLVM that the indexing below is . // in-bounds. Then after inlining -- once the actual . // lengths of the slices are known -- it's removed. . let (a, b) = (&mut a[..n], &mut b[..n]); . . for i in 0..n { 193 ( 0.00%) mem::swap(&mut a[i], &mut b[n - 1 - i]); . } . } . } . . /// Returns an iterator over the slice. . /// . /// # Examples . /// -- line 693 ---------------------------------------- -- line 1499 ---------------------------------------- . /// assert_eq!(left, [1, 2, 3, 4, 5, 6]); . /// assert_eq!(right, []); . /// } . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] . pub fn split_at(&self, mid: usize) -> (&[T], &[T]) { 18 ( 0.00%) assert!(mid <= self.len()); . // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which . // fulfills the requirements of `from_raw_parts_mut`. . unsafe { self.split_at_unchecked(mid) } . } . . /// Divides one mutable slice into two at an index. . /// . /// The first will contain all indices from `[0, mid)` (excluding -- line 1515 ---------------------------------------- -- line 1530 ---------------------------------------- . /// left[1] = 2; . /// right[1] = 4; . /// assert_eq!(v, [1, 2, 3, 4, 5, 6]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] . pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) { 7,432 ( 0.00%) assert!(mid <= self.len()); . // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which . // fulfills the requirements of `from_raw_parts_mut`. . unsafe { self.split_at_mut_unchecked(mid) } . } . . /// Divides one slice into two at an index, without doing bounds checking. . /// . /// The first will contain all indices from `[0, mid)` (excluding -- line 1546 ---------------------------------------- -- line 1628 ---------------------------------------- . pub unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut [T], &mut [T]) { . let len = self.len(); . let ptr = self.as_mut_ptr(); . . // SAFETY: Caller has to check that `0 <= mid <= self.len()`. . // . // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference . // is fine. 1,445 ( 0.00%) unsafe { (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid)) } . } . . /// Divides one slice into an array and a remainder slice at an index. . /// . /// The array will contain all indices from `[0, N)` (excluding . /// the index `N` itself) and the slice will contain all . /// indices from `[N, len)` (excluding the index `len` itself). . /// -- line 1644 ---------------------------------------- -- line 2113 ---------------------------------------- . /// assert!(!v.iter().any(|e| e == "hi")); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn contains(&self, x: &T) -> bool . where . T: PartialEq, . { 80 ( 0.00%) cmp::SliceContains::slice_contains(x, self) . } . . /// Returns `true` if `needle` is a prefix of the slice. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; -- line 2129 ---------------------------------------- -- line 2142 ---------------------------------------- . /// assert!(v.starts_with(&[])); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn starts_with(&self, needle: &[T]) -> bool . where . T: PartialEq, . { . let n = needle.len(); 9,413 ( 0.00%) self.len() >= n && needle == &self[..n] . } . . /// Returns `true` if `needle` is a suffix of the slice. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; -- line 2158 ---------------------------------------- -- line 2171 ---------------------------------------- . /// assert!(v.ends_with(&[])); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn ends_with(&self, needle: &[T]) -> bool . where . T: PartialEq, . { . let (m, n) = (self.len(), needle.len()); 3,264 ( 0.00%) m >= n && needle == &self[m - n..] . } . . /// Returns a subslice with the prefix removed. . /// . /// If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. . /// If `prefix` is empty, simply returns the original slice. . /// . /// If the slice does not start with `prefix`, returns `None`. -- line 2187 ---------------------------------------- -- line 2293 ---------------------------------------- . /// s.insert(idx, num); . /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn binary_search(&self, x: &T) -> Result . where . T: Ord, . { 3 ( 0.00%) self.binary_search_by(|p| p.cmp(x)) . } . . /// Binary searches this sorted slice with a comparator function. . /// . /// The comparator function should implement an order consistent . /// with the sort order of the underlying slice, returning an . /// order code that indicates whether its argument is `Less`, . /// `Equal` or `Greater` the desired target. -- line 2309 ---------------------------------------- -- line 2345 ---------------------------------------- . #[inline] . pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result . where . F: FnMut(&'a T) -> Ordering, . { . let mut size = self.len(); . let mut left = 0; . let mut right = size; 2,675,389 ( 0.11%) while left < right { 2,135,052 ( 0.08%) let mid = left + size / 2; . . // SAFETY: the call is made safe by the following invariants: . // - `mid >= 0` . // - `mid < size`: `mid` is limited by `[left; right)` bound. 377,049 ( 0.01%) let cmp = f(unsafe { self.get_unchecked(mid) }); . . // The reason why we use if/else control flow rather than match . // is because match reorders comparison operations, which is perf sensitive. . // This is x86 asm for u8: https://rust.godbolt.org/z/8Y8Pra. 555,511 ( 0.02%) if cmp == Less { 1,896,528 ( 0.08%) left = mid + 1; 141,447 ( 0.01%) } else if cmp == Greater { . right = mid; . } else { . // SAFETY: same as the `get_unchecked` above . unsafe { crate::intrinsics::assume(mid < self.len()) }; . return Ok(mid); . } . 1,647,372 ( 0.07%) size = right - left; . } . Err(left) . } . . /// Binary searches this sorted slice with a key extraction function. . /// . /// Assumes that the slice is sorted by the key, for instance with . /// [`sort_by_key`] using the same key extraction function. -- line 2382 ---------------------------------------- -- line 3203 ---------------------------------------- . #[track_caller] . fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! { . panic!( . "source slice length ({}) does not match destination slice length ({})", . src_len, dst_len, . ); . } . 20,722 ( 0.00%) if self.len() != src.len() { . len_mismatch_fail(self.len(), src.len()); . } . . // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was . // checked to have the same length. The slices cannot overlap because . // mutable references are exclusive. . unsafe { . ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len()); -- line 3219 ---------------------------------------- -- line 3382 ---------------------------------------- . } . let gcd: usize = gcd(mem::size_of::(), mem::size_of::()); . let ts: usize = mem::size_of::() / gcd; . let us: usize = mem::size_of::() / gcd; . . // Armed with this knowledge, we can find how many `U`s we can fit! . let us_len = self.len() / ts * us; . // And how many `T`s will be in the trailing slice! 930 ( 0.00%) let ts_len = self.len() % ts; . (us_len, ts_len) . } . . /// Transmute the slice to a slice of another type, ensuring alignment of the types is . /// maintained. . /// . /// This method splits the slice into three distinct slices: prefix, correctly aligned middle . /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest -- line 3398 ---------------------------------------- -- line 3429 ---------------------------------------- . return (self, &[], &[]); . } . . // First, find at what point do we split between the first and 2nd slice. Easy with . // ptr.align_offset. . let ptr = self.as_ptr(); . // SAFETY: See the `align_to_mut` method for the detailed safety comment. . let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::()) }; 930 ( 0.00%) if offset > self.len() { . (self, &[], &[]) . } else { . let (left, rest) = self.split_at(offset); . let (us_len, ts_len) = rest.align_to_offsets::(); . // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay, . // since the caller guarantees that we can transmute `T` to `U` safely. . unsafe { . ( . left, . from_raw_parts(rest.as_ptr() as *const U, us_len), 930 ( 0.00%) from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len), . ) . } . } . } . . /// Transmute the slice to a slice of another type, ensuring alignment of the types is . /// maintained. . /// -- line 3456 ---------------------------------------- 1,719,449 ( 0.07%) -------------------------------------------------------------------------------- -- 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 { 32 ( 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 { 165,530 ( 0.01%) match self { 234,428 ( 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. 5 ( 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 { 113 ( 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>> { 126,295 ( 0.00%) if mplace.layout.is_unsized() { . // Don't touch unsized . return Ok(None); . } . 295,611 ( 0.01%) let alloc = match self.get_alloc(mplace)? { 492,685 ( 0.02%) Some(ptr) => ptr, . None => { . return Ok(Some(ImmTy { . // zero-sized type . imm: Scalar::ZST.into(), . layout: mplace.layout, . })); . } . }; . 784,514 ( 0.03%) match mplace.layout.abi { . Abi::Scalar(..) => { 82,767 ( 0.00%) let scalar = alloc.read_scalar(alloc_range(Size::ZERO, mplace.layout.size))?; . Ok(Some(ImmTy { imm: scalar.into(), layout: mplace.layout })) . } 5,673 ( 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); 3,782 ( 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))?; 5,673 ( 0.00%) let b_val = alloc.read_scalar(alloc_range(b_offset, b_size))?; 9,455 ( 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. 1,078,398 ( 0.04%) pub fn try_read_immediate( . &self, . src: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Result, MPlaceTy<'tcx, M::PointerTag>>> { 2,156,796 ( 0.09%) Ok(match src.try_as_mplace() { . Ok(ref mplace) => { 197,074 ( 0.01%) if let Some(val) = self.try_read_immediate_from_mplace(mplace)? { . Ok(val) . } else { . Err(*mplace) . } . } 212,850 ( 0.01%) Err(val) => Ok(val), . }) 1,078,398 ( 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>> { 272,553 ( 0.01%) if let Ok(imm) = self.try_read_immediate(op)? { 469,040 ( 0.02%) Ok(imm) . } else { . span_bug!(self.cur_span(), "primitive read failed for type: {:?}", op.layout.ty); . } . } . . /// Read a scalar from a place 644,677 ( 0.03%) pub fn read_scalar( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, ScalarMaybeUninit> { 58,607 ( 0.00%) Ok(self.read_immediate(op)?.to_scalar_or_uninit()) 527,463 ( 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 944,090 ( 0.04%) 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)?; 1,038,477 ( 0.04%) return Ok(field.into()); . } 14 ( 0.00%) 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 }); . } 6 ( 0.00%) let offset = op.layout.fields.offset(field); 4 ( 0.00%) let immediate = match *base { . // the field covers the entire type 12 ( 0.00%) _ if offset.bytes() == 0 && field_layout.size == op.layout.size => *base, . // extract fields from types with `ScalarPair` ABI . Immediate::ScalarPair(a, b) => { 2 ( 0.00%) let val = if offset.bytes() == 0 { a } else { b }; . Immediate::from(val) . } . Immediate::Scalar(val) => span_bug!( . self.cur_span(), . "field access on non aggregate {:#?}, {:#?}", . val, . op.layout . ), . }; 28 ( 0.00%) Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout }) 849,681 ( 0.03%) } . . 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()) . } . } . 177,122 ( 0.01%) pub fn operand_downcast( . &self, . op: &OpTy<'tcx, M::PointerTag>, . variant: VariantIdx, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . // Downcasts only change the layout 273,734 ( 0.01%) Ok(match op.try_as_mplace() { 161,020 ( 0.01%) Ok(ref mplace) => self.mplace_downcast(mplace, variant)?.into(), . Err(..) => { . let layout = op.layout.for_variant(self, variant); . OpTy { layout, ..*op } . } . }) 144,918 ( 0.01%) } . 8 ( 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::*; 32 ( 0.00%) Ok(match proj_elem { 6 ( 0.00%) Field(field, _) => self.operand_field(base, field.index())?, . 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() . } . }) 8 ( 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 142,056 ( 0.01%) 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)?; 13,879 ( 0.00%) let op = if layout.is_zst() { . // Do not read from ZST, they might not be initialized . Operand::Immediate(Scalar::ZST.into()) . } else { . M::access_local(&self, frame, local)? . }; 205,192 ( 0.01%) Ok(OpTy { op, layout }) 126,272 ( 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>> { 8 ( 0.00%) let op = match **place { . Place::Ptr(mplace) => Operand::Indirect(mplace), . Place::Local { frame, local } => { 36 ( 0.00%) *self.access_local(&self.stack()[frame], local, None)? . } . }; 28 ( 0.00%) Ok(OpTy { op, layout: place.layout }) . } . . // Evaluate a place with the goal of reading from it. This lets us sometimes . // avoid allocations. 126,120 ( 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. 15,765 ( 0.00%) let layout = if place.projection.is_empty() { layout } else { None }; . 47,295 ( 0.00%) let base_op = self.access_local(self.frame(), place.local, layout)?; . . let op = place . .projection . .iter() 18 ( 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, . )); 47,295 ( 0.00%) Ok(op) 141,885 ( 0.01%) } . . /// 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] 333,243 ( 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::*; 74,054 ( 0.00%) let op = match *mir_op { . // FIXME: do some more logic on `move` to invalidate the old location 78,825 ( 0.00%) Copy(place) | Move(place) => self.eval_place_to_op(place, layout)?, . . Constant(ref constant) => { . let val = 318,930 ( 0.01%) 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. . . self.mir_const_to_op(&val, layout)? . } . }; . trace!("{:?}: {:?}", mir_op, *op); 481,351 ( 0.02%) Ok(op) 222,162 ( 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). 255,144 ( 0.01%) pub fn const_to_op( . &self, . val: &ty::Const<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { 106,310 ( 0.00%) match val.val { . ty::ConstKind::Param(_) | ty::ConstKind::Bound(..) => throw_inval!(TooGeneric), . ty::ConstKind::Error(_) => throw_inval!(AlreadyReported(ErrorReported)), . ty::ConstKind::Unevaluated(uv) => { . let instance = self.resolve(uv.def, uv.substs)?; . 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) . } 212,620 ( 0.01%) ty::ConstKind::Value(val_val) => self.const_val_to_op(val_val, val.ty, layout), . } 191,358 ( 0.01%) } . . pub fn mir_const_to_op( . &self, . val: &mir::ConstantKind<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { 42,524 ( 0.00%) match val { 85,048 ( 0.00%) mir::ConstantKind::Ty(ct) => self.const_to_op(ct, layout), . mir::ConstantKind::Val(val, ty) => self.const_val_to_op(*val, ty, layout), . } . } . 212,620 ( 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, _> { 127,560 ( 0.01%) Ok(match scalar { . Scalar::Ptr(ptr, size) => Scalar::Ptr(self.global_base_pointer(ptr)?, size), 63,774 ( 0.00%) Scalar::Int(int) => Scalar::Int(int), . }) . }; 6 ( 0.00%) let layout = from_known_layout(self.tcx, self.param_env, layout, || self.layout_of(ty))?; 63,790 ( 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)) . } 191,340 ( 0.01%) ConstValue::Scalar(x) => Operand::Immediate(tag_scalar(x)?.into()), 6 ( 0.00%) 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( 6 ( 0.00%) 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, . )) . } . }; 446,502 ( 0.02%) Ok(OpTy { op, layout }) 170,096 ( 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)! 241,530 ( 0.01%) pub fn read_discriminant( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, (Scalar, VariantIdx)> { . trace!("read_discriminant_value {:#?}", op.layout); . // Get type and layout of the discriminant. 289,836 ( 0.01%) let discr_layout = self.layout_of(op.layout.ty.discriminant_ty(*self.tcx))?; . trace!("discriminant type: {:?}", discr_layout.ty); . . // We use "discriminant" to refer to the value associated with a particular enum variant. . // This is not to be confused with its "variant index", which is just determining its position in the . // declared list of variants -- they can differ with explicitly assigned discriminants. . // We use "tag" to refer to how the discriminant is encoded in memory, which can be either . // straight-forward (`TagEncoding::Direct`) or with a niche (`TagEncoding::Niche`). 72,459 ( 0.00%) let (tag_scalar_layout, tag_encoding, tag_field) = match op.layout.variants { . Variants::Single { index } => { . let discr = match op.layout.ty.discriminant_for_variant(*self.tcx, index) { . Some(discr) => { . // This type actually has discriminants. . assert_eq!(discr.ty, discr_layout.ty); . Scalar::from_uint(discr.val, discr_layout.size) . } . None => { . // On a type without actual discriminants, variant is 0. . assert_eq!(index.as_u32(), 0); . Scalar::from_uint(index.as_u32(), discr_layout.size) . } . }; . return Ok((discr, index)); . } 48,306 ( 0.00%) Variants::Multiple { tag, ref tag_encoding, tag_field, .. } => { . (tag, tag_encoding, tag_field) . } . }; . . // There are *three* layouts that come into play here: . // - The discriminant has a type for typechecking. This is `discr_layout`, and is used for . // the `Scalar` we return. . // - The tag (encoded discriminant) has layout `tag_layout`. This is always an integer type, . // and used to interpret the value we read from the tag field. . // For the return value, a cast to `discr_layout` is performed. . // - The field storing the tag has a layout, which is very similar to `tag_layout` but . // may be a pointer. This is `tag_val.layout`; we just use it for sanity checks. . . // Get layout for tag. 144,918 ( 0.01%) let tag_layout = self.layout_of(tag_scalar_layout.value.to_int_ty(*self.tcx))?; . . // Read tag and sanity-check `tag_layout`. 169,071 ( 0.01%) let tag_val = self.read_immediate(&self.operand_field(op, tag_field)?)?; 48,306 ( 0.00%) assert_eq!(tag_layout.size, tag_val.layout.size); 193,224 ( 0.01%) assert_eq!(tag_layout.abi.is_signed(), tag_val.layout.abi.is_signed()); . let tag_val = tag_val.to_scalar()?; . trace!("tag value: {:?}", tag_val); . . // Figure out which discriminant and variant this corresponds to. 217,377 ( 0.01%) Ok(match *tag_encoding { . TagEncoding::Direct => { 483,060 ( 0.02%) let tag_bits = tag_val . .try_to_int() . .map_err(|dbg_val| err_ub!(InvalidTag(dbg_val)))? . .assert_bits(tag_layout.size); . // Cast bits from tag layout to discriminant layout. 193,224 ( 0.01%) let discr_val = self.cast_from_scalar(tag_bits, tag_layout, discr_layout.ty); 48,306 ( 0.00%) let discr_bits = discr_val.assert_bits(discr_layout.size); . // Convert discriminant to variant index, and catch invalid discriminants. 120,765 ( 0.00%) let index = match *op.layout.ty.kind() { 24,153 ( 0.00%) ty::Adt(adt, _) => { 458,118 ( 0.02%) adt.discriminants(*self.tcx).find(|(_, var)| var.val == discr_bits) . } . ty::Generator(def_id, substs, _) => { . let substs = substs.as_generator(); . substs . .discriminants(def_id, *self.tcx) . .find(|(_, var)| var.val == discr_bits) . } . _ => span_bug!(self.cur_span(), "tagged layout for non-adt non-generator"), . } . .ok_or_else(|| err_ub!(InvalidTag(Scalar::from_uint(tag_bits, tag_layout.size))))?; . // Return the cast value, and the index. 96,612 ( 0.00%) (discr_val, index.0) . } . TagEncoding::Niche { dataful_variant, ref niche_variants, niche_start } => { . // Compute the variant this niche value/"tag" corresponds to. With niche layout, . // discriminant (encoded in niche/tag) and variant index are the same. . let variants_start = niche_variants.start().as_u32(); . let variants_end = niche_variants.end().as_u32(); . let variant = match tag_val.try_to_int() { . Err(dbg_val) => { -- line 721 ---------------------------------------- -- line 766 ---------------------------------------- . } . }; . // Compute the size of the scalar we need to return. . // No need to cast, because the variant index directly serves as discriminant and is . // encoded in the tag. . (Scalar::from_uint(variant.as_u32(), discr_layout.size), variant) . } . }) 217,377 ( 0.01%) } . } 3,069,099 ( 0.12%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/stacker-0.1.14/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 42 ---------------------------------------- . /// `stack_size` bytes. . /// . /// The closure `f` is guaranteed to run on a stack with at least `red_zone` bytes, and it will be . /// run on the current stack if there's space available. . #[inline(always)] . pub fn maybe_grow R>(red_zone: usize, stack_size: usize, callback: F) -> R { . // if we can't guess the remaining stack (unsupported on some platforms) we immediately grow . // the stack and then cache the new stack size (which we do know now because we allocated it. 538,110 ( 0.02%) let enough_space = match remaining_stack() { . Some(remaining) => remaining >= red_zone, . None => false, . }; 784,560 ( 0.03%) if enough_space { 22,659 ( 0.00%) callback() . } else { . grow(stack_size, callback) . } . } . . /// Always creates a new stack for the passed closure to run on. . /// The closure will still be on the same thread as the caller of `grow`. . /// This will allocate a new stack with at least `stack_size` bytes. -- line 63 ---------------------------------------- -- line 82 ---------------------------------------- . _grow(stack_size, dyn_callback); . ret.unwrap() . } . . /// Queries the amount of remaining stack as interpreted by this library. . /// . /// This function will return the amount of stack space left which will be used . /// to determine whether a stack switch should be made or not. 523,040 ( 0.02%) pub fn remaining_stack() -> Option { . let current_ptr = current_stack_ptr(); 523,040 ( 0.02%) get_stack_limit().map(|limit| current_ptr - limit) 1,046,080 ( 0.04%) } . . psm_stack_information! ( . yes { . fn current_stack_ptr() -> usize { 523,040 ( 0.02%) psm::stack_pointer() as usize . } . } . no { . #[inline(always)] . fn current_stack_ptr() -> usize { . unsafe { . let mut x = std::mem::MaybeUninit::::uninit(); . // Unlikely to be ever exercised. As a fallback we execute a volatile read to a -- line 106 ---------------------------------------- -- line 111 ---------------------------------------- . x.as_ptr() as usize . } . } . } . ); . . thread_local! { . static STACK_LIMIT: Cell> = Cell::new(unsafe { 1 ( 0.00%) guess_os_stack_limit() . }) . } . . #[inline(always)] . fn get_stack_limit() -> Option { . STACK_LIMIT.with(|s| s.get()) . } . -- line 127 ---------------------------------------- -- line 403 ---------------------------------------- . VirtualQuery( . psm::stack_pointer() as *const _, . mi.as_mut_ptr(), . std::mem::size_of::() as SIZE_T, . ); . Some(mi.assume_init().AllocationBase as usize + get_thread_stack_guarantee() + 0x1000) . } . } else if #[cfg(any(target_os = "linux", target_os="solaris", target_os = "netbsd"))] { 2 ( 0.00%) unsafe fn guess_os_stack_limit() -> Option { . let mut attr = std::mem::MaybeUninit::::uninit(); 4 ( 0.00%) assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0); 7 ( 0.00%) assert_eq!(libc::pthread_getattr_np(libc::pthread_self(), . attr.as_mut_ptr()), 0); 1 ( 0.00%) let mut stackaddr = std::ptr::null_mut(); 4 ( 0.00%) let mut stacksize = 0; 4 ( 0.00%) assert_eq!(libc::pthread_attr_getstack( . attr.as_ptr(), &mut stackaddr, &mut stacksize . ), 0); 4 ( 0.00%) assert_eq!(libc::pthread_attr_destroy(attr.as_mut_ptr()), 0); 1 ( 0.00%) Some(stackaddr as usize) 3 ( 0.00%) } . } else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] { . unsafe fn guess_os_stack_limit() -> Option { . let mut attr = std::mem::MaybeUninit::::uninit(); . assert_eq!(libc::pthread_attr_init(attr.as_mut_ptr()), 0); . assert_eq!(libc::pthread_attr_get_np(libc::pthread_self(), attr.as_mut_ptr()), 0); . let mut stackaddr = std::ptr::null_mut(); . let mut stacksize = 0; . assert_eq!(libc::pthread_attr_getstack( -- line 431 ---------------------------------------- 343,821 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/opaque.rs -------------------------------------------------------------------------------- Ir -- line 14 ---------------------------------------- . . pub type EncodeResult = Result<(), !>; . . pub struct Encoder { . pub data: Vec, . } . . impl Encoder { 1 ( 0.00%) pub fn new(data: Vec) -> Encoder { 4 ( 0.00%) Encoder { data } 1 ( 0.00%) } . 1 ( 0.00%) pub fn into_inner(self) -> Vec { 4 ( 0.00%) self.data 1 ( 0.00%) } . . #[inline] . pub fn position(&self) -> usize { 80,415 ( 0.00%) self.data.len() . } . } . . macro_rules! write_leb128 { . ($enc:expr, $value:expr, $int_ty:ty, $fun:ident) => {{ . const MAX_ENCODED_LEN: usize = max_leb128_len!($int_ty); . let old_len = $enc.data.len(); . -- line 40 ---------------------------------------- -- line 67 ---------------------------------------- . . #[inline] . fn emit_unit(&mut self) -> EncodeResult { . Ok(()) . } . . #[inline] . fn emit_usize(&mut self, v: usize) -> EncodeResult { 3,764,961 ( 0.15%) write_leb128!(self, v, usize, write_usize_leb128) . } . . #[inline] . fn emit_u128(&mut self, v: u128) -> EncodeResult { 148,862 ( 0.01%) write_leb128!(self, v, u128, write_u128_leb128) . } . . #[inline] . fn emit_u64(&mut self, v: u64) -> EncodeResult { 1,890 ( 0.00%) write_leb128!(self, v, u64, write_u64_leb128) . } . . #[inline] . fn emit_u32(&mut self, v: u32) -> EncodeResult { 2,817,982 ( 0.11%) write_leb128!(self, v, u32, write_u32_leb128) . } . . #[inline] . fn emit_u16(&mut self, v: u16) -> EncodeResult { . self.data.extend_from_slice(&v.to_le_bytes()); . Ok(()) . } . -- line 98 ---------------------------------------- -- line 131 ---------------------------------------- . #[inline] . fn emit_i8(&mut self, v: i8) -> EncodeResult { . let as_u8: u8 = unsafe { std::mem::transmute(v) }; . self.emit_u8(as_u8) . } . . #[inline] . fn emit_bool(&mut self, v: bool) -> EncodeResult { 32,026 ( 0.00%) self.emit_u8(if v { 1 } else { 0 }) . } . . #[inline] . fn emit_f64(&mut self, v: f64) -> EncodeResult { . let as_u64: u64 = v.to_bits(); . self.emit_u64(as_u64) . } . -- line 147 ---------------------------------------- -- line 549 ---------------------------------------- . #[inline] . pub fn advance(&mut self, bytes: usize) { . self.position += bytes; . } . . #[inline] . pub fn read_raw_bytes(&mut self, bytes: usize) -> &'a [u8] { . let start = self.position; 24 ( 0.00%) self.position += bytes; 24 ( 0.00%) &self.data[start..self.position] . } . } . . macro_rules! read_leb128 { . ($dec:expr, $fun:ident) => {{ leb128::$fun($dec.data, &mut $dec.position) }}; . } . . impl<'a> serialize::Decoder for Decoder<'a> { . #[inline] . fn read_unit(&mut self) -> () { . () . } . . #[inline] . fn read_u128(&mut self) -> u128 { 668 ( 0.00%) read_leb128!(self, read_u128_leb128) . } . . #[inline] . fn read_u64(&mut self) -> u64 { 3,266 ( 0.00%) read_leb128!(self, read_u64_leb128) . } . . #[inline] 53,959 ( 0.00%) fn read_u32(&mut self) -> u32 { 206,310 ( 0.01%) read_leb128!(self, read_u32_leb128) 107,918 ( 0.00%) } . . #[inline] . fn read_u16(&mut self) -> u16 { 563,892 ( 0.02%) let bytes = [self.data[self.position], self.data[self.position + 1]]; 80,556 ( 0.00%) let value = u16::from_le_bytes(bytes); 161,118 ( 0.01%) self.position += 2; . value . } . . #[inline] . fn read_u8(&mut self) -> u8 { 2,176,560 ( 0.09%) let value = self.data[self.position]; 418,987 ( 0.02%) self.position += 1; . value . } . . #[inline] 248,913 ( 0.01%) fn read_usize(&mut self) -> usize { 248,937 ( 0.01%) read_leb128!(self, read_usize_leb128) 497,826 ( 0.02%) } . . #[inline] . fn read_i128(&mut self) -> i128 { . read_leb128!(self, read_i128_leb128) . } . . #[inline] . fn read_i64(&mut self) -> i64 { -- line 613 ---------------------------------------- -- line 637 ---------------------------------------- . #[inline] . fn read_isize(&mut self) -> isize { . read_leb128!(self, read_isize_leb128) . } . . #[inline] . fn read_bool(&mut self) -> bool { . let value = self.read_u8(); 25,141 ( 0.00%) value != 0 . } . . #[inline] . fn read_f64(&mut self) -> f64 { . let bits = self.read_u64(); . f64::from_bits(bits) . } . -- line 653 ---------------------------------------- -- line 660 ---------------------------------------- . #[inline] . fn read_char(&mut self) -> char { . let bits = self.read_u32(); . std::char::from_u32(bits).unwrap() . } . . #[inline] . fn read_str(&mut self) -> Cow<'_, str> { 39,857 ( 0.00%) let len = self.read_usize(); 216,648 ( 0.01%) let sentinel = self.data[self.position + len]; 54,180 ( 0.00%) assert!(sentinel == STR_SENTINEL); . let s = unsafe { . std::str::from_utf8_unchecked(&self.data[self.position..self.position + len]) . }; 135,450 ( 0.01%) self.position += len + 1; 38,373 ( 0.00%) Cow::Borrowed(s) . } . . #[inline] . fn read_raw_bytes_into(&mut self, s: &mut [u8]) { 124 ( 0.00%) let start = self.position; 2,188 ( 0.00%) self.position += s.len(); 124 ( 0.00%) s.copy_from_slice(&self.data[start..self.position]); . } . } . . // Specializations for contiguous byte sequences follow. The default implementations for slices . // encode and decode each element individually. This isn't necessary for `u8` slices when using . // opaque encoders and decoders, because each `u8` is unchanged by encoding and decoding. . // Therefore, we can use more efficient implementations that process the entire sequence at once. . -- line 690 ---------------------------------------- 2,812,789 ( 0.11%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs -------------------------------------------------------------------------------- Ir -- line 32 ---------------------------------------- . /// . /// If the syntax extension is an MBE macro, it will attempt to match its . /// LHS token tree against the provided token tree, and if it finds a . /// match, will transcribe the RHS token tree, splicing in any captured . /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds. . /// . /// The RHS of an MBE macro is the only place `SubstNt`s are substituted. . /// Nothing special happens to misnamed or misplaced `SubstNt`s. 1,060,266 ( 0.04%) #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub enum TokenTree { . /// A single token. 394,363 ( 0.02%) Token(Token), . /// A delimited sequence of token trees. 28,668 ( 0.00%) Delimited(DelimSpan, DelimToken, TokenStream), . } . . #[derive(Copy, Clone)] . pub enum CanSynthesizeMissingTokens { . Yes, . No, . } . -- line 53 ---------------------------------------- -- line 71 ---------------------------------------- . delim == delim2 && tts.eq_unspanned(&tts2) . } . _ => false, . } . } . . /// Retrieves the `TokenTree`'s span. . pub fn span(&self) -> Span { 20 ( 0.00%) match self { 31 ( 0.00%) TokenTree::Token(token) => token.span, 20 ( 0.00%) TokenTree::Delimited(sp, ..) => sp.entire(), . } 6 ( 0.00%) } . . /// Modify the `TokenTree`'s span in-place. . pub fn set_span(&mut self, span: Span) { 20 ( 0.00%) match self { 6 ( 0.00%) TokenTree::Token(token) => token.span = span, 8 ( 0.00%) TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span), . } 10 ( 0.00%) } . 3 ( 0.00%) pub fn token(kind: TokenKind, span: Span) -> TokenTree { 113,896 ( 0.00%) TokenTree::Token(Token::new(kind, span)) 3 ( 0.00%) } . . /// Returns the opening delimiter as a token tree. 14,251 ( 0.00%) pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 42,753 ( 0.00%) TokenTree::token(token::OpenDelim(delim), span.open) 14,251 ( 0.00%) } . . /// Returns the closing delimiter as a token tree. 14,220 ( 0.00%) pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 42,660 ( 0.00%) TokenTree::token(token::CloseDelim(delim), span.close) 14,220 ( 0.00%) } . 336 ( 0.00%) pub fn uninterpolate(self) -> TokenTree { 224 ( 0.00%) match self { 1,008 ( 0.00%) TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()), . tt => tt, . } 448 ( 0.00%) } . } . . impl HashStable for TokenStream . where . CTX: crate::HashStableContext, . { 189 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 516 ( 0.00%) for sub_tt in self.trees() { . sub_tt.hash_stable(hcx, hasher); . } 168 ( 0.00%) } . } . . pub trait CreateTokenStream: sync::Send + sync::Sync { . fn create_token_stream(&self) -> AttrAnnotatedTokenStream; . } . . impl CreateTokenStream for AttrAnnotatedTokenStream { . fn create_token_stream(&self) -> AttrAnnotatedTokenStream { -- line 131 ---------------------------------------- -- line 188 ---------------------------------------- . Delimited(DelimSpan, DelimToken, AttrAnnotatedTokenStream), . /// Stores the attributes for an attribute target, . /// along with the tokens for that attribute target. . /// See `AttributesData` for more information . Attributes(AttributesData), . } . . impl AttrAnnotatedTokenStream { 28,360 ( 0.00%) pub fn new(tokens: Vec<(AttrAnnotatedTokenTree, Spacing)>) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream(Lrc::new(tokens)) 28,360 ( 0.00%) } . . /// Converts this `AttrAnnotatedTokenStream` to a plain `TokenStream . /// During conversion, `AttrAnnotatedTokenTree::Attributes` get 'flattened' . /// back to a `TokenStream` of the form `outer_attr attr_target`. . /// If there are inner attributes, they are inserted into the proper . /// place in the attribute target tokens. . pub fn to_tokenstream(&self) -> TokenStream { . let trees: Vec<_> = self -- line 206 ---------------------------------------- -- line 316 ---------------------------------------- . pub struct TokenStream(pub(crate) Lrc>); . . pub type TreeAndSpacing = (TokenTree, Spacing); . . // `TokenStream` 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!(TokenStream, 8); . 115,299 ( 0.00%) #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable)] . pub enum Spacing { . Alone, . Joint, . } . . impl TokenStream { . /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream` . /// separating the two arguments with a comma for diagnostic suggestions. -- line 332 ---------------------------------------- -- line 371 ---------------------------------------- . impl From<(AttrAnnotatedTokenTree, Spacing)> for AttrAnnotatedTokenStream { . fn from((tree, spacing): (AttrAnnotatedTokenTree, Spacing)) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream::new(vec![(tree, spacing)]) . } . } . . impl From for TokenStream { . fn from(tree: TokenTree) -> TokenStream { 130 ( 0.00%) TokenStream::new(vec![(tree, Spacing::Alone)]) . } . } . . impl From for TreeAndSpacing { . fn from(tree: TokenTree) -> TreeAndSpacing { 42,797 ( 0.00%) (tree, Spacing::Alone) . } . } . . impl iter::FromIterator for TokenStream { . fn from_iter>(iter: I) -> Self { . TokenStream::new(iter.into_iter().map(Into::into).collect::>()) . } . } -- line 393 ---------------------------------------- -- line 401 ---------------------------------------- . } . . impl TokenStream { . pub fn new(streams: Vec) -> TokenStream { . TokenStream(Lrc::new(streams)) . } . . pub fn is_empty(&self) -> bool { 14,167 ( 0.00%) self.0.is_empty() 14,167 ( 0.00%) } . . pub fn len(&self) -> usize { 141,617 ( 0.01%) self.0.len() 4 ( 0.00%) } . . pub fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream { . match streams.len() { . 0 => TokenStream::default(), . 1 => streams.pop().unwrap(), . _ => { . // We are going to extend the first stream in `streams` with . // the elements from the subsequent streams. This requires -- line 422 ---------------------------------------- -- line 448 ---------------------------------------- . . // Create the final `TokenStream`. . TokenStream(first_stream_lrc) . } . } . } . . pub fn trees(&self) -> Cursor { 114 ( 0.00%) self.clone().into_trees() 228 ( 0.00%) } . 14,306 ( 0.00%) pub fn into_trees(self) -> Cursor { . Cursor::new(self) 28,612 ( 0.00%) } . . /// Compares two `TokenStream`s, checking equality without regarding span information. . pub fn eq_unspanned(&self, other: &TokenStream) -> bool { . let mut t1 = self.trees(); . let mut t2 = other.trees(); . for (t1, t2) in iter::zip(&mut t1, &mut t2) { . if !t1.eq_unspanned(&t2) { . return false; . } . } . t1.next().is_none() && t2.next().is_none() . } . . pub fn map_enumerated TokenTree>(self, mut f: F) -> TokenStream { 4 ( 0.00%) TokenStream(Lrc::new( . self.0 . .iter() . .enumerate() 60 ( 0.00%) .map(|(i, (tree, is_joint))| (f(i, tree), *is_joint)) . .collect(), . )) . } . } . . // 99.5%+ of the time we have 1 or 2 elements in this vector. . #[derive(Clone)] . pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>); -- line 488 ---------------------------------------- -- line 572 ---------------------------------------- . pub struct Cursor { . pub stream: TokenStream, . index: usize, . } . . impl Iterator for Cursor { . type Item = TokenTree; . 1,473 ( 0.00%) fn next(&mut self) -> Option { 3,798 ( 0.00%) self.next_with_spacing().map(|(tree, _)| tree) 1,964 ( 0.00%) } . } . . impl Cursor { . fn new(stream: TokenStream) -> Self { . Cursor { stream, index: 0 } . } . 705,590 ( 0.03%) pub fn next_with_spacing(&mut self) -> Option { 424,827 ( 0.02%) if self.index < self.stream.len() { 225,650 ( 0.01%) self.index += 1; 787,241 ( 0.03%) Some(self.stream.0[self.index - 1].clone()) . } else { 57,310 ( 0.00%) None . } 846,708 ( 0.03%) } . . pub fn index(&self) -> usize { . self.index . } . . pub fn append(&mut self, new_stream: TokenStream) { . if new_stream.is_empty() { . return; . } . let index = self.index; . let stream = mem::take(&mut self.stream); . *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees(); . self.index = index; . } . 178,810 ( 0.01%) pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> { 357,620 ( 0.01%) self.stream.0[self.index..].get(n).map(|(tree, _)| tree) 357,620 ( 0.01%) } . } . 30,821 ( 0.00%) #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub struct DelimSpan { . pub open: Span, . pub close: Span, . } . . impl DelimSpan { 1 ( 0.00%) pub fn from_single(sp: Span) -> Self { . DelimSpan { open: sp, close: sp } 2 ( 0.00%) } . 28,334 ( 0.00%) pub fn from_pair(open: Span, close: Span) -> Self { . DelimSpan { open, close } 14,167 ( 0.00%) } . . pub fn dummy() -> Self { . Self::from_single(DUMMY_SP) 192 ( 0.00%) } . 304 ( 0.00%) pub fn entire(self) -> Span { . self.open.with_hi(self.close.hi()) 228 ( 0.00%) } . } 1,625 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/visitor.rs -------------------------------------------------------------------------------- Ir -- line 47 ---------------------------------------- . self.layout . } . . #[inline(always)] . fn to_op( . &self, . _ecx: &InterpCx<'mir, 'tcx, M>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { 16,102 ( 0.00%) Ok(*self) . } . . #[inline(always)] . fn from_mem_place(mplace: MPlaceTy<'tcx, M::PointerTag>) -> Self { 178,794 ( 0.01%) mplace.into() . } . . #[inline(always)] . fn project_downcast( . &self, . ecx: &InterpCx<'mir, 'tcx, M>, . variant: VariantIdx, . ) -> InterpResult<'tcx, Self> { 48,306 ( 0.00%) ecx.operand_downcast(self, variant) . } . . #[inline(always)] . fn project_field( . &self, . ecx: &InterpCx<'mir, 'tcx, M>, . field: usize, . ) -> InterpResult<'tcx, Self> { 210,762 ( 0.01%) ecx.operand_field(self, field) . } . } . . impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> Value<'mir, 'tcx, M> . for MPlaceTy<'tcx, M::PointerTag> . { . #[inline(always)] . fn layout(&self) -> TyAndLayout<'tcx> { -- line 86 ---------------------------------------- -- line 87 ---------------------------------------- . self.layout . } . . #[inline(always)] . fn to_op( . &self, . _ecx: &InterpCx<'mir, 'tcx, M>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { 72,465 ( 0.00%) Ok((*self).into()) . } . . #[inline(always)] . fn from_mem_place(mplace: MPlaceTy<'tcx, M::PointerTag>) -> Self { . mplace . } . . #[inline(always)] -- line 103 ---------------------------------------- -- line 130 ---------------------------------------- . -> &$($mutability)? InterpCx<'mir, 'tcx, M>; . . /// `read_discriminant` can be hooked for better error messages. . #[inline(always)] . fn read_discriminant( . &mut self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, VariantIdx> { 8,051 ( 0.00%) Ok(self.ecx().read_discriminant(op)?.1) . } . . // Recursive actions, ready to be overloaded. . /// Visits the given value, dispatching as appropriate to more specialized visitors. . #[inline(always)] . fn visit_value(&mut self, v: &Self::V) -> InterpResult<'tcx> . { . self.walk_value(v) -- line 146 ---------------------------------------- -- line 170 ---------------------------------------- . /// we are descending through. . #[inline(always)] . fn visit_field( . &mut self, . _old_val: &Self::V, . _field: usize, . new_val: &Self::V, . ) -> InterpResult<'tcx> { 100,053 ( 0.00%) self.visit_value(new_val) . } . /// Called when recursing into an enum variant. . /// This gives the visitor the chance to track the stack of nested fields that . /// we are descending through. . #[inline(always)] . fn visit_variant( . &mut self, . _old_val: &Self::V, . _variant: VariantIdx, . new_val: &Self::V, . ) -> InterpResult<'tcx> { . self.visit_value(new_val) . } . . // Default recursors. Not meant to be overloaded. 190,510 ( 0.01%) fn walk_aggregate( . &mut self, . v: &Self::V, . fields: impl Iterator>, . ) -> InterpResult<'tcx> { . // Now iterate over it. 377,092 ( 0.01%) for (idx, field_val) in fields.enumerate() { 1,561,839 ( 0.06%) self.visit_field(v, idx, &field_val?)?; . } . Ok(()) 214,324 ( 0.01%) } 428,670 ( 0.02%) fn walk_value(&mut self, v: &Self::V) -> InterpResult<'tcx> . { . trace!("walk_value: type: {}", v.layout().ty); . . // Special treatment for special types, where the (static) layout is not sufficient. 349,886 ( 0.01%) match *v.layout().ty.kind() { . // If it is a trait object, switch to the real type that was used to create it. . ty::Dynamic(..) => { . // immediate trait objects are not a thing . let op = v.to_op(self.ecx())?; . let dest = op.assert_mem_place(); . let inner = self.ecx().unpack_dyn_trait(&dest)?.1; . trace!("walk_value: dyn object layout: {:#?}", inner.layout); . // recurse with the inner type -- line 218 ---------------------------------------- -- line 220 ---------------------------------------- . }, . // Slices do not need special handling here: they have `Array` field . // placement with length 0, so we enter the `Array` case below which . // indirectly uses the metadata to determine the actual length. . _ => {}, . }; . . // Visit the fields of this value. 445,144 ( 0.02%) match v.layout().fields { . FieldsShape::Primitive => {}, . FieldsShape::Union(fields) => { . self.visit_union(v, fields)?; . }, . FieldsShape::Arbitrary { ref offsets, .. } => { . // FIXME: We collect in a vec because otherwise there are lifetime . // errors: Projecting to a field needs access to `ecx`. . let fields: Vec> = 71,436 ( 0.00%) (0..offsets.len()).map(|i| { 105,381 ( 0.00%) v.project_field(self.ecx(), i) . }) . .collect(); . self.visit_aggregate(v, fields.into_iter())?; . }, . FieldsShape::Array { .. } => { . // Let's get an mplace first. 36 ( 0.00%) let op = v.to_op(self.ecx())?; . let mplace = op.assert_mem_place(); . // Now we can go over all the fields. . // This uses the *run-time length*, i.e., if we are a slice, . // the dynamic info from the metadata is used. 28 ( 0.00%) let iter = self.ecx().mplace_array_fields(&mplace)? . .map(|f| f.and_then(|f| { . Ok(Value::from_mem_place(f)) . })); . self.visit_aggregate(v, iter)?; . } . } . 302,256 ( 0.01%) match v.layout().variants { . // If this is a multi-variant layout, find the right variant and proceed . // with *its* fields. . Variants::Multiple { .. } => { 201,275 ( 0.01%) let op = v.to_op(self.ecx())?; 24,153 ( 0.00%) let idx = self.read_discriminant(&op)?; 64,408 ( 0.00%) let inner = v.project_downcast(self.ecx(), idx)?; . trace!("walk_value: variant layout: {:#?}", inner.layout()); . // recurse with the inner type . self.visit_variant(v, idx, &inner) . } . // For single-variant layouts, we already did anything there is to do. . Variants::Single { .. } => Ok(()) . } 428,670 ( 0.02%) } . } . } . } . . make_value_visitor!(ValueVisitor,); . make_value_visitor!(MutValueVisitor, mut); 178,689 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs -------------------------------------------------------------------------------- Ir -- line 82 ---------------------------------------- . /// promotion of temporaries must not change program behavior; if the promoted could be . /// written to, that would be a problem. . pub struct HasMutInterior; . . impl Qualif for HasMutInterior { . const ANALYSIS_NAME: &'static str = "flow_has_mut_interior"; . . fn in_qualifs(qualifs: &ConstQualifs) -> bool { 2 ( 0.00%) qualifs.has_mut_interior . } . . fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { 382,716 ( 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. . // It arises structurally for all other types. 208,220 ( 0.01%) Some(adt.did) == cx.tcx.lang_items().unsafe_cell_type() . } . } . . /// Constant containing an ADT that implements `Drop`. . /// This must be ruled out because implicit promotion would remove side-effects . /// that occur as part of dropping that value. N.B., the implicit promotion has . /// to reject const Drop implementations because even if side-effects are ruled . /// out through other means, the execution of the drop could diverge. -- line 112 ---------------------------------------- -- 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 . } . 170,088 ( 0.01%) fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { 42,522 ( 0.00%) ty.needs_drop(cx.tcx, cx.param_env) 191,349 ( 0.01%) } . . fn in_adt_inherently<'tcx>( . cx: &ConstCx<'_, 'tcx>, . adt: &'tcx AdtDef, . _: SubstsRef<'tcx>, . ) -> bool { 41,658 ( 0.00%) adt.has_dtor(cx.tcx) . } . } . . /// Constant containing an ADT that implements non-const `Drop`. . /// This must be ruled out because we cannot run `Drop` during compile-time. . pub struct NeedsNonConstDrop; . . impl Qualif for NeedsNonConstDrop { -- line 140 ---------------------------------------- -- 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 . } . 117 ( 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. 52 ( 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() . }) 117 ( 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`). 39 ( 0.00%) traits::search_for_structural_match_violation(cx.body.span, cx.tcx, ty).is_some() . } . 194,306 ( 0.01%) fn in_adt_inherently<'tcx>( . cx: &ConstCx<'_, 'tcx>, . adt: &'tcx AdtDef, . substs: SubstsRef<'tcx>, . ) -> bool { 27,758 ( 0.00%) let ty = cx.tcx.mk_ty(ty::Adt(adt, substs)); . !ty.is_structural_eq_shallow(cx.tcx) 222,064 ( 0.01%) } . } . . // FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return. . . /// Returns `true` if this `Rvalue` contains qualif `Q`. 908,630 ( 0.04%) 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, . { 454,315 ( 0.02%) 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()) . } . . Rvalue::Use(operand) . | Rvalue::Repeat(operand, _) . | Rvalue::UnaryOp(_, operand) . | Rvalue::Cast(_, operand, _) 153 ( 0.00%) | 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) . } . 12 ( 0.00%) Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => { . // Special-case reborrows to be more like a copy of the reference. 4 ( 0.00%) if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() { 2 ( 0.00%) let base_ty = place_base.ty(cx.body, cx.tcx).ty; 4 ( 0.00%) if let ty::Ref(..) = base_ty.kind() { 10 ( 0.00%) return in_place::(cx, in_local, place_base); . } . } . 20 ( 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. 494,570 ( 0.02%) if let AggregateKind::Adt(adt_did, _, substs, ..) = **kind { 83,288 ( 0.00%) let def = cx.tcx.adt_def(adt_did); 263,722 ( 0.01%) if Q::in_adt_inherently(cx, def, substs) { . return true; . } 55,530 ( 0.00%) if def.is_union() && Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)) { . return true; . } . } . . // Otherwise, proceed structurally... 666,170 ( 0.03%) operands.iter().any(|o| in_operand::(cx, in_local, o)) . } . } 770,154 ( 0.03%) } . . /// Returns `true` if this `Place` contains qualif `Q`. 788,154 ( 0.03%) 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, . { 18 ( 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()); 10 ( 0.00%) in_local(place.local) 64 ( 0.00%) } . . /// Returns `true` if this `Operand` contains qualif `Q`. 1,295,612 ( 0.05%) 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, . { 296,138 ( 0.01%) let constant = match operand { . Operand::Copy(place) | Operand::Move(place) => { 472,870 ( 0.02%) return in_place::(cx, in_local, place.as_ref()); . } . . Operand::Constant(c) => c, . }; . . // Check the qualifs of the value of `const` items. 425,105 ( 0.02%) if let Some(ct) = constant.literal.const_for_ty() { 170,042 ( 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. 2 ( 0.00%) assert!(promoted.is_none() || Q::ALLOW_PROMOTED); . // Don't peek inside trait associated constants. 2 ( 0.00%) if promoted.is_none() && cx.tcx.trait_of_item(def.did).is_none() { 20 ( 0.00%) 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)) . } else { . cx.tcx.at(constant.span).mir_const_qualif(def.did) . }; . 2 ( 0.00%) if !Q::in_qualifs(&qualifs) { . return false; . } . . // 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. 233,782 ( 0.01%) Q::in_any_value_of_ty(cx, constant.literal.ty()) 1,011,149 ( 0.04%) } 117,061 ( 0.00%) -------------------------------------------------------------------------------- -- 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) { 76 ( 0.00%) let mut tt_reader = TokenTreesReader { . string_reader: self, 4 ( 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(), . }; 4 ( 0.00%) let res = tt_reader.parse_all_token_trees(); 24 ( 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`. 32 ( 0.00%) fn parse_all_token_trees(&mut self) -> PResult<'a, TokenStream> { . let mut buf = TokenStreamBuilder::default(); . . self.bump(); 1,148 ( 0.00%) while self.token != token::Eof { 4,560 ( 0.00%) buf.push(self.parse_token_tree()?); . } . . Ok(buf.into_token_stream()) 36 ( 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 { 251,082 ( 0.01%) if let token::CloseDelim(..) = self.token.kind { . return buf.into_token_stream(); . } . 556,870 ( 0.02%) match self.parse_token_tree() { 1,002,366 ( 0.04%) Ok(tree) => buf.push(tree), . Err(mut e) => { . e.emit(); . return buf.into_token_stream(); . } . } . } . } . 1,007,496 ( 0.04%) fn parse_token_tree(&mut self) -> PResult<'a, TreeAndSpacing> { 223,888 ( 0.01%) let sm = self.string_reader.sess.source_map(); . 950,828 ( 0.04%) 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) . } 14,167 ( 0.00%) token::OpenDelim(delim) => { . // The span for beginning of the delimited section 14,167 ( 0.00%) let pre_span = self.token.span; . . // Parse the open delimiter. 99,169 ( 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. 14,167 ( 0.00%) let tts = self.parse_token_trees_until_close_delim(); . . // Expand to cover the entire delimited token tree 70,835 ( 0.00%) let delim_span = DelimSpan::from_pair(pre_span, self.token.span); . 28,334 ( 0.00%) match self.token.kind { . // Correct delimiter. 28,334 ( 0.00%) token::CloseDelim(d) if d == delim => { . let (open_brace, open_brace_span) = self.open_braces.pop().unwrap(); 28,334 ( 0.00%) let close_brace_span = self.token.span; . 42,501 ( 0.00%) if tts.is_empty() { 348 ( 0.00%) let empty_block_span = open_brace_span.to(close_brace_span); 464 ( 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 56,668 ( 0.00%) if let (DelimToken::Brace, DelimToken::Brace) = (open_brace, delim) { . self.matching_block_spans.push((open_brace_span, close_brace_span)); . } . 14,167 ( 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. . } . _ => {} . } . 99,169 ( 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) . } . _ => { 488,885 ( 0.02%) let tt = TokenTree::Token(self.token.take()); . let mut spacing = self.bump(); 195,554 ( 0.01%) if !self.token.is_op() { . spacing = Alone; . } 586,662 ( 0.02%) Ok((tt, spacing)) . } . } 895,552 ( 0.04%) } . . fn bump(&mut self) -> Spacing { 1,064,188 ( 0.04%) let (spacing, token) = self.string_reader.next_token(); 559,756 ( 0.02%) self.token = token; . spacing . } . } . 14,167 ( 0.00%) #[derive(Default)] . struct TokenStreamBuilder { . buf: Vec, . } . . impl TokenStreamBuilder { 1,455,272 ( 0.06%) fn push(&mut self, (tree, joint): TreeAndSpacing) { 722,485 ( 0.03%) if let Some((TokenTree::Token(prev_token), Joint)) = self.buf.last() { 68,748 ( 0.00%) if let TokenTree::Token(token) = &tree { 104,282 ( 0.00%) if let Some(glued) = prev_token.glue(token) { . self.buf.pop(); 3,480 ( 0.00%) self.buf.push((TokenTree::Token(glued), joint)); . return; . } . } . } 558,270 ( 0.02%) self.buf.push((tree, joint)) 895,552 ( 0.04%) } . . fn into_token_stream(self) -> TokenStream { 141,706 ( 0.01%) TokenStream::new(self.buf) . } . } 393,029 ( 0.02%) -------------------------------------------------------------------------------- -- 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 { 160 ( 0.00%) fn clone(&self) -> Self { 230 ( 0.00%) HashMap { . hash_builder: self.hash_builder.clone(), 35 ( 0.00%) table: self.table.clone(), . } 180 ( 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, . { 232,178 ( 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, . { 945,519 ( 0.04%) 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, . { 432,132 ( 0.02%) 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 { 559,173 ( 0.02%) 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 { 187 ( 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 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 { 8,075 ( 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 { 156,199 ( 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)] 300 ( 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)) { 35 ( 0.00%) Entry::Occupied(OccupiedEntry { . hash, . key: Some(key), . elem, . table: self, . }) . } else { 340 ( 0.00%) Entry::Vacant(VacantEntry { . hash, . key, . table: self, . }) . } 375 ( 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. 1,697,074 ( 0.07%) 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, . { 2,080,447 ( 0.08%) 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)] 409,414 ( 0.02%) pub fn contains_key(&self, k: &Q) -> bool . where . K: Borrow, . Q: Hash + Eq, . { . self.get_inner(k).is_some() 600,182 ( 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)] 117 ( 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. 351 ( 0.00%) match self.get_inner_mut(k) { . Some(&mut (_, ref mut v)) => Some(v), . None => None, . } 234 ( 0.00%) } . . #[inline] . fn get_inner_mut(&mut self, k: &Q) -> Option<&mut (K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 117 ( 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)] 4,216,527 ( 0.17%) pub fn insert(&mut self, k: K, v: V) -> Option { . let hash = make_insert_hash::(&self.hash_builder, &k); 47 ( 0.00%) if let Some((_, item)) = self.table.get_mut(hash, equivalent_key(&k)) { . Some(mem::replace(item, v)) . } else { 1,017,157 ( 0.04%) self.table 1,222,227 ( 0.05%) .insert(hash, (k, v), make_hasher::(&self.hash_builder)); 149,001 ( 0.01%) None . } 3,964,615 ( 0.16%) } . . /// 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)] 360,913 ( 0.01%) pub fn remove(&mut self, k: &Q) -> Option . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 585,099 ( 0.02%) match self.remove_entry(k) { 4,278 ( 0.00%) Some((_, v)) => Some(v), 170,489 ( 0.01%) None => None, . } 637,164 ( 0.03%) } . . /// 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); 211,706 ( 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, . { 1,438,888 ( 0.06%) 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)] 3,705,305 ( 0.15%) 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) 3,887,246 ( 0.15%) } . . #[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, . { 456,756 ( 0.02%) match self.map.table.find(hash, |(k, _)| is_match(k)) { 2,487,411 ( 0.10%) Some(elem) => RawEntryMut::Occupied(RawOccupiedEntryMut { . elem, . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), 129,044 ( 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)] 2,092,849 ( 0.08%) pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)> . where . K: Borrow, . Q: Eq, . { 2,418,814 ( 0.10%) self.from_hash(hash, equivalent(k)) 3,823,334 ( 0.15%) } . . #[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, . { 3,620,401 ( 0.14%) 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, . { 207,654 ( 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)] 195 ( 0.00%) fn into_iter(self) -> IntoIter { 5,179 ( 0.00%) IntoIter { 3,537 ( 0.00%) inner: self.table.into_iter(), . } 585 ( 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. 244,522 ( 0.01%) match self.inner.next() { . Some(x) => unsafe { . let r = x.as_ref(); 155 ( 0.00%) Some((&r.0, &r.1)) . }, . None => None, . } . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { 6 ( 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)> { 250 ( 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)] 39 ( 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, . } 78 ( 0.00%) } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . } . impl ExactSizeIterator for Keys<'_, K, V> { . #[cfg_attr(feature = "inline-more", inline)] . fn len(&self) -> usize { -- line 3098 ---------------------------------------- -- line 3819 ---------------------------------------- . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn insert(self, value: V) -> &'a mut V . where . K: Hash, . S: BuildHasher, . { . let table = &mut self.table.table; 18 ( 0.00%) let entry = table.insert_entry( . self.hash, . (self.key, value), . make_hasher::(&self.table.hash_builder), . ); . &mut entry.1 . } . . #[cfg_attr(feature = "inline-more", inline)] -- line 3835 ---------------------------------------- -- line 4557 ---------------------------------------- . /// keys with new values returned from the iterator. . impl Extend<(K, V)> for HashMap . where . K: Eq + Hash, . S: BuildHasher, . A: Allocator + Clone, . { . #[cfg_attr(feature = "inline-more", inline)] 56,740 ( 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. 14,903 ( 0.00%) let iter = iter.into_iter(); 45,078 ( 0.00%) let reserve = if self.is_empty() { . iter.size_hint().0 . } else { 127 ( 0.00%) (iter.size_hint().0 + 1) / 2 . }; . self.reserve(reserve); . iter.for_each(move |(k, v)| { 383,752 ( 0.02%) self.insert(k, v); . }); 49,479 ( 0.00%) } . . #[inline] . #[cfg(feature = "nightly")] . fn extend_one(&mut self, (k, v): (K, V)) { . self.insert(k, v); . } . . #[inline] -- line 4588 ---------------------------------------- 2,254,739 ( 0.09%) -------------------------------------------------------------------------------- -- 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 { 540,842 ( 0.02%) 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 { 83,586 ( 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 { 145,695 ( 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 { 28,589,547 ( 1.13%) 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_target/src/abi/mod.rs -------------------------------------------------------------------------------- Ir -- line 40 ---------------------------------------- . /// Minimum size of #[repr(C)] enums (default I32 bits) . pub c_enum_min_size: Integer, . } . . impl Default for TargetDataLayout { . /// Creates an instance of `TargetDataLayout`. . fn default() -> TargetDataLayout { . let align = |bits| Align::from_bits(bits).unwrap(); 24 ( 0.00%) TargetDataLayout { . endian: Endian::Big, . i1_align: AbiAndPrefAlign::new(align(8)), . i8_align: AbiAndPrefAlign::new(align(8)), . i16_align: AbiAndPrefAlign::new(align(16)), . i32_align: AbiAndPrefAlign::new(align(32)), . i64_align: AbiAndPrefAlign { abi: align(32), pref: align(64) }, . i128_align: AbiAndPrefAlign { abi: align(32), pref: align(64) }, . f32_align: AbiAndPrefAlign::new(align(32)), . f64_align: AbiAndPrefAlign::new(align(64)), . pointer_size: Size::from_bits(64), . pointer_align: AbiAndPrefAlign::new(align(64)), . aggregate_align: AbiAndPrefAlign { abi: align(0), pref: align(64) }, 8 ( 0.00%) vector_align: vec![ . (Size::from_bits(64), AbiAndPrefAlign::new(align(64))), . (Size::from_bits(128), AbiAndPrefAlign::new(align(128))), . ], . instruction_address_space: AddressSpace::DATA, . c_enum_min_size: Integer::I32, . } . } . } . . impl TargetDataLayout { 18 ( 0.00%) pub fn parse(target: &Target) -> Result { . // Parse an address space index from a string. . let parse_address_space = |s: &str, cause: &str| { . s.parse::().map(AddressSpace).map_err(|err| { . format!("invalid address space `{}` for `{}` in \"data-layout\": {}", s, cause, err) . }) . }; . . // Parse a bit count from a string. -- line 80 ---------------------------------------- -- line 83 ---------------------------------------- . format!("invalid {} `{}` for `{}` in \"data-layout\": {}", kind, s, cause, err) . }) . }; . . // Parse a size string. . let size = |s: &str, cause: &str| parse_bits(s, "size", cause).map(Size::from_bits); . . // Parse an alignment string. 20 ( 0.00%) let align = |s: &[&str], cause: &str| { 2 ( 0.00%) if s.is_empty() { . return Err(format!("missing alignment for `{}` in \"data-layout\"", cause)); . } 12 ( 0.00%) let align_from_bits = |bits| { . Align::from_bits(bits).map_err(|err| { . format!("invalid alignment for `{}` in \"data-layout\": {}", cause, err) . }) 16 ( 0.00%) }; 18 ( 0.00%) let abi = parse_bits(s[0], "alignment", cause)?; . let pref = s.get(1).map_or(Ok(abi), |pref| parse_bits(pref, "alignment", cause))?; 14 ( 0.00%) Ok(AbiAndPrefAlign { abi: align_from_bits(abi)?, pref: align_from_bits(pref)? }) 16 ( 0.00%) }; . . let mut dl = TargetDataLayout::default(); . let mut i128_align_src = 64; 32 ( 0.00%) for spec in target.data_layout.split('-') { . let spec_parts = spec.split(':').collect::>(); . . match &*spec_parts { 78 ( 0.00%) ["e"] => dl.endian = Endian::Little, . ["E"] => dl.endian = Endian::Big, 2 ( 0.00%) [p] if p.starts_with('P') => { . dl.instruction_address_space = parse_address_space(&p[1..], "P")? . } 44 ( 0.00%) ["a", ref a @ ..] => dl.aggregate_align = align(a, "a")?, 4 ( 0.00%) ["f32", ref a @ ..] => dl.f32_align = align(a, "f32")?, 4 ( 0.00%) ["f64", ref a @ ..] => dl.f64_align = align(a, "f64")?, 44 ( 0.00%) [p @ "p", s, ref a @ ..] | [p @ "p0", s, ref a @ ..] => { . dl.pointer_size = size(s, p)?; . dl.pointer_align = align(a, p)?; . } 64 ( 0.00%) [s, ref a @ ..] if s.starts_with('i') => { 4 ( 0.00%) let bits = match s[1..].parse::() { . Ok(bits) => bits, . Err(_) => { . size(&s[1..], "i")?; // For the user error. . continue; . } . }; 14 ( 0.00%) let a = align(a, s)?; 10 ( 0.00%) match bits { . 1 => dl.i1_align = a, . 8 => dl.i8_align = a, . 16 => dl.i16_align = a, . 32 => dl.i32_align = a, 6 ( 0.00%) 64 => dl.i64_align = a, . _ => {} . } 8 ( 0.00%) if bits >= i128_align_src && bits <= 128 { . // Default alignment for i128 is decided by taking the alignment of . // largest-sized i{64..=128}. . i128_align_src = bits; 8 ( 0.00%) dl.i128_align = a; . } . } 14 ( 0.00%) [s, ref a @ ..] if s.starts_with('v') => { . let v_size = size(&s[1..], "v")?; . let a = align(a, s)?; . if let Some(v) = dl.vector_align.iter_mut().find(|v| v.0 == v_size) { . v.1 = a; . continue; . } . // No existing entry, add a new one. . dl.vector_align.push((v_size, a)); . } . _ => {} // Ignore everything else. . } . } . . // Perform consistency checks against the Target information. 8 ( 0.00%) if dl.endian != target.endian { . return Err(format!( . "inconsistent target specification: \"data-layout\" claims \ . architecture is {}-endian, while \"target-endian\" is `{}`", . dl.endian.as_str(), . target.endian.as_str(), . )); . } . 10 ( 0.00%) if dl.pointer_size.bits() != target.pointer_width.into() { . return Err(format!( . "inconsistent target specification: \"data-layout\" claims \ . pointers are {}-bit, while \"target-pointer-width\" is `{}`", . dl.pointer_size.bits(), . target.pointer_width . )); . } . 4 ( 0.00%) dl.c_enum_min_size = Integer::from_size(Size::from_bits(target.c_enum_min_bits))?; . 34 ( 0.00%) Ok(dl) 18 ( 0.00%) } . . /// Returns exclusive upper bound on object size. . /// . /// The theoretical maximum object size is defined as the maximum positive `isize` value. . /// This ensures that the `offset` semantics remain well-defined by allowing it to correctly . /// index every address within an object along with one byte past the end, along with allowing . /// `isize` to store the difference between any two pointers into an object. . /// . /// The upper bound on 64-bit currently needs to be lower because LLVM uses a 64-bit integer . /// to represent object size in bits. It would need to be 1 << 61 to account for this, but is . /// currently conservatively bounded to 1 << 47 as that is enough to cover the current usable . /// address space on 64-bit ARMv8 and x86_64. . #[inline] . pub fn obj_size_bound(&self) -> u64 { 945,174 ( 0.04%) match self.pointer_size.bits() { . 16 => 1 << 15, . 32 => 1 << 31, . 64 => 1 << 47, . bits => panic!("obj_size_bound: unknown pointer bit size {}", bits), . } 2 ( 0.00%) } . . #[inline] . pub fn ptr_sized_integer(&self) -> Integer { 1,122 ( 0.00%) match self.pointer_size.bits() { . 16 => I16, . 32 => I32, . 64 => I64, . bits => panic!("ptr_sized_integer: unknown pointer bit size {}", bits), . } 6 ( 0.00%) } . . #[inline] . pub fn vector_align(&self, vec_size: Size) -> AbiAndPrefAlign { . for &(size, align) in &self.vector_align { . if size == vec_size { . return align; . } . } -- line 222 ---------------------------------------- -- line 233 ---------------------------------------- . impl HasDataLayout for TargetDataLayout { . #[inline] . fn data_layout(&self) -> &TargetDataLayout { . self . } . } . . /// Endianness of the target, which must match cfg(target-endian). 2 ( 0.00%) #[derive(Copy, Clone, PartialEq)] . pub enum Endian { . Little, . Big, . } . . impl Endian { . pub fn as_str(&self) -> &'static str { 3 ( 0.00%) match self { . Self::Little => "little", . Self::Big => "big", . } 1 ( 0.00%) } . } . . impl fmt::Debug for Endian { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . f.write_str(self.as_str()) . } . } . -- line 261 ---------------------------------------- -- line 277 ---------------------------------------- . } . } . . /// Size of a type in bytes. . #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encodable, Decodable)] . #[derive(HashStable_Generic)] . pub struct Size { . // The top 3 bits are ALWAYS zero. 422,826 ( 0.02%) raw: u64, . } . . impl Size { . pub const ZERO: Size = Size { raw: 0 }; . . /// Rounds `bits` up to the next-higher byte boundary, if `bits` is . /// is not aligned. . pub fn from_bits(bits: impl TryInto) -> Size { -- line 293 ---------------------------------------- -- line 296 ---------------------------------------- . #[cold] . fn overflow(bits: u64) -> ! { . panic!("Size::from_bits({}) has overflowed", bits); . } . . // This is the largest value of `bits` that does not cause overflow . // during rounding, and guarantees that the resulting number of bytes . // cannot cause overflow when multiplied by 8. 12 ( 0.00%) if bits > 0xffff_ffff_ffff_fff8 { . overflow(bits); . } . . // Avoid potential overflow from `bits + 7`. 26 ( 0.00%) Size { raw: bits / 8 + ((bits % 8) + 7) / 8 } . } . . #[inline] . pub fn from_bytes(bytes: impl TryInto) -> Size { . let bytes: u64 = bytes.try_into().ok().unwrap(); . Size { raw: bytes } . } . -- line 317 ---------------------------------------- -- line 322 ---------------------------------------- . . #[inline] . pub fn bytes_usize(self) -> usize { . self.bytes().try_into().unwrap() . } . . #[inline] . pub fn bits(self) -> u64 { 744,183 ( 0.03%) self.raw << 3 . } . . #[inline] . pub fn bits_usize(self) -> usize { . self.bits().try_into().unwrap() . } . . #[inline] 2 ( 0.00%) pub fn align_to(self, align: Align) -> Size { 11,592 ( 0.00%) let mask = align.bytes() - 1; 9,744 ( 0.00%) Size::from_bytes((self.bytes() + mask) & !mask) 6 ( 0.00%) } . . #[inline] . pub fn is_aligned(self, align: Align) -> bool { . let mask = align.bytes() - 1; . self.bytes() & mask == 0 . } . . #[inline] . pub fn checked_add(self, offset: Size, cx: &C) -> Option { . let dl = cx.data_layout(); . 157,521 ( 0.01%) let bytes = self.bytes().checked_add(offset.bytes())?; . 787,551 ( 0.03%) if bytes < dl.obj_size_bound() { Some(Size::from_bytes(bytes)) } else { None } . } . . #[inline] 4 ( 0.00%) pub fn checked_mul(self, count: u64, cx: &C) -> Option { . let dl = cx.data_layout(); . 6 ( 0.00%) let bytes = self.bytes().checked_mul(count)?; 18 ( 0.00%) if bytes < dl.obj_size_bound() { Some(Size::from_bytes(bytes)) } else { None } 2 ( 0.00%) } . . /// Truncates `value` to `self` bits and then sign-extends it to 128 bits . /// (i.e., if it is negative, fill with 1's on the left). . #[inline] . pub fn sign_extend(self, value: u128) -> u128 { . let size = self.bits(); . if size == 0 { . // Truncated until nothing is left. . return 0; . } . // Sign-extend it. 358 ( 0.00%) let shift = 128 - size; . // Shift the unsigned value to the left, then shift back to the right as signed . // (essentially fills with sign bit on the left). 12,172 ( 0.00%) (((value << shift) as i128) >> shift) as u128 . } . . /// Truncates `value` to `self` bits. . #[inline] . pub fn truncate(self, value: u128) -> u128 { . let size = self.bits(); 266,244 ( 0.01%) if size == 0 { . // Truncated until nothing is left. . return 0; . } 258,195 ( 0.01%) let shift = 128 - size; . // Truncate (shift left to drop out leftover values, shift right to fill with zeroes). 3,015,859 ( 0.12%) (value << shift) >> shift . } . . #[inline] . pub fn signed_int_min(&self) -> i128 { 3,222 ( 0.00%) self.sign_extend(1_u128 << (self.bits() - 1)) as i128 . } . . #[inline] . pub fn signed_int_max(&self) -> i128 { 3,222 ( 0.00%) i128::MAX >> (128 - self.bits()) . } . . #[inline] 2 ( 0.00%) pub fn unsigned_int_max(&self) -> u128 { 667,901 ( 0.03%) u128::MAX >> (128 - self.bits()) 4 ( 0.00%) } . } . . // Panicking addition, subtraction and multiplication for convenience. . // Avoid during layout computation, return `LayoutError` instead. . . impl Add for Size { . type Output = Size; . #[inline] -- line 417 ---------------------------------------- -- line 438 ---------------------------------------- . fn mul(self, size: Size) -> Size { . size * self . } . } . . impl Mul for Size { . type Output = Size; . #[inline] 55,516 ( 0.00%) fn mul(self, count: u64) -> Size { 93,025 ( 0.00%) match self.bytes().checked_mul(count) { . Some(bytes) => Size::from_bytes(bytes), . None => panic!("Size::mul: {} * {} doesn't fit in u64", self.bytes(), count), . } 55,516 ( 0.00%) } . } . . impl AddAssign for Size { . #[inline] . fn add_assign(&mut self, other: Size) { 15,809 ( 0.00%) *self = *self + other; . } . } . . impl Step for Size { . #[inline] . fn steps_between(start: &Self, end: &Self) -> Option { . u64::steps_between(&start.bytes(), &end.bytes()) . } -- line 465 ---------------------------------------- -- line 494 ---------------------------------------- . Self::from_bytes(u64::backward_unchecked(start.bytes(), count)) . } . } . . /// Alignment of a type in bytes (always a power of two). . #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encodable, Decodable)] . #[derive(HashStable_Generic)] . pub struct Align { 56,757 ( 0.00%) pow2: u8, . } . . impl Align { . pub const ONE: Align = Align { pow2: 0 }; . . #[inline] . pub fn from_bits(bits: u64) -> Result { . Align::from_bytes(Size::from_bits(bits).bytes()) . } . . #[inline] . pub fn from_bytes(align: u64) -> Result { . // Treat an alignment of 0 bytes like 1-byte alignment. 8 ( 0.00%) if align == 0 { . return Ok(Align::ONE); . } . . #[cold] . fn not_power_of_2(align: u64) -> String { . format!("`{}` is not a power of 2", align) . } . . #[cold] . fn too_large(align: u64) -> String { . format!("`{}` is too large", align) . } . . let mut bytes = align; . let mut pow2: u8 = 0; 56 ( 0.00%) while (bytes & 1) == 0 { 36 ( 0.00%) pow2 += 1; 24 ( 0.00%) bytes >>= 1; . } 8 ( 0.00%) if bytes != 1 { . return Err(not_power_of_2(align)); . } 8 ( 0.00%) if pow2 > 29 { . return Err(too_large(align)); . } . 4 ( 0.00%) Ok(Align { pow2 }) . } . . #[inline] . pub fn bytes(self) -> u64 { 4,058 ( 0.00%) 1 << self.pow2 . } . . #[inline] . pub fn bits(self) -> u64 { 10 ( 0.00%) self.bytes() * 8 . } . . /// Computes the best alignment possible for the given offset . /// (the largest power of two that the offset is a multiple of). . /// . /// N.B., for an offset of `0`, this happens to return `2^64`. . #[inline] . pub fn max_for_offset(offset: Size) -> Align { -- line 561 ---------------------------------------- -- line 591 ---------------------------------------- . . #[inline] . pub fn max(self, other: AbiAndPrefAlign) -> AbiAndPrefAlign { . AbiAndPrefAlign { abi: self.abi.max(other.abi), pref: self.pref.max(other.pref) } . } . } . . /// Integers, also used for enum discriminants. 112,735 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, HashStable_Generic)] . pub enum Integer { . I8, . I16, . I32, . I64, . I128, . } . . impl Integer { . #[inline] . pub fn size(self) -> Size { 632,470 ( 0.03%) match self { . I8 => Size::from_bytes(1), . I16 => Size::from_bytes(2), . I32 => Size::from_bytes(4), . I64 => Size::from_bytes(8), . I128 => Size::from_bytes(16), . } . } . . pub fn align(self, cx: &C) -> AbiAndPrefAlign { . let dl = cx.data_layout(); . 60 ( 0.00%) match self { 225,450 ( 0.01%) I8 => dl.i8_align, 11,304 ( 0.00%) I16 => dl.i16_align, 24 ( 0.00%) I32 => dl.i32_align, 32 ( 0.00%) I64 => dl.i64_align, . I128 => dl.i128_align, . } . } . . /// Finds the smallest Integer type which can represent the signed value. . #[inline] . pub fn fit_signed(x: i128) -> Integer { . match x { 28 ( 0.00%) -0x0000_0000_0000_0080..=0x0000_0000_0000_007f => I8, . -0x0000_0000_0000_8000..=0x0000_0000_0000_7fff => I16, . -0x0000_0000_8000_0000..=0x0000_0000_7fff_ffff => I32, . -0x8000_0000_0000_0000..=0x7fff_ffff_ffff_ffff => I64, . _ => I128, . } . } . . /// Finds the smallest Integer type which can represent the unsigned value. . #[inline] . pub fn fit_unsigned(x: u128) -> Integer { . match x { 8 ( 0.00%) 0..=0x0000_0000_0000_00ff => I8, . 0..=0x0000_0000_0000_ffff => I16, . 0..=0x0000_0000_ffff_ffff => I32, . 0..=0xffff_ffff_ffff_ffff => I64, . _ => I128, . } . } . . /// Finds the smallest integer with the given alignment. 12 ( 0.00%) pub fn for_align(cx: &C, wanted: Align) -> Option { . let dl = cx.data_layout(); . 84 ( 0.00%) for candidate in [I8, I16, I32, I64, I128] { 16 ( 0.00%) if wanted == candidate.align(dl).abi && wanted.bytes() == candidate.size().bytes() { . return Some(candidate); . } . } . None 12 ( 0.00%) } . . /// Find the largest integer with the given alignment or less. . pub fn approximate_align(cx: &C, wanted: Align) -> Integer { . let dl = cx.data_layout(); . . // FIXME(eddyb) maybe include I128 in the future, when it works everywhere. . for candidate in [I64, I32, I16] { . if wanted >= candidate.align(dl).abi && wanted.bytes() >= candidate.size().bytes() { -- line 674 ---------------------------------------- -- line 677 ---------------------------------------- . } . I8 . } . . // FIXME(eddyb) consolidate this and other methods that find the appropriate . // `Integer` given some requirements. . #[inline] . fn from_size(size: Size) -> Result { 8 ( 0.00%) match size.bits() { . 8 => Ok(Integer::I8), . 16 => Ok(Integer::I16), . 32 => Ok(Integer::I32), . 64 => Ok(Integer::I64), . 128 => Ok(Integer::I128), . _ => Err(format!("rust does not support integers with {} bits", size.bits())), . } . } . } . . /// Fundamental unit of memory access and layout. 1,917,166 ( 0.08%) #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub enum Primitive { . /// The `bool` is the signedness of the `Integer` type. . /// . /// One would think we would not care about such details this low down, . /// but some ABIs are described in terms of C types and ISAs where the . /// integer arithmetic is done on {sign,zero}-extended registers, e.g. . /// a negative integer passed by zero-extension will appear positive in . /// the callee, and most operations on it will produce the wrong values. 676,386 ( 0.03%) Int(Integer, bool), . F32, . F64, . Pointer, . } . . impl Primitive { . pub fn size(self, cx: &C) -> Size { . let dl = cx.data_layout(); . 792,103 ( 0.03%) match self { . Int(i, _) => i.size(), . F32 => Size::from_bits(32), . F64 => Size::from_bits(64), 54 ( 0.00%) Pointer => dl.pointer_size, . } 2 ( 0.00%) } . . pub fn align(self, cx: &C) -> AbiAndPrefAlign { . let dl = cx.data_layout(); . 120 ( 0.00%) match self { . Int(i, _) => i.align(dl), . F32 => dl.f32_align, . F64 => dl.f64_align, 8 ( 0.00%) Pointer => dl.pointer_align, . } . } . . // FIXME(eddyb) remove, it's trivial thanks to `matches!`. . #[inline] . pub fn is_float(self) -> bool { . matches!(self, F32 | F64) . } -- line 739 ---------------------------------------- -- line 753 ---------------------------------------- . /// sequence: . /// . /// 254 (-2), 255 (-1), 0, 1, 2 . /// . /// This is intended specifically to mirror LLVM’s `!range` metadata semantics. . #[derive(Clone, Copy, PartialEq, Eq, Hash)] . #[derive(HashStable_Generic)] . pub struct WrappingRange { 338,235 ( 0.01%) pub start: u128, . pub end: u128, . } . . impl WrappingRange { . /// Returns `true` if `v` is contained in the range. . #[inline(always)] . pub fn contains(&self, v: u128) -> bool { . if self.start <= self.end { -- line 769 ---------------------------------------- -- line 806 ---------------------------------------- . Ok(()) . } . } . . /// Information about one scalar component of a Rust type. . #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] . #[derive(HashStable_Generic)] . pub struct Scalar { 394,756 ( 0.02%) pub value: Primitive, . . // FIXME(eddyb) always use the shortest range, e.g., by finding . // the largest space between two consecutive valid values and . // taking everything else as the (shortest) valid range. 450,966 ( 0.02%) pub valid_range: WrappingRange, . } . . impl Scalar { . #[inline] . pub fn is_bool(&self) -> bool { . matches!( . self, . Scalar { value: Int(I8, false), valid_range: WrappingRange { start: 0, end: 1 } } -- line 827 ---------------------------------------- -- line 831 ---------------------------------------- . /// Returns `true` if all possible numbers are valid, i.e `valid_range` covers the whole layout . #[inline] . pub fn is_always_valid(&self, cx: &C) -> bool { . self.valid_range.is_full_for(self.value.size(cx)) . } . } . . /// Describes how the fields of a type are located in memory. 902,664 ( 0.04%) #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub enum FieldsShape { . /// Scalar primitives and `!`, which never have fields. . Primitive, . . /// All fields start at no offset. The `usize` is the field count. . Union(NonZeroUsize), . . /// Array/vector-like placement, with all fields of identical types. -- line 847 ---------------------------------------- -- line 875 ---------------------------------------- . // FIXME(camlorn) also consider small vector optimization here. . memory_index: Vec, . }, . } . . impl FieldsShape { . #[inline] . pub fn count(&self) -> usize { 80 ( 0.00%) match *self { . FieldsShape::Primitive => 0, . FieldsShape::Union(count) => count.get(), . FieldsShape::Array { count, .. } => count.try_into().unwrap(), 48 ( 0.00%) FieldsShape::Arbitrary { ref offsets, .. } => offsets.len(), . } . } . . #[inline] 278,938 ( 0.01%) pub fn offset(&self, i: usize) -> Size { 872,980 ( 0.03%) match *self { . FieldsShape::Primitive => { . unreachable!("FieldsShape::offset: `Primitive`s have no fields") . } . FieldsShape::Union(count) => { . assert!( . i < count.get(), . "tried to access field {} of union with {} fields", . i, . count . ); . Size::ZERO . } . FieldsShape::Array { stride, count } => { . let i = u64::try_from(i).unwrap(); 19,866 ( 0.00%) assert!(i < count); . stride * i . } 164,663 ( 0.01%) FieldsShape::Arbitrary { ref offsets, .. } => offsets[i], . } 278,938 ( 0.01%) } . . #[inline] . pub fn memory_index(&self, i: usize) -> usize { . match *self { . FieldsShape::Primitive => { . unreachable!("FieldsShape::memory_index: `Primitive`s have no fields") . } . FieldsShape::Union(_) | FieldsShape::Array { .. } => i, . FieldsShape::Arbitrary { ref memory_index, .. } => memory_index[i].try_into().unwrap(), . } . } . . /// Gets source indices of the fields by increasing offsets. . #[inline] . pub fn index_by_increasing_offset<'a>(&'a self) -> impl Iterator + 'a { 64 ( 0.00%) let mut inverse_small = [0u8; 64]; . let mut inverse_big = vec![]; 16 ( 0.00%) let use_small = self.count() <= inverse_small.len(); . . // We have to write this logic twice in order to keep the array small. . if let FieldsShape::Arbitrary { ref memory_index, .. } = *self { 16 ( 0.00%) if use_small { . for i in 0..self.count() { 36 ( 0.00%) inverse_small[memory_index[i] as usize] = i as u8; . } . } else { . inverse_big = vec![0; self.count()]; . for i in 0..self.count() { . inverse_big[memory_index[i] as usize] = i as u32; . } . } . } . 140 ( 0.00%) (0..self.count()).map(move |i| match *self { . FieldsShape::Primitive | FieldsShape::Union(_) | FieldsShape::Array { .. } => i, . FieldsShape::Arbitrary { .. } => { 6 ( 0.00%) if use_small { 18 ( 0.00%) inverse_small[i] as usize . } else { . inverse_big[i] as usize . } . } . }) . } . } . -- line 959 ---------------------------------------- -- line 965 ---------------------------------------- . . impl AddressSpace { . /// The default address space, corresponding to data space. . pub const DATA: Self = AddressSpace(0); . } . . /// Describes how values of the type are passed by target ABIs, . /// in terms of categories of C types there are ABI rules for. 564,170 ( 0.02%) #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub enum Abi { . Uninhabited, . Scalar(Scalar), 30 ( 0.00%) ScalarPair(Scalar, Scalar), . Vector { . element: Scalar, . count: u64, . }, . Aggregate { . /// If true, the size is exact, otherwise it's only a lower bound. 86 ( 0.00%) sized: bool, . }, . } . . impl Abi { . /// Returns `true` if the layout corresponds to an unsized type. . #[inline] . pub fn is_unsized(&self) -> bool { 496,671 ( 0.02%) match *self { . Abi::Uninhabited | Abi::Scalar(_) | Abi::ScalarPair(..) | Abi::Vector { .. } => false, . Abi::Aggregate { sized } => !sized, . } . } . . /// Returns `true` if this is a single signed integer scalar . #[inline] . pub fn is_signed(&self) -> bool { 144,920 ( 0.01%) match self { 338,146 ( 0.01%) Abi::Scalar(scal) => match scal.value { . Primitive::Int(_, signed) => signed, . _ => false, . }, . _ => panic!("`is_signed` on non-scalar ABI {:?}", self), . } . } . . /// Returns `true` if this is an uninhabited type . #[inline] . pub fn is_uninhabited(&self) -> bool { 8,094 ( 0.00%) matches!(*self, Abi::Uninhabited) . } . . /// Returns `true` is this is a scalar type . #[inline] . pub fn is_scalar(&self) -> bool { . matches!(*self, Abi::Scalar(_)) . } . } . . rustc_index::newtype_index! { . pub struct VariantIdx { . derive [HashStable_Generic] . } . } . 623,039 ( 0.02%) #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub enum Variants { . /// Single enum variants, structs/tuples, unions, and all non-ADTs. 94,412 ( 0.00%) Single { index: VariantIdx }, . . /// Enum-likes with more than one inhabited variant: each variant comes with . /// a *discriminant* (usually the same as the variant index but the user can . /// assign explicit discriminant values). That discriminant is encoded . /// as a *tag* on the machine. The layout of each variant is . /// a struct, and they all have space reserved for the tag. . /// For enums, the tag is the sole field of the layout. . Multiple { . tag: Scalar, 5 ( 0.00%) tag_encoding: TagEncoding, 4 ( 0.00%) tag_field: usize, 1 ( 0.00%) variants: IndexVec, . }, . } . 18 ( 0.00%) #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub enum TagEncoding { . /// The tag directly stores the discriminant, but possibly with a smaller layout . /// (so converting the tag to the discriminant can require sign extension). . Direct, . . /// Niche (values invalid for a type) encoding the discriminant: . /// Discriminant and variant index coincide. . /// The variant `dataful_variant` contains a niche at an arbitrary -- line 1056 ---------------------------------------- -- line 1065 ---------------------------------------- . dataful_variant: VariantIdx, . niche_variants: RangeInclusive, . niche_start: u128, . }, . } . . #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub struct Niche { 56,367 ( 0.00%) pub offset: Size, 56,367 ( 0.00%) pub scalar: Scalar, . } . . impl Niche { 12 ( 0.00%) pub fn from_scalar(cx: &C, offset: Size, scalar: Scalar) -> Option { 12 ( 0.00%) let niche = Niche { offset, scalar }; 902,118 ( 0.04%) if niche.available(cx) > 0 { Some(niche) } else { None } 14 ( 0.00%) } . . pub fn available(&self, cx: &C) -> u128 { . let Scalar { value, valid_range: v } = self.scalar; . let size = value.size(cx); 112,820 ( 0.00%) assert!(size.bits() <= 128); . let max_value = size.unsigned_int_max(); . . // Find out how many values are outside the valid range. . let niche = v.end.wrapping_add(1)..v.start; 98 ( 0.00%) niche.end.wrapping_sub(niche.start) & max_value . } . . pub fn reserve(&self, cx: &C, count: u128) -> Option<(u128, Scalar)> { . assert!(count > 0); . . let Scalar { value, valid_range: v } = self.scalar; . let size = value.size(cx); . assert!(size.bits() <= 128); -- line 1099 ---------------------------------------- -- line 1144 ---------------------------------------- . move_start(v) . } else { . move_end(v) . } . } . } . } . 790,594 ( 0.03%) #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub struct Layout { . /// Says where the fields are located within the layout. . pub fields: FieldsShape, . . /// Encodes information about multi-variant layouts. . /// Even with `Multiple` variants, a layout still has its own fields! Those are then . /// shared between all variants. One of them will be the discriminant, . /// but e.g. generators can have more. . /// . /// To access all fields of this layout, both `fields` and the fields of the active variant . /// must be taken into account. 16 ( 0.00%) pub variants: Variants, . . /// The `abi` defines how this data is passed between functions, and it defines . /// value restrictions via `valid_range`. . /// . /// Note that this is entirely orthogonal to the recursive structure defined by . /// `variants` and `fields`; for example, `ManuallyDrop>` has . /// `Abi::ScalarPair`! So, even with non-`Aggregate` `abi`, `fields` and `variants` . /// have to be taken into account to find all fields of this layout. 56,380 ( 0.00%) pub abi: Abi, . . /// The leaf scalar with the largest number of invalid values . /// (i.e. outside of its `valid_range`), if it exists. 281,875 ( 0.01%) pub largest_niche: Option, . 451,194 ( 0.02%) pub align: AbiAndPrefAlign, 225,524 ( 0.01%) pub size: Size, . } . . impl Layout { 338,244 ( 0.01%) pub fn scalar(cx: &C, scalar: Scalar) -> Self { 338,244 ( 0.01%) let largest_niche = Niche::from_scalar(cx, Size::ZERO, scalar); . let size = scalar.value.size(cx); . let align = scalar.value.align(cx); 1,183,854 ( 0.05%) Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, . fields: FieldsShape::Primitive, 338,244 ( 0.01%) abi: Abi::Scalar(scalar), 225,496 ( 0.01%) largest_niche, . size, . align, . } 450,992 ( 0.02%) } . } . . /// The layout of a type, alongside the type itself. . /// Provides various type traversal APIs (e.g., recursing into fields). . /// . /// Note that the layout is NOT guaranteed to always be identical . /// to that obtained from `layout_of(ty)`, as we need to produce . /// layouts for which Rust types do not exist, such as enum variants . /// or synthetic fields of enums (i.e., discriminants) and fat pointers. . #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable_Generic)] . pub struct TyAndLayout<'a, Ty> { 182,442 ( 0.01%) pub ty: Ty, 369,436 ( 0.01%) pub layout: &'a Layout, . } . . impl<'a, Ty> Deref for TyAndLayout<'a, Ty> { . type Target = &'a Layout; . fn deref(&self) -> &&'a Layout { 8 ( 0.00%) &self.layout . } . } . . #[derive(Copy, Clone, PartialEq, Eq, Debug)] . pub enum PointerKind { . /// Most general case, we know no restrictions to tell LLVM. . Shared, . -- line 1223 ---------------------------------------- -- line 1255 ---------------------------------------- . ) -> Option; . } . . impl<'a, Ty> TyAndLayout<'a, Ty> { . pub fn for_variant(self, cx: &C, variant_index: VariantIdx) -> Self . where . Ty: TyAbiInterface<'a, C>, . { 121,306 ( 0.00%) Ty::ty_and_layout_for_variant(self, cx, variant_index) . } . . pub fn field(self, cx: &C, i: usize) -> Self . where . Ty: TyAbiInterface<'a, C>, . { 722,595 ( 0.03%) Ty::ty_and_layout_field(self, cx, i) . } . . pub fn pointee_info_at(self, cx: &C, offset: Size) -> Option . where . Ty: TyAbiInterface<'a, C>, . { . Ty::ty_and_layout_pointee_info_at(self, cx, offset) . } . } . . impl<'a, Ty> TyAndLayout<'a, Ty> { . /// Returns `true` if the layout corresponds to an unsized type. . pub fn is_unsized(&self) -> bool { 60,862 ( 0.00%) self.abi.is_unsized() . } . . /// Returns `true` if the type is a ZST and not unsized. . pub fn is_zst(&self) -> bool { 360,550 ( 0.01%) match self.abi { . Abi::Scalar(_) | Abi::ScalarPair(..) | Abi::Vector { .. } => false, . Abi::Uninhabited => self.size.bytes() == 0, 71,654 ( 0.00%) Abi::Aggregate { sized } => sized && self.size.bytes() == 0, . } 4 ( 0.00%) } . . /// Determines if this type permits "raw" initialization by just transmuting some . /// memory into an instance of `T`. . /// `zero` indicates if the memory is zero-initialized, or alternatively . /// left entirely uninitialized. . /// This is conservative: in doubt, it will answer `true`. . /// . /// FIXME: Once we removed all the conservatism, we could alternatively -- line 1302 ---------------------------------------- 2,688,137 ( 0.11%) -------------------------------------------------------------------------------- -- 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}; . 125,865 ( 0.00%) 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); . } . } . } . }; . } . 2,197 ( 0.00%) #[derive(Clone)] . pub struct Parser<'a> { 55 ( 0.00%) pub sess: &'a ParseSess, . /// The current token. 34 ( 0.00%) pub token: Token, . /// The spacing for the current token 34 ( 0.00%) pub token_spacing: Spacing, . /// The previous token. 51 ( 0.00%) pub prev_token: Token, 51 ( 0.00%) pub capture_cfg: bool, 119 ( 0.00%) restrictions: Restrictions, 68 ( 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, 68 ( 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. 68 ( 0.00%) unmatched_angle_bracket_count: u32, 102 ( 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. 34 ( 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` 34 ( 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, . } . 140 ( 0.00%) #[derive(Clone)] . struct CaptureState { 136 ( 0.00%) capturing: Capturing, 34 ( 0.00%) replace_ranges: Vec, . inner_attr_ranges: FxHashMap, . } . . impl<'a> Drop for Parser<'a> { . fn drop(&mut self) { 257 ( 0.00%) emit_unclosed_delims(&mut self.unclosed_delims, &self.sess); . } . } . 9,413 ( 0.00%) #[derive(Clone)] . struct TokenCursor { . frame: TokenCursorFrame, 2,240 ( 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. 681 ( 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, . } . 4,325 ( 0.00%) #[derive(Clone)] . struct TokenCursorFrame { 1,820 ( 0.00%) delim: token::DelimToken, . span: DelimSpan, . open_delim: bool, 3,640 ( 0.00%) tree_cursor: tokenstream::Cursor, . close_delim: bool, . } . . impl TokenCursorFrame { . fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self { 200 ( 0.00%) TokenCursorFrame { . delim, . span, . open_delim: false, 14,331 ( 0.00%) tree_cursor: tts.into_trees(), . close_delim: false, . } . } . } . . impl TokenCursor { 1,518,612 ( 0.06%) fn next(&mut self) -> (Token, Spacing) { . loop { 732,450 ( 0.03%) let (tree, spacing) = if !self.frame.open_delim { 14,251 ( 0.00%) self.frame.open_delim = true; 71,255 ( 0.00%) TokenTree::open_tt(self.frame.span, self.frame.delim).into() 1,489,843 ( 0.06%) } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() { . tree 56,974 ( 0.00%) } else if !self.frame.close_delim { 14,220 ( 0.00%) self.frame.close_delim = true; 71,100 ( 0.00%) TokenTree::close_tt(self.frame.span, self.frame.delim).into() 28,440 ( 0.00%) } else if let Some(frame) = self.stack.pop() { 184,860 ( 0.01%) self.frame = frame; . continue; . } else { 846 ( 0.00%) (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone) . }; . 281,604 ( 0.01%) match tree { . TokenTree::Token(token) => { 1,012,408 ( 0.04%) return (token, spacing); . } . TokenTree::Delimited(sp, delim, tts) => { . let frame = TokenCursorFrame::new(sp, delim, tts); . self.stack.push(mem::replace(&mut self.frame, frame)); . } . } . } 1,012,408 ( 0.04%) } . 3,550 ( 0.00%) fn next_desugared(&mut self) -> (Token, Spacing) { 1,065 ( 0.00%) let (data, attr_style, sp) = match self.next() { . (Token { kind: token::DocComment(_, attr_style, data), span }, _) => { . (data, attr_style, span) . } 1,775 ( 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() 3,195 ( 0.00%) } . } . 2,160 ( 0.00%) #[derive(Debug, Clone, PartialEq)] . enum TokenType { 1,728 ( 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 { 33 ( 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> { 38 ( 0.00%) Some(match token.kind { 76 ( 0.00%) _ if token.is_special_ident() => "reserved identifier", 76 ( 0.00%) _ if token.is_used_keyword() => "keyword", 76 ( 0.00%) _ if token.is_unused_keyword() => "reserved keyword", . token::DocComment(..) => "doc comment", . _ => return None, . }) . } . 133 ( 0.00%) pub(super) fn token_descr(token: &Token) -> String { 38 ( 0.00%) let token_str = pprust::token_to_string(token); . match token_descr_opt(token) { . Some(prefix) => format!("{} `{}`", prefix, token_str), 133 ( 0.00%) _ => format!("`{}`", token_str), . } 95 ( 0.00%) } . . impl<'a> Parser<'a> { 560 ( 0.00%) pub fn new( . sess: &'a ParseSess, . tokens: TokenStream, . desugar_doc_comments: bool, . subparser_name: Option<&'static str>, . ) -> Self { 40 ( 0.00%) let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens); 80 ( 0.00%) start_frame.open_delim = true; . start_frame.close_delim = true; . 1,240 ( 0.00%) let mut parser = Parser { . sess, 40 ( 0.00%) token: Token::dummy(), . token_spacing: Spacing::Alone, 40 ( 0.00%) prev_token: Token::dummy(), . capture_cfg: false, . restrictions: Restrictions::empty(), . expected_tokens: Vec::new(), . token_cursor: TokenCursor { 240 ( 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. 80 ( 0.00%) parser.bump(); . . parser 360 ( 0.00%) } . . fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) { . loop { 758,148 ( 0.03%) let (mut next, spacing) = if self.desugar_doc_comments { 1,420 ( 0.00%) self.token_cursor.next_desugared() . } else { 378,009 ( 0.01%) self.token_cursor.next() . }; 505,432 ( 0.02%) 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 126,358 ( 0.00%) self.token_cursor.break_last_token = false; 505,432 ( 0.02%) if next.span.is_dummy() { . // Tweak the location for better diagnostics, but keep syntactic context intact. 172 ( 0.00%) next.span = fallback_span.with_ctxt(next.span.ctxt()); . } 421,734 ( 0.02%) if matches!( 252,716 ( 0.01%) next.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 505,432 ( 0.02%) 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`. 286,992 ( 0.01%) pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { 31,888 ( 0.00%) if self.expected_tokens.is_empty() { 396 ( 0.00%) if self.token == *t { 330 ( 0.00%) self.bump(); . Ok(false) . } else { . self.unexpected_try_recover(t) . } . } else { 381,864 ( 0.02%) self.expect_one_of(slice::from_ref(t), &[]) . } 478,320 ( 0.02%) } . . /// 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. 594,408 ( 0.02%) pub fn expect_one_of( . &mut self, . edible: &[TokenKind], . inedible: &[TokenKind], . ) -> PResult<'a, bool /* recovered */> { 99,068 ( 0.00%) if edible.contains(&self.token.kind) { 130,575 ( 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) . } 743,010 ( 0.03%) } . . // Public for rustfmt usage. . pub fn parse_ident(&mut self) -> PResult<'a, Ident> { 61,121 ( 0.00%) self.parse_ident_common(true) . } . . fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> { 98,430 ( 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(), . }) . } . 229,383 ( 0.01%) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { 32,769 ( 0.00%) let (ident, is_raw) = self.ident_or_err()?; 196,614 ( 0.01%) if !is_raw && ident.is_reserved() { . let mut err = self.expected_ident_found(); . if recover { . err.emit(); . } else { . return Err(err); . } . } 131,076 ( 0.01%) self.bump(); . Ok(ident) 327,690 ( 0.01%) } . . /// 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. 2,635,654 ( 0.10%) fn check(&mut self, tok: &TokenKind) -> bool { 1,142,304 ( 0.05%) let is_present = self.token == *tok; 777,546 ( 0.03%) if !is_present { 1,808,862 ( 0.07%) self.expected_tokens.push(TokenType::Token(tok.clone())); . } . is_present 2,635,654 ( 0.10%) } . . /// Consumes a token 'tok' if it exists. Returns whether the given token was present. 4 ( 0.00%) pub fn eat(&mut self, tok: &TokenKind) -> bool { 470,775 ( 0.02%) let is_present = self.check(tok); 324,685 ( 0.01%) if is_present { 18,828 ( 0.00%) self.bump() . } . is_present 5 ( 0.00%) } . . /// If the next token is the given keyword, returns `true` without eating it. . /// An expectation is also added for diagnostics purposes. 8,045 ( 0.00%) fn check_keyword(&mut self, kw: Symbol) -> bool { 1,224 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw)); 44,023 ( 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. 16,355 ( 0.00%) pub fn eat_keyword(&mut self, kw: Symbol) -> bool { 10,362 ( 0.00%) if self.check_keyword(kw) { 974 ( 0.00%) self.bump(); . true . } else { . false . } 16,355 ( 0.00%) } . . fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { 842 ( 0.00%) if self.token.is_keyword(kw) { 197 ( 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. 75 ( 0.00%) fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { . if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } 60 ( 0.00%) } . . /// Is the given keyword `kw` followed by a non-reserved identifier? 8,736 ( 0.00%) fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { 4,368 ( 0.00%) self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) 9,828 ( 0.00%) } . 91,686 ( 0.00%) fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { 31,106 ( 0.00%) if ok { . true . } else { 1,704 ( 0.00%) self.expected_tokens.push(typ); . false . } 91,686 ( 0.00%) } . . fn check_ident(&mut self) -> bool { 2,113 ( 0.00%) self.check_or_expected(self.token.is_ident(), TokenType::Ident) . } . 58,972 ( 0.00%) fn check_path(&mut self) -> bool { 119,000 ( 0.00%) self.check_or_expected(self.token.is_path_start(), TokenType::Path) 73,715 ( 0.00%) } . . fn check_type(&mut self) -> bool { 292 ( 0.00%) self.check_or_expected(self.token.can_begin_type(), TokenType::Type) . } . . fn check_const_arg(&mut self) -> bool { 280 ( 0.00%) self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) . } . 3,123 ( 0.00%) fn check_inline_const(&self, dist: usize) -> bool { 1,735 ( 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, . }) 3,123 ( 0.00%) } . . /// Checks to see if the next token is either `+` or `+=`. . /// Otherwise returns `false`. . fn check_plus(&mut self) -> bool { 604 ( 0.00%) self.check_or_expected( 302 ( 0.00%) self.token.is_like_plus(), 302 ( 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. 177,480 ( 0.01%) fn break_and_eat(&mut self, expected: TokenKind) -> bool { 103,530 ( 0.00%) if self.token.kind == expected { 312 ( 0.00%) self.bump(); . return true; . } 73,170 ( 0.00%) match self.token.kind.break_two_token_op() { 14 ( 0.00%) Some((first, second)) if first == expected => { 8 ( 0.00%) let first_span = self.sess.source_map().start_point(self.token.span); 10 ( 0.00%) let second_span = self.token.span.with_lo(first_span.hi()); 18 ( 0.00%) 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 . // is not needed (we'll capture the entire 'glued' token), . // and `next_tok` will set this field to `None` 2 ( 0.00%) self.token_cursor.break_last_token = true; . // Use the spacing of the glued token as the spacing . // of the unglued second token. 28 ( 0.00%) self.bump_with((Token::new(second, second_span), self.token_spacing)); . true . } . _ => { 43,896 ( 0.00%) self.expected_tokens.push(TokenType::Token(expected)); . false . } . } 191,638 ( 0.01%) } . . /// Eats `+` possibly breaking tokens like `+=` in process. . fn eat_plus(&mut self) -> bool { 8 ( 0.00%) 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, ()> { 384 ( 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, ()> { 66 ( 0.00%) if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `<` possibly breaking tokens like `<<` in process. 518 ( 0.00%) fn eat_lt(&mut self) -> bool { 44,098 ( 0.00%) let ate = self.break_and_eat(token::Lt); 29,376 ( 0.00%) if ate { . // See doc comment for `unmatched_angle_bracket_count`. 164 ( 0.00%) self.unmatched_angle_bracket_count += 1; 173 ( 0.00%) self.max_angle_bracket_count += 1; . debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); . } . ate 518 ( 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, ()> { 246 ( 0.00%) if self.break_and_eat(token::Gt) { . // See doc comment for `unmatched_angle_bracket_count`. 123 ( 0.00%) if self.unmatched_angle_bracket_count > 0 { 82 ( 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 { 107,724 ( 0.00%) TokenExpectType::Expect => self.check(k), 165 ( 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) { 107,577 ( 0.00%) if let token::CloseDelim(..) | token::Eof = self.token.kind { . break; . } 71,545 ( 0.00%) if let Some(ref t) = sep.sep { 72,157 ( 0.00%) if first { . first = false; . } else { 93,683 ( 0.00%) 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; . } . } . } . } . } . } 39,856 ( 0.00%) if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) { . trailing = true; . break; . } . 20,092 ( 0.00%) let t = f(self)?; 366 ( 0.00%) v.push(t); . } . 32,316 ( 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)> { 30,375 ( 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. 60,230 ( 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 */)> { 22,167 ( 0.00%) let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; 10,105 ( 0.00%) if !recovered { . self.eat(ket); . } 58,441 ( 0.00%) Ok((val, trailing)) 48,184 ( 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)> { 18,230 ( 0.00%) self.expect(bra)?; 48,184 ( 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( 6,122 ( 0.00%) &token::OpenDelim(delim), 6,222 ( 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. 1,642,680 ( 0.06%) fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) { . // Bumping after EOF is a bad sign, usually an infinite loop. 758,160 ( 0.03%) 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. 505,440 ( 0.02%) self.prev_token = mem::replace(&mut self.token, next_token); 126,360 ( 0.00%) self.token_spacing = next_spacing; . . // Diagnostics. 126,360 ( 0.00%) self.expected_tokens.clear(); . } . . /// Advance the parser by one token. 1,010,864 ( 0.04%) pub fn bump(&mut self) { 505,432 ( 0.02%) let next_token = self.next_tok(self.token.span); 758,148 ( 0.03%) self.bump_with(next_token); 1,010,864 ( 0.04%) } . . /// 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 { 914 ( 0.00%) if dist == 0 { 415 ( 0.00%) return looker(&self.token); . } . 57,244 ( 0.00%) let frame = &self.token_cursor.frame; 86,592 ( 0.00%) if frame.delim != DelimToken::NoDelim { . let all_normal = (0..dist).all(|i| { 247,836 ( 0.01%) let token = frame.tree_cursor.look_ahead(i); 371,234 ( 0.01%) !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _))) . }); . if all_normal { 426,175 ( 0.02%) return match frame.tree_cursor.look_ahead(dist - 1) { 156,681 ( 0.01%) Some(tree) => match tree { 60,646 ( 0.00%) TokenTree::Token(token) => looker(token), . TokenTree::Delimited(dspan, delim, _) => { 124,187 ( 0.00%) looker(&Token::new(token::OpenDelim(*delim), dspan.open)) . } . }, 56,591 ( 0.00%) None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)), . }; . } . } . . let mut cursor = self.token_cursor.clone(); . let mut i = 0; 193 ( 0.00%) let mut token = Token::dummy(); 114 ( 0.00%) while i < dist { 1,399 ( 0.00%) token = cursor.next().0; 653 ( 0.00%) if matches!( 386 ( 0.00%) token.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 60 ( 0.00%) i += 1; . } 4 ( 0.00%) return looker(&token); . } . . /// Returns whether any of the given keywords are `dist` tokens ahead of the current one. 3,888 ( 0.00%) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool { 1,002 ( 0.00%) self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw))) 3,888 ( 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. 104 ( 0.00%) fn parse_unsafety(&mut self) -> Unsafe { . if self.eat_keyword(kw::Unsafe) { . Unsafe::Yes(self.prev_token.uninterpolated_span()) . } else { . Unsafe::No . } 416 ( 0.00%) } . . /// Parses constness: `const` or nothing. 1,736 ( 0.00%) fn parse_constness(&mut self) -> Const { . // Avoid const blocks to be parsed as const items 493 ( 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 . } 3,038 ( 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 1108 ---------------------------------------- . id: DUMMY_NODE_ID, . value: self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()), . }; . 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). 12 ( 0.00%) fn parse_mutability(&mut self) -> Mutability { . if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not } 153 ( 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 { . None . } . } . . fn parse_field_name(&mut self) -> PResult<'a, Ident> { 35,046 ( 0.00%) if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind . { . self.expect_no_suffix(self.token.span, "a tuple index", suffix); . self.bump(); . Ok(Ident::new(symbol, self.prev_token.span)) . } else { 52,569 ( 0.00%) self.parse_ident_common(true) . } . } . . fn parse_mac_args(&mut self) -> PResult<'a, P> { 23 ( 0.00%) self.parse_mac_args_common(true).map(P) . } . . fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> { 66 ( 0.00%) self.parse_mac_args_common(false) . } . 279 ( 0.00%) fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> { 248 ( 0.00%) Ok( 199 ( 0.00%) if self.check(&token::OpenDelim(DelimToken::Paren)) 33 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Bracket)) 33 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Brace)) . { 80 ( 0.00%) match self.parse_token_tree() { 100 ( 0.00%) TokenTree::Delimited(dspan, delim, tokens) => . // We've confirmed above that there is a delimiter so unwrapping is OK. . { 40 ( 0.00%) MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens) . } . _ => unreachable!(), . } 22 ( 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(); . }, . ) 217 ( 0.00%) } . . fn parse_or_use_outer_attributes( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, AttrWrapper> { 114,343 ( 0.00%) if let Some(attrs) = already_parsed_attrs { . Ok(attrs) . } else { 75,682 ( 0.00%) self.parse_outer_attributes() . } . } . . /// Parses a single token tree from the input. 1,048 ( 0.00%) pub(crate) fn parse_token_tree(&mut self) -> TokenTree { 733 ( 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. 1,322 ( 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. 746 ( 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; 92 ( 0.00%) let stream = frame.tree_cursor.stream.clone(); 92 ( 0.00%) let span = frame.span; 46 ( 0.00%) let delim = frame.delim; . // Consume close delimiter 92 ( 0.00%) self.bump(); 230 ( 0.00%) TokenTree::Delimited(span, delim, stream) . } . token::CloseDelim(_) | token::Eof => unreachable!(), . _ => { 170 ( 0.00%) self.bump(); 425 ( 0.00%) TokenTree::Token(self.prev_token.clone()) . } . } 917 ( 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 { 38,161 ( 0.00%) let old = self.restrictions; 38,637 ( 0.00%) self.restrictions = res; . let res = f(self); 38,585 ( 0.00%) self.restrictions = old; . res . } . 3,248 ( 0.00%) fn is_crate_vis(&self) -> bool { 2,030 ( 0.00%) self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep) 3,654 ( 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. 2,710 ( 0.00%) pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> { 542 ( 0.00%) maybe_whole!(self, NtVis, |x| x); . 271 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw::Crate)); 1,084 ( 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". 244 ( 0.00%) return Ok(Visibility { 732 ( 0.00%) span: self.token.span.shrink_to_lo(), . kind: VisibilityKind::Inherited, . tokens: None, . }); . } 27 ( 0.00%) let lo = self.prev_token.span; . 135 ( 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. 45 ( 0.00%) if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep) . // account for `pub(crate::foo)` . { . // Parse `pub(crate)`. 15 ( 0.00%) self.bump(); // `(` 10 ( 0.00%) self.bump(); // `crate` 15 ( 0.00%) self.expect(&token::CloseDelim(token::Paren))?; // `)` 5 ( 0.00%) let vis = VisibilityKind::Crate(CrateSugar::PubCrate); . return Ok(Visibility { 15 ( 0.00%) span: lo.to(self.prev_token.span), . kind: vis, . tokens: None, . }); . } else if self.is_keyword_ahead(1, &[kw::In]) { . // Parse `pub(in path)`. . self.bump(); // `(` . self.bump(); // `in` . let path = self.parse_path(PathStyle::Mod)?; // `path` -- line 1317 ---------------------------------------- -- 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. . } . } . 66 ( 0.00%) Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None }) 2,439 ( 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 { 37 ( 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 1395 ---------------------------------------- . .emit(); . None . } . }, . Err(None) => None, . } . } . 30 ( 0.00%) pub fn collect_tokens_no_attrs( . &mut self, . f: impl FnOnce(&mut Self) -> PResult<'a, R>, . ) -> PResult<'a, R> { . // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use . // `ForceCollect::Yes` . self.collect_tokens_trailing_token( . AttrWrapper::empty(), . ForceCollect::Yes, 3 ( 0.00%) |this, _attrs| Ok((f(this)?, TrailingToken::None)), . ) 30 ( 0.00%) } . . /// `::{` or `::*` 119,288 ( 0.00%) fn is_import_coupler(&mut self) -> bool { 59,644 ( 0.00%) self.check(&token::ModSep) . && self.look_ahead(1, |t| { 1,521 ( 0.00%) *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star) . }) 133,425 ( 0.01%) } . . 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) . } . 592 ( 0.00%) pub fn emit_unclosed_delims(unclosed_delims: &mut Vec, sess: &ParseSess) { 296 ( 0.00%) *sess.reached_eof.borrow_mut() |= . unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()); 296 ( 0.00%) for unmatched in unclosed_delims.drain(..) { . if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) { . e.emit(); . } . } 592 ( 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 ---------------------------------------- 795,857 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs -------------------------------------------------------------------------------- Ir -- line 180 ---------------------------------------- . /// assert_eq!(v, &[0.into()]); . /// . /// // Ensure that the last item was dropped. . /// assert!(weak.upgrade().is_none()); . /// ``` . #[stable(feature = "drop_in_place", since = "1.8.0")] . #[lang = "drop_in_place"] . #[allow(unconditional_recursion)] 31,137,476 ( 1.23%) pub unsafe fn drop_in_place(to_drop: *mut T) { . // Code here does not matter - this is replaced by the . // real drop glue by the compiler. . . // SAFETY: see comment above . unsafe { drop_in_place(to_drop) } . } . . /// Creates a null raw pointer. -- line 196 ---------------------------------------- -- line 448 ---------------------------------------- . return; . } . } . . // Direct swapping, for the cases not going through the block optimization. . // SAFETY: the caller must guarantee that `x` and `y` are valid . // for writes, properly aligned, and non-overlapping. . unsafe { 14 ( 0.00%) let z = read(x); . copy_nonoverlapping(y, x, 1); . write(y, z); . } . } . . #[inline] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] . const unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) { -- line 464 ---------------------------------------- -- line 693 ---------------------------------------- . let mut tmp = MaybeUninit::::uninit(); . // SAFETY: the caller must guarantee that `src` is valid for reads. . // `src` cannot overlap `tmp` because `tmp` was just allocated on . // the stack as a separate allocated object. . // . // Also, since we just wrote a valid value into `tmp`, it is guaranteed . // to be properly initialized. . unsafe { 351,150 ( 0.01%) copy_nonoverlapping(src, tmp.as_mut_ptr(), 1); 3,285,522 ( 0.13%) tmp.assume_init() . } . } . . /// Reads the value from `src` without moving it. This leaves the . /// memory in `src` unchanged. . /// . /// Unlike [`read`], `read_unaligned` works with unaligned pointers. . /// -- line 710 ---------------------------------------- -- line 884 ---------------------------------------- . #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] . fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize); . } . . // SAFETY: the caller must guarantee that `dst` is valid for writes. . // `dst` cannot overlap `src` because the caller has mutable access . // to `dst` while `src` is owned by this function. . unsafe { 33,692,630 ( 1.33%) copy_nonoverlapping(&src as *const T, dst, 1); . intrinsics::forget(src); . } . } . . /// Overwrites a memory location with the given value without reading or . /// dropping the old value. . /// . /// Unlike [`write()`], the pointer may be unaligned. -- line 900 ---------------------------------------- -- line 1206 ---------------------------------------- . if stride == 1 { . // `stride == 1` case can be computed more simply through `-p (mod a)`, but doing so . // inhibits LLVM's ability to select instructions like `lea`. Instead we compute . // . // round_up_to_next_alignment(p, a) - p . // . // which distributes operations around the load-bearing, but pessimizing `and` sufficiently . // for LLVM to be able to utilize the various optimizations it knows about. 465 ( 0.00%) return wrapping_sub( 1,536 ( 0.00%) wrapping_add(p as usize, a_minus_one) & wrapping_sub(0, a), . p as usize, . ); . } . . let pmoda = p as usize & a_minus_one; . if pmoda == 0 { . // Already aligned. Yay! . return 0; -- line 1223 ---------------------------------------- -- line 1348 ---------------------------------------- . /// assert!(std::ptr::eq( . /// &wrapper as &dyn Trait as *const dyn Trait as *const u8, . /// &wrapper.member as &dyn Trait as *const dyn Trait as *const u8, . /// )); . /// ``` . #[stable(feature = "ptr_eq", since = "1.17.0")] . #[inline] . pub fn eq(a: *const T, b: *const T) -> bool { 918,874 ( 0.04%) a == b . } . . /// Hash a raw pointer. . /// . /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly) . /// by its address rather than the value it points to . /// (which is what the `Hash for &T` implementation does). . /// -- line 1364 ---------------------------------------- 5,768,165 ( 0.23%) -------------------------------------------------------------------------------- -- 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) { 416 ( 0.00%) let old = self.replace(val); 272 ( 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. 149,294 ( 0.01%) unsafe { *self.value.get() } . } . . /// Updates the contained value using a function and returns the new value. . /// . /// # Examples . /// . /// ``` . /// #![feature(cell_update)] -- line 450 ---------------------------------------- -- line 689 ---------------------------------------- . . #[inline(always)] . fn is_writing(x: BorrowFlag) -> bool { . x < UNUSED . } . . #[inline(always)] . fn is_reading(x: BorrowFlag) -> bool { 558,568 ( 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 { 19,107 ( 0.00%) RefCell { 14,703 ( 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. 428 ( 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] 711 ( 0.00%) pub fn borrow(&self) -> Ref<'_, T> { . self.try_borrow().expect("already mutably borrowed") 2,133 ( 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] 57,538 ( 0.00%) pub fn borrow_mut(&self) -> RefMut<'_, T> { . self.try_borrow_mut().expect("already borrowed") 172,614 ( 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. 22 ( 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> { 908,683 ( 0.04%) let b = borrow.get().wrapping_add(1); 505,416 ( 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) { 460,320 ( 0.02%) let borrow = self.borrow.get(); . debug_assert!(is_reading(borrow)); 920,387 ( 0.04%) 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) { 4,646,163 ( 0.18%) let borrow = self.borrow.get(); . debug_assert!(is_writing(borrow)); 8,856,682 ( 0.35%) 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. 9,523,294 ( 0.38%) 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 { 155 ( 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! 4,397,433 ( 0.17%) 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 ---------------------------------------- 7,487,314 ( 0.30%) -------------------------------------------------------------------------------- -- 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, . }; . 250,096 ( 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 { 28 ( 0.00%) match self { 12 ( 0.00%) 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 { 153,886 ( 0.01%) 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 { 540 ( 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 { 60 ( 0.00%) match self.meta { 42 ( 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> { 942,096 ( 0.04%) Ok(MPlaceTy { mplace: self.mplace.offset(offset, meta, cx)?, layout }) . } . . #[inline] . pub fn from_aligned_ptr(ptr: Pointer>, layout: TyAndLayout<'tcx>) -> Self { 8 ( 0.00%) MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout } . } . . #[inline] 8 ( 0.00%) pub(super) fn len(&self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> { 38 ( 0.00%) if self.layout.is_unsized() { . // We need to consult `meta` metadata 34 ( 0.00%) match self.layout.ty.kind() { 10 ( 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!) 8 ( 0.00%) match self.layout.fields { 8 ( 0.00%) FieldsShape::Array { count, .. } => Ok(count), . _ => bug!("len not supported on sized type {:?}", self.layout.ty), . } . } 16 ( 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>> { 460,682 ( 0.02%) match **self { 2,344,192 ( 0.09%) Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }), 2 ( 0.00%) Operand::Immediate(_) if self.layout.is_zst() => Ok(MPlaceTy::dangling(self.layout)), 149,013 ( 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`. 160 ( 0.00%) pub fn ref_to_mplace( . &self, . val: &ImmTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { . let pointee_type = 48 ( 0.00%) val.layout.ty.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty; 48 ( 0.00%) let layout = self.layout_of(pointee_type)?; 80 ( 0.00%) let (ptr, meta) = match **val { 16 ( 0.00%) Immediate::Scalar(ptr) => (ptr, MemPlaceMeta::None), 56 ( 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. 16 ( 0.00%) align: layout.align.abi, . meta, . }; 272 ( 0.00%) Ok(MPlaceTy { mplace, layout }) 144 ( 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. 44 ( 0.00%) pub fn deref_operand( . &self, . src: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { 12 ( 0.00%) let val = self.read_immediate(src)?; . trace!("deref to {} on {:?}", val.layout.ty, *val); 8 ( 0.00%) let mplace = self.ref_to_mplace(&val)?; 20 ( 0.00%) self.check_mplace_access(mplace, CheckInAllocMsg::DerefTest)?; 44 ( 0.00%) Ok(mplace) 36 ( 0.00%) } . . #[inline] . pub(super) fn get_alloc( . &self, . place: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Option>> { . assert!(!place.layout.is_unsized()); 98,537 ( 0.00%) assert!(!place.meta.has_meta()); 98,537 ( 0.00%) let size = place.layout.size; 886,833 ( 0.04%) 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>> { 31,196 ( 0.00%) assert!(!place.layout.is_unsized()); 31,196 ( 0.00%) assert!(!place.meta.has_meta()); 31,196 ( 0.00%) let size = place.layout.size; 187,176 ( 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)? 4 ( 0.00%) .unwrap_or((mplace.layout.size, mplace.layout.align.abi)); 4 ( 0.00%) assert!(mplace.mplace.align <= align, "dynamic alignment less strict than static one?"); 4 ( 0.00%) let align = M::enforce_alignment(&self.memory.extra).then_some(align); 12 ( 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>> { 628,122 ( 0.02%) let offset = base.layout.fields.offset(field); 429,375 ( 0.02%) let field_layout = base.layout.field(self, field); . . // Offset may need adjustment for unsized fields. 935,696 ( 0.04%) 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 140,508 ( 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`. 80 ( 0.00%) pub(super) fn mplace_array_fields<'a>( . &self, . base: &'a MPlaceTy<'tcx, Tag>, . ) -> InterpResult<'tcx, impl Iterator>> + 'a> . { 32 ( 0.00%) let len = base.len(self)?; // also asserts that we have a type where this makes sense 24 ( 0.00%) let stride = match base.layout.fields { 8 ( 0.00%) FieldsShape::Array { stride, .. } => stride, . _ => span_bug!(self.cur_span(), "mplace_array_fields: expected an array layout"), . }; 16 ( 0.00%) let layout = base.layout.field(self, 0); 8 ( 0.00%) let dl = &self.tcx.data_layout; . // `Size` multiplication 178,850 ( 0.01%) Ok((0..len).map(move |i| base.offset(stride * i, MemPlaceMeta::None, layout, dl))) 72 ( 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 24,153 ( 0.00%) assert!(!base.meta.has_meta()); 72,459 ( 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. 450,600 ( 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. 45,060 ( 0.00%) let mplace = self.force_allocation(base)?; 540,720 ( 0.02%) Ok(self.mplace_field(&mplace, field)?.into()) 360,480 ( 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 46,624 ( 0.00%) Ok(match base.place { . Place::Ptr(mplace) => { . self.mplace_downcast(&MPlaceTy { mplace, layout: base.layout }, variant)?.into() . } . Place::Local { .. } => { . let layout = base.layout.for_variant(self, variant); 5,828 ( 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::*; 493,620 ( 0.02%) Ok(match proj_elem { 135,380 ( 0.01%) Field(field, _) => self.place_field(base, field.index())?, . Downcast(_, variant) => self.place_downcast(base, variant)?, 32 ( 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`. 281,256 ( 0.01%) pub fn eval_place( . &mut self, . place: mir::Place<'tcx>, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { 175,785 ( 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)?, . }; . 65,816 ( 0.00%) for elem in place.projection.iter() { 32,908 ( 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, . )); 632,826 ( 0.03%) Ok(place_ty) 281,256 ( 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> { 40,352 ( 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. 31,218 ( 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. 62,436 ( 0.00%) let mplace = match dest.place { 44 ( 0.00%) Place::Local { frame, local } => { . match M::access_local_mut(self, frame, local)? { . Ok(local) => { . // Local can be updated in-place. 220 ( 0.00%) *local = LocalValue::Live(Operand::Immediate(src)); . return Ok(()); . } . Err(mplace) => { . // The local is in memory, go on below. . mplace . } . } . } 187,176 ( 0.01%) Place::Ptr(mplace) => mplace, // already referring to memory . }; 280,764 ( 0.01%) let dest = MPlaceTy { mplace, layout: dest.layout }; . . // This is already in memory, write there. 343,156 ( 0.01%) self.write_immediate_to_mplace_no_validate(src, &dest) 62,436 ( 0.00%) } . . /// Write an immediate to memory. . /// If you use this you are responsible for validating that things got copied at the . /// right type. 311,960 ( 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 31,196 ( 0.00%) let tcx = *self.tcx; 62,392 ( 0.00%) let mut alloc = match self.get_alloc_mut(dest)? { 155,980 ( 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! 62,392 ( 0.00%) match value { . Immediate::Scalar(scalar) => { 58,620 ( 0.00%) match dest.layout.abi { . Abi::Scalar(_) => {} // fine . _ => span_bug!( . self.cur_span(), . "write_immediate_to_mplace: invalid Scalar layout: {:#?}", . dest.layout . ), . } 263,790 ( 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. 3,772 ( 0.00%) let (a, b) = match dest.layout.abi { 16,950 ( 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. . 18,860 ( 0.00%) alloc.write_scalar(alloc_range(Size::ZERO, a_size), a_val)?; 15,088 ( 0.00%) alloc.write_scalar(alloc_range(b_offset, b_size), b_val) . } . } 249,568 ( 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> { 195,178 ( 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. 296,296 ( 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. 666,666 ( 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. 185,185 ( 0.01%) let src = match self.try_read_immediate(src)? { . Ok(src_val) => { 23,158 ( 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`. 301,054 ( 0.01%) return self.write_immediate_no_validate(*src_val, dest); . } 111,032 ( 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! 180,427 ( 0.01%) let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?; . let size = size.unwrap_or_else(|| { 41,637 ( 0.00%) assert!( . !dest.layout.is_unsized(), . "Cannot copy into already initialized unsized place" . ); 13,879 ( 0.00%) dest.layout.size . }); 13,879 ( 0.00%) assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances"); . 13,879 ( 0.00%) self.memory 41,637 ( 0.00%) .copy(src.ptr, src.align, dest.ptr, dest.align, size, /*nonoverlapping*/ true) 296,296 ( 0.01%) } . . /// Copies the data from an operand to a place. The layouts may disagree, but they must . /// have the same size. 120 ( 0.00%) pub fn copy_op_transmute( . &mut self, . src: &OpTy<'tcx, M::PointerTag>, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 270 ( 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. 530,505 ( 0.02%) pub fn force_allocation_maybe_sized( . &mut self, . place: &PlaceTy<'tcx, M::PointerTag>, . meta: MemPlaceMeta, . ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option)> { 589,450 ( 0.02%) let (mplace, size) = match place.place { 45,062 ( 0.00%) Place::Local { frame, local } => { 90,124 ( 0.00%) match M::access_local_mut(self, frame, local)? { 141,867 ( 0.01%) 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 = 78,815 ( 0.00%) self.layout_of_local(&self.stack()[frame], local, None)?; . // We also need to support unsized types, and hence cannot use `allocate`. 63,052 ( 0.00%) let (size, align) = self . .size_and_align_of(&meta, &local_layout)? . .expect("Cannot allocate for non-dyn-sized type"); 110,341 ( 0.00%) let ptr = self.memory.allocate(size, align, MemoryKind::Stack)?; . let mplace = MemPlace { ptr: ptr.into(), align, meta }; 78,815 ( 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. 299,497 ( 0.01%) *M::access_local_mut(self, frame, local).unwrap().unwrap() = . LocalValue::Live(Operand::Indirect(mplace)); 110,341 ( 0.00%) (mplace, Some(size)) . } 292,990 ( 0.01%) Err(mplace) => (mplace, None), // this already was an indirect local . } . } 180,479 ( 0.01%) Place::Ptr(mplace) => (mplace, None), . }; . // Return with the original layout, so that the caller can go on 707,340 ( 0.03%) Ok((MPlaceTy { mplace, layout: place.layout }, size)) 471,560 ( 0.02%) } . . #[inline(always)] . pub fn force_allocation( . &mut self, . place: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { 405,576 ( 0.02%) Ok(self.force_allocation_maybe_sized(place, MemPlaceMeta::None)?.0) . } . . pub fn allocate( . &mut self, . layout: TyAndLayout<'tcx>, . kind: MemoryKind, . ) -> InterpResult<'static, MPlaceTy<'tcx, M::PointerTag>> { 105 ( 0.00%) let ptr = self.memory.allocate(layout.size, layout.align.abi, kind)?; . Ok(MPlaceTy::from_aligned_ptr(ptr.into(), layout)) . } . . /// 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, -- line 989 ---------------------------------------- -- 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,561 ( 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,204 ( 0.00%) match dest.layout.ty.kind() { 16,102 ( 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. 16,102 ( 0.00%) if dest.layout.for_variant(self, variant_index).abi.is_uninhabited() { . throw_ub!(UninhabitedEnumVariantWritten) . } . 40,255 ( 0.00%) match dest.layout.variants { . Variants::Single { index } => { . assert_eq!(index, variant_index); . } . Variants::Multiple { . tag_encoding: TagEncoding::Direct, 24,153 ( 0.00%) tag: tag_layout, 16,102 ( 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,204 ( 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); . 40,255 ( 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,408 ( 0.00%) } . 36 ( 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` 12 ( 0.00%) let _ = self.tcx.global_alloc(raw.alloc_id); . let ptr = self.global_base_pointer(Pointer::from(raw.alloc_id))?; 12 ( 0.00%) let layout = self.layout_of(raw.ty)?; 24 ( 0.00%) Ok(MPlaceTy::from_aligned_ptr(ptr.into(), layout)) 28 ( 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 ---------------------------------------- 920,801 ( 0.04%) -------------------------------------------------------------------------------- -- 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 { 5,061,287 ( 0.20%) Vec { buf: RawVec::NEW, len: 0 } 88 ( 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 { 1,265,929 ( 0.05%) 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 { 33,178 ( 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 { 1,017,728 ( 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) { 218,119 ( 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) { 2,128 ( 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. 44,310 ( 0.00%) if self.capacity() > self.len { 1,084 ( 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(); 15,074 ( 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")] 632,132 ( 0.03%) 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. 652,207 ( 0.03%) 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); 447,141 ( 0.02%) self.len = len; 1,046 ( 0.00%) ptr::drop_in_place(s); . } 758,558 ( 0.03%) } . . /// 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. 4,554,305 ( 0.18%) 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. 3,981,807 ( 0.16%) 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()); . 1,300,292 ( 0.05%) self.len = new_len; 228 ( 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")] 938 ( 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); . } . 145 ( 0.00%) let len = self.len(); 302 ( 0.00%) if index > len { . assert_failed(index, len); . } . . // space for the new element 422 ( 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.) 600 ( 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); . } 422 ( 0.00%) self.set_len(len + 1); . } 804 ( 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); . } . 80 ( 0.00%) let len = self.len(); 313 ( 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. 112 ( 0.00%) ret = ptr::read(ptr); . . // Shift everything down to fill in that spot. 240 ( 0.00%) ptr::copy(ptr.offset(1), ptr, len - index - 1); . } 95 ( 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")] 41,973 ( 0.00%) pub fn retain(&mut self, mut f: F) . where . F: FnMut(&T) -> bool, . { 2,631 ( 0.00%) self.retain_mut(|elem| f(elem)); 40,760 ( 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, . { 5,230 ( 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) { 4,134 ( 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), 2,688 ( 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, . { 393,540 ( 0.02%) 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) }; 141,895 ( 0.01%) if !f(cur) { . // Advance early to avoid double drop if `drop_in_place` panicked. 94,826 ( 0.00%) g.processed_len += 1; 94,686 ( 0.00%) g.deleted_cnt += 1; . // SAFETY: We never touch this element again after dropped. 94,603 ( 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 { 300 ( 0.00%) let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt); . ptr::copy_nonoverlapping(cur, hole_slot, 1); . } . } 200 ( 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")] 518 ( 0.00%) pub fn dedup_by(&mut self, mut same_bucket: F) . where . F: FnMut(&mut T, &mut T) -> bool, . { 74 ( 0.00%) let len = self.len(); 368 ( 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 { 309 ( 0.00%) while gap.read < len { . let read_ptr = ptr.add(gap.read); . let prev_ptr = ptr.add(gap.write.wrapping_sub(1)); . 164 ( 0.00%) if same_bucket(&mut *read_ptr, &mut *prev_ptr) { . // Increase `gap.read` now since the drop may panic. . gap.read += 1; . /* We have found duplicate, drop it in-place */ . ptr::drop_in_place(read_ptr); . } else { . let write_ptr = ptr.add(gap.write); . . /* Because `read_ptr` can be equal to `write_ptr`, we either . * have to use `copy` or conditional `copy_nonoverlapping`. . * Looks like the first option is faster. */ . ptr::copy(read_ptr, write_ptr, 1); . . /* We have filled that place, so go further */ 105 ( 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); . } 592 ( 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")] 40 ( 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. 6,735,999 ( 0.27%) if self.len == self.buf.capacity() { 341,897 ( 0.01%) self.buf.reserve_for_push(self.len); . } . unsafe { 147,414 ( 0.01%) let end = self.as_mut_ptr().add(self.len); . ptr::write(end, value); 9,705,366 ( 0.38%) self.len += 1; . } 32 ( 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 { 1,021,569 ( 0.04%) if self.len == 0 { 4 ( 0.00%) None . } else { . unsafe { 1,014,590 ( 0.04%) self.len -= 1; 107,261 ( 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")] 91 ( 0.00%) pub fn append(&mut self, other: &mut Self) { . unsafe { . self.append_elements(other.as_slice() as _); . other.set_len(0); . } 78 ( 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); 1,945 ( 0.00%) let len = self.len(); . unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; 179,310 ( 0.01%) 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. . // 16,869 ( 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). 40,620 ( 0.00%) let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); 153 ( 0.00%) Drain { . tail_start: end, 27,082 ( 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) { 1,137,410 ( 0.04%) 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 { 968,338 ( 0.04%) 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); . } . 202 ( 0.00%) if at > self.len() { . assert_failed(at, self.len()); . } . 164 ( 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")] 4,882 ( 0.00%) pub fn resize_with(&mut self, new_len: usize, f: F) . where . F: FnMut() -> T, . { 662 ( 0.00%) let len = self.len(); 1,324 ( 0.00%) if new_len > len { 57,154 ( 0.00%) self.extend_with(new_len - len, ExtendFunc(f)); . } else { . self.truncate(new_len); . } 4,220 ( 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, 27 ( 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")] 160 ( 0.00%) pub fn resize(&mut self, new_len: usize, value: T) { 16 ( 0.00%) let len = self.len(); . 48 ( 0.00%) if new_len > len { 606 ( 0.00%) self.extend_with(new_len - len, ExtendElement(value)) . } else { . self.truncate(new_len); . } 32 ( 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 { 58,106 ( 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. 28,300 ( 0.00%) fn extend_with>(&mut self, n: usize, mut value: E) { . self.reserve(n); . . unsafe { 969 ( 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); . } . 125,863 ( 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 . } 22,499 ( 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) { 75 ( 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")] 16,253 ( 0.00%) pub fn from_elem(elem: T, n: usize) -> Vec { 76,257 ( 0.00%) ::from_elem(elem, n, Global) 22,955 ( 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] { 7,519,741 ( 0.30%) unsafe { slice::from_raw_parts(self.as_ptr(), self.len) } 46 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::DerefMut for Vec { . fn deref_mut(&mut self) -> &mut [T] { 1,360,961 ( 0.05%) 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))] 217,091 ( 0.01%) fn clone(&self) -> Self { . let alloc = self.allocator().clone(); 2 ( 0.00%) <[T]>::to_vec_in(&**self, alloc) 251,302 ( 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 { 47,097 ( 0.00%) Index::index(&**self, index) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_on_unimplemented( . message = "vector indices are of type `usize` or ranges of `usize`", . label = "vector indices are of type `usize` or ranges of `usize`" . )] . impl, A: Allocator> IndexMut for Vec { . #[inline] . fn index_mut(&mut self, index: I) -> &mut Self::Output { 232 ( 0.00%) IndexMut::index_mut(&mut **self, index) . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl FromIterator for Vec { . #[inline] . fn from_iter>(iter: I) -> Vec { 1,915,944 ( 0.08%) >::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 { 1,161,908 ( 0.05%) 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(); 535,337 ( 0.02%) 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> { 1,168 ( 0.00%) self.iter_mut() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend for Vec { . #[inline] 424 ( 0.00%) fn extend>(&mut self, iter: I) { 511,415 ( 0.02%) >::spec_extend(self, iter.into_iter()) 424 ( 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); . // } 26,004 ( 0.00%) while let Some(element) = iterator.next() { 4,216 ( 0.00%) let len = self.len(); 79,564 ( 0.00%) if len == self.capacity() { 353 ( 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 66,428 ( 0.00%) self.set_len(len + 1); . } . } 804 ( 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, . { 148,918 ( 0.01%) 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, . { 848 ( 0.00%) let old_len = self.len(); . . // Guard against us getting leaked (leak amplification) . unsafe { . self.set_len(0); . } . 1,912 ( 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 { 1,756,203 ( 0.07%) 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 552,287 ( 0.02%) ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len)) . } . // RawVec handles deallocation 2,082,008 ( 0.08%) } . } . . #[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 ---------------------------------------- 2,788,988 ( 0.11%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 38 ---------------------------------------- . #[derive(Debug)] . pub struct Token { . pub kind: TokenKind, . pub len: usize, . } . . impl Token { . fn new(kind: TokenKind, len: usize) -> Token { 1,686,483 ( 0.07%) Token { kind, len } . } . } . . /// Enum representing common lexeme types. . // perf note: Changing all `usize` to `u32` doesn't change performance. See #77629 334,490 ( 0.01%) #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] . pub enum TokenKind { . // Multi-char tokens: . /// "// comment" . LineComment { doc_style: Option }, . /// `/* block comment */` . /// . /// Block comments can be recursive, so the sequence like `/* /* */` . /// will not be considered terminated and will result in a parsing error. -- line 60 ---------------------------------------- -- line 192 ---------------------------------------- . /// Literal starts with "0x". . Hexadecimal, . /// Literal doesn't contain a prefix. . Decimal, . } . . /// `rustc` allows files to have a shebang, e.g. "#!/usr/bin/rustrun", . /// but shebang isn't a part of rust syntax. 28 ( 0.00%) pub fn strip_shebang(input: &str) -> Option { . // Shebang must start with `#!` literally, without any preceding whitespace. . // For simplicity we consider any line starting with `#!` a shebang, . // regardless of restrictions put on shebangs by specific platforms. . if let Some(input_tail) = input.strip_prefix("#!") { . // Ok, this is a shebang but if the next non-whitespace token is `[`, . // then it may be valid Rust code, so consider it Rust code. . let next_non_whitespace_token = tokenize(input_tail).map(|tok| tok.kind).find(|tok| { . !matches!( -- line 208 ---------------------------------------- -- line 213 ---------------------------------------- . ) . }); . if next_non_whitespace_token != Some(TokenKind::OpenBracket) { . // No other choice than to consider this a shebang. . return Some(2 + input_tail.lines().next().unwrap_or_default().len()); . } . } . None 32 ( 0.00%) } . . /// Parses the first token from the provided input string. 562,161 ( 0.02%) pub fn first_token(input: &str) -> Token { . debug_assert!(!input.is_empty()); 187,387 ( 0.01%) Cursor::new(input).advance_token() 749,548 ( 0.03%) } . . /// Creates an iterator that produces tokens from the input string. . pub fn tokenize(input: &str) -> impl Iterator + '_ { . let mut cursor = Cursor::new(input); . std::iter::from_fn(move || { . if cursor.is_eof() { . None . } else { -- line 235 ---------------------------------------- -- line 243 ---------------------------------------- . /// See [Rust language reference](https://doc.rust-lang.org/reference/whitespace.html) . /// for definitions of these classes. . pub fn is_whitespace(c: char) -> bool { . // This is Pattern_White_Space. . // . // Note that this set is stable (ie, it doesn't change with different . // Unicode versions), so it's ok to just hard-code the values. . 342,154 ( 0.01%) matches!( . c, . // Usual ASCII suspects . '\u{0009}' // \t . | '\u{000A}' // \n . | '\u{000B}' // vertical tab . | '\u{000C}' // form feed . | '\u{000D}' // \r . | '\u{0020}' // space -- line 259 ---------------------------------------- -- line 271 ---------------------------------------- . ) . } . . /// True if `c` is valid as a first character of an identifier. . /// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for . /// a formal definition of valid identifier name. . pub fn is_id_start(c: char) -> bool { . // This is XID_Start OR '_' (which formally is not a XID_Start). 46,632 ( 0.00%) c == '_' || unicode_xid::UnicodeXID::is_xid_start(c) . } . . /// True if `c` is valid as a non-first character of an identifier. . /// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for . /// a formal definition of valid identifier name. . pub fn is_id_continue(c: char) -> bool { . unicode_xid::UnicodeXID::is_xid_continue(c) . } . . /// The passed string is lexically an identifier. 5 ( 0.00%) pub fn is_ident(string: &str) -> bool { . let mut chars = string.chars(); . if let Some(start) = chars.next() { . is_id_start(start) && chars.all(is_id_continue) . } else { . false . } 7 ( 0.00%) } . . impl Cursor<'_> { . /// Parses a token from the input string. 1,499,096 ( 0.06%) fn advance_token(&mut self) -> Token { . let first_char = self.bump().unwrap(); 644,366 ( 0.03%) let token_kind = match first_char { . // Slash, comment or block comment. 736 ( 0.00%) '/' => match self.first() { . '/' => self.line_comment(), . '*' => self.block_comment(), 22 ( 0.00%) _ => Slash, . }, . . // Whitespace sequence. . c if is_whitespace(c) => self.whitespace(), . . // Raw identifier, raw string literal or identifier. 184 ( 0.00%) 'r' => match (self.first(), self.second()) { . ('#', c1) if is_id_start(c1) => self.raw_ident(), . ('#', _) | ('"', _) => { . let (n_hashes, err) = self.raw_double_quoted_string(1); . let suffix_start = self.len_consumed(); . if err.is_none() { . self.eat_literal_suffix(); . } . let kind = RawStr { n_hashes, err }; . Literal { kind, suffix_start } . } . _ => self.ident_or_unknown_prefix(), . }, . . // Byte literal, byte string literal, raw byte string literal or identifier. 158,309 ( 0.01%) 'b' => match (self.first(), self.second()) { . ('\'', _) => { . self.bump(); 33 ( 0.00%) let terminated = self.single_quoted_string(); . let suffix_start = self.len_consumed(); 22 ( 0.00%) if terminated { . self.eat_literal_suffix(); . } . let kind = Byte { terminated }; 22 ( 0.00%) Literal { kind, suffix_start } . } . ('"', _) => { . self.bump(); . let terminated = self.double_quoted_string(); . let suffix_start = self.len_consumed(); . if terminated { . self.eat_literal_suffix(); . } -- line 347 ---------------------------------------- -- line 361 ---------------------------------------- . _ => self.ident_or_unknown_prefix(), . }, . . // Identifier (this should be checked after other variant that can . // start as identifier). . c if is_id_start(c) => self.ident_or_unknown_prefix(), . . // Numeric literal. 277,677 ( 0.01%) c @ '0'..='9' => { . let literal_kind = self.number(c); . let suffix_start = self.len_consumed(); . self.eat_literal_suffix(); 97,155 ( 0.00%) TokenKind::Literal { kind: literal_kind, suffix_start } . } . . // One-symbol tokens. 464 ( 0.00%) ';' => Semi, 47,482 ( 0.00%) ',' => Comma, 442 ( 0.00%) '.' => Dot, 16,168 ( 0.00%) '(' => OpenParen, 16,168 ( 0.00%) ')' => CloseParen, 12,080 ( 0.00%) '{' => OpenBrace, 12,080 ( 0.00%) '}' => CloseBrace, 86 ( 0.00%) '[' => OpenBracket, 86 ( 0.00%) ']' => CloseBracket, 6 ( 0.00%) '@' => At, 44 ( 0.00%) '#' => Pound, . '~' => Tilde, 10 ( 0.00%) '?' => Question, 35,606 ( 0.00%) ':' => Colon, . '$' => Dollar, 524 ( 0.00%) '=' => Eq, 56 ( 0.00%) '!' => Bang, 104 ( 0.00%) '<' => Lt, 282 ( 0.00%) '>' => Gt, 122 ( 0.00%) '-' => Minus, 176 ( 0.00%) '&' => And, 162 ( 0.00%) '|' => Or, 82 ( 0.00%) '+' => Plus, 40 ( 0.00%) '*' => Star, . '^' => Caret, 4 ( 0.00%) '%' => Percent, . . // Lifetime or character literal. 5,913 ( 0.00%) '\'' => self.lifetime_or_char(), . . // String literal. . '"' => { 60 ( 0.00%) let terminated = self.double_quoted_string(); . let suffix_start = self.len_consumed(); 40 ( 0.00%) if terminated { . self.eat_literal_suffix(); . } . let kind = Str { terminated }; 40 ( 0.00%) Literal { kind, suffix_start } . } . // Identifier starting with an emoji. Only lexed for graceful error recovery. . c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => { . self.fake_ident_or_unknown_prefix() . } . _ => Unknown, . }; . Token::new(token_kind, self.len_consumed()) 1,686,483 ( 0.07%) } . . fn line_comment(&mut self) -> TokenKind { . debug_assert!(self.prev() == '/' && self.first() == '/'); . self.bump(); . 596 ( 0.00%) let doc_style = match self.first() { . // `//!` is an inner line doc comment. . '!' => Some(DocStyle::Inner), . // `////` (more than 3 slashes) is not considered a doc comment. 144 ( 0.00%) '/' if self.second() != '/' => Some(DocStyle::Outer), . _ => None, . }; . 7,634 ( 0.00%) self.eat_while(|c| c != '\n'); 519 ( 0.00%) LineComment { doc_style } . } . . fn block_comment(&mut self) -> TokenKind { . debug_assert!(self.prev() == '/' && self.first() == '*'); . self.bump(); . . let doc_style = match self.first() { . // `/*!` is an inner block doc comment. -- line 447 ---------------------------------------- -- line 474 ---------------------------------------- . } . . BlockComment { doc_style, terminated: depth == 0 } . } . . fn whitespace(&mut self) -> TokenKind { . debug_assert!(is_whitespace(self.prev())); . self.eat_while(is_whitespace); 61,184 ( 0.00%) Whitespace . } . . fn raw_ident(&mut self) -> TokenKind { . debug_assert!(self.prev() == 'r' && self.first() == '#' && is_id_start(self.second())); . // Eat "#" symbol. . self.bump(); . // Eat the identifier part of RawIdent. . self.eat_identifier(); . RawIdent . } . 167,245 ( 0.01%) fn ident_or_unknown_prefix(&mut self) -> TokenKind { . debug_assert!(is_id_start(self.prev())); . // Start is already eaten, eat the rest of identifier. 66,898 ( 0.00%) self.eat_while(is_id_continue); . // Known prefixes must have been handled earlier. So if . // we see a prefix here, it is definitely an unknown prefix. 66,898 ( 0.00%) match self.first() { . '#' | '"' | '\'' => UnknownPrefix, 33,449 ( 0.00%) c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => { . self.fake_ident_or_unknown_prefix() . } 33,449 ( 0.00%) _ => Ident, . } 133,796 ( 0.01%) } . . fn fake_ident_or_unknown_prefix(&mut self) -> TokenKind { . // Start is already eaten, eat the rest of identifier. . self.eat_while(|c| { . unicode_xid::UnicodeXID::is_xid_continue(c) . || (!c.is_ascii() && unic_emoji_char::is_emoji(c)) . || c == '\u{200d}' . }); -- line 515 ---------------------------------------- -- line 519 ---------------------------------------- . '#' | '"' | '\'' => UnknownPrefix, . _ => InvalidIdent, . } . } . . fn number(&mut self, first_digit: char) -> LiteralKind { . debug_assert!('0' <= self.prev() && self.prev() <= '9'); . let mut base = Base::Decimal; 38,862 ( 0.00%) if first_digit == '0' { . // Attempt to parse encoding base. 5,728 ( 0.00%) let has_digits = match self.first() { . 'b' => { . base = Base::Binary; . self.bump(); . self.eat_decimal_digits() . } . 'o' => { . base = Base::Octal; . self.bump(); -- line 537 ---------------------------------------- -- line 538 ---------------------------------------- . self.eat_decimal_digits() . } . 'x' => { . base = Base::Hexadecimal; . self.bump(); . self.eat_hexadecimal_digits() . } . // Not a base prefix. 3,435 ( 0.00%) '0'..='9' | '_' | '.' | 'e' | 'E' => { . self.eat_decimal_digits(); . true . } . // Just a 0. . _ => return Int { base, empty_int: false }, . }; . // Base prefix was provided, but there were no digits . // after it, e.g. "0x". -- line 554 ---------------------------------------- -- line 555 ---------------------------------------- . if !has_digits { . return Int { base, empty_int: true }; . } . } else { . // No base prefix, parse number in the usual way. . self.eat_decimal_digits(); . }; . 109,710 ( 0.00%) match self.first() { . // Don't be greedy if this is actually an . // integer literal followed by field/method access or a range pattern . // (`0..2` and `12.foo()`) 6 ( 0.00%) '.' if self.second() != '.' && !is_id_start(self.second()) => { . // might have stuff after the ., and if it does, it needs to start . // with a number . self.bump(); . let mut empty_exponent = false; . if self.first().is_digit(10) { . self.eat_decimal_digits(); . match self.first() { . 'e' | 'E' => { -- line 575 ---------------------------------------- -- line 585 ---------------------------------------- . self.bump(); . let empty_exponent = !self.eat_float_exponent(); . Float { base, empty_exponent } . } . _ => Int { base, empty_int: false }, . } . } . 13,797 ( 0.00%) fn lifetime_or_char(&mut self) -> TokenKind { . debug_assert!(self.prev() == '\''); . 3,942 ( 0.00%) let can_be_a_lifetime = if self.second() == '\'' { . // It's surely not a lifetime. . false . } else { . // If the first symbol is valid for identifier, it can be a lifetime. . // Also check if it's a number for a better error reporting (so '0 will . // be reported as invalid lifetime and not as unterminated char literal). . is_id_start(self.first()) || self.first().is_digit(10) . }; . 1,882 ( 0.00%) if !can_be_a_lifetime { 5,838 ( 0.00%) let terminated = self.single_quoted_string(); . let suffix_start = self.len_consumed(); 3,892 ( 0.00%) if terminated { . self.eat_literal_suffix(); . } . let kind = Char { terminated }; 7,784 ( 0.00%) return Literal { kind, suffix_start }; . } . . // Either a lifetime or a character literal with . // length greater than 1. . . let starts_with_number = self.first().is_digit(10); . . // Skip the literal contents. . // First symbol can be a number (which isn't a valid identifier start), . // so skip it without any checks. . self.bump(); 50 ( 0.00%) self.eat_while(is_id_continue); . . // Check if after skipping literal contents we've met a closing . // single quote (which means that user attempted to create a . // string with single quotes). 50 ( 0.00%) if self.first() == '\'' { . self.bump(); . let kind = Char { terminated: true }; . Literal { kind, suffix_start: self.len_consumed() } . } else { 50 ( 0.00%) Lifetime { starts_with_number } . } 11,826 ( 0.00%) } . . fn single_quoted_string(&mut self) -> bool { . debug_assert!(self.prev() == '\''); . // Check if it's a one-symbol literal. 4,064 ( 0.00%) if self.second() == '\'' && self.first() != '\\' { . self.bump(); . self.bump(); . return true; . } . . // Literal has more than one symbol. . . // Parse until either quotes are terminated or error is detected. . loop { 89,762 ( 0.00%) match self.first() { . // Quotes are terminated, finish parsing. . '\'' => { . self.bump(); . return true; . } . // Probably beginning of the comment, which we don't want to include . // to the error report. . '/' => break, -- line 660 ---------------------------------------- -- line 670 ---------------------------------------- . // Skip the character. . _ => { . self.bump(); . } . } . } . // String was not terminated. . false 1,957 ( 0.00%) } . . /// Eats double-quoted string and returns true . /// if string is terminated. . fn double_quoted_string(&mut self) -> bool { . debug_assert!(self.prev() == '"'); . while let Some(c) = self.bump() { 232,267 ( 0.01%) match c { . '"' => { . return true; . } 42,452 ( 0.00%) '\\' if self.first() == '\\' || self.first() == '"' => { . // Bump again to skip escaped character. . self.bump(); . } . _ => (), . } . } . // End of file reached. . false 20 ( 0.00%) } . . /// Eats the double-quoted string and returns `n_hashes` and an error if encountered. . fn raw_double_quoted_string(&mut self, prefix_len: usize) -> (u16, Option) { . // Wrap the actual function to handle the error with too many hashes. . // This way, it eats the whole raw string. . let (n_hashes, err) = self.raw_string_unvalidated(prefix_len); . // Only up to 65535 `#`s are allowed in raw strings . match u16::try_from(n_hashes) { -- line 706 ---------------------------------------- -- line 773 ---------------------------------------- . max_hashes = n_end_hashes; . } . } . } . . fn eat_decimal_digits(&mut self) -> bool { . let mut has_digits = false; . loop { 74,366 ( 0.00%) match self.first() { . '_' => { . self.bump(); . } 111,549 ( 0.00%) '0'..='9' => { . has_digits = true; . self.bump(); . } . _ => break, . } . } . has_digits 36,572 ( 0.00%) } . . fn eat_hexadecimal_digits(&mut self) -> bool { . let mut has_digits = false; . loop { 6 ( 0.00%) match self.first() { . '_' => { . self.bump(); . } 12 ( 0.00%) '0'..='9' | 'a'..='f' | 'A'..='F' => { . has_digits = true; . self.bump(); . } . _ => break, . } . } . has_digits 2 ( 0.00%) } . . /// Eats the float exponent. Returns true if at least one digit was met, . /// and returns false otherwise. . fn eat_float_exponent(&mut self) -> bool { . debug_assert!(self.prev() == 'e' || self.prev() == 'E'); . if self.first() == '-' || self.first() == '+' { . self.bump(); . } . self.eat_decimal_digits() . } . . // Eats the suffix of the literal, e.g. "_u8". . fn eat_literal_suffix(&mut self) { 42,816 ( 0.00%) self.eat_identifier(); . } . . // Eats the identifier. 64,224 ( 0.00%) fn eat_identifier(&mut self) { . if !is_id_start(self.first()) { . return; . } . self.bump(); . . self.eat_while(is_id_continue); 85,632 ( 0.00%) } . } 2,297,483 ( 0.09%) -------------------------------------------------------------------------------- -- 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> { 402,550 ( 0.02%) 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. 8 ( 0.00%) fn from_attr(cx: &C, ity: attr::IntType) -> Integer { . let dl = cx.data_layout(); . 20 ( 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) => { . dl.ptr_sized_integer() . } . } 8 ( 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, 358 ( 0.00%) ty::IntTy::Isize => cx.data_layout().ptr_sized_integer(), . } . } . fn from_uint_ty(cx: &C, ity: ty::UintTy) -> Integer { 360 ( 0.00%) match ity { . ty::UintTy::U8 => I8, . ty::UintTy::U16 => I16, . ty::UintTy::U32 => I32, . ty::UintTy::U64 => I64, . ty::UintTy::U128 => I128, 2 ( 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. 6 ( 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)); . 24 ( 0.00%) if let Some(ity) = repr.int { . let discr = Integer::from_attr(&tcx, ity); 6 ( 0.00%) let fit = if ity.is_signed() { signed_fit } else { unsigned_fit }; 2 ( 0.00%) if discr < fit { . bug!( . "Integer::repr_discr: `#[repr]` hint too small for \ . discriminant range of enum `{}", . ty . ) . } . return (discr, ity.is_signed()); . } -- line 132 ---------------------------------------- -- line 141 ---------------------------------------- . }; . . // If there are no negative values, we can use the unsigned fit. . if min >= 0 { . (cmp::max(unsigned_fit, at_least), false) . } else { . (cmp::max(signed_fit, at_least), true) . } 8 ( 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> { 338,142 ( 0.01%) 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. . /// Useful in particular when dealing with enum discriminants. . #[inline] . fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 193,224 ( 0.01%) match *self { 96,612 ( 0.00%) Int(i, signed) => i.to_ty(tcx, signed), . Pointer => tcx.types.usize, . F32 | F64 => bug!("floats do not have an int type"), . } . } . } . . /// The first half of a fat pointer. . /// -- line 181 ---------------------------------------- -- line 215 ---------------------------------------- . "unable to determine layout for `{}` because `{}` cannot be normalized", . t, . e.get_type_for_failure() . ), . } . } . } . 656 ( 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| { 41 ( 0.00%) let (param_env, ty) = query.into_parts(); . debug!(?ty); . 164 ( 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 369 ( 0.00%) let icx = ty::tls::ImplicitCtxt { layout_depth: icx.layout_depth + 1, ..icx.clone() }; . . ty::tls::enter_context(&icx, |_| { 123 ( 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)); . } . }; . 41 ( 0.00%) if ty != unnormalized_ty { . // Ensure this layout is also cached for the normalized type. . return tcx.layout_of(param_env.and(ty)); . } . 144 ( 0.00%) let cx = LayoutCx { tcx, param_env }; . 108 ( 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. 36 ( 0.00%) if tcx.conservative_is_privately_uninhabited(param_env.and(ty)) { . assert!(layout.abi.is_uninhabited()); . } . 108 ( 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() { 48 ( 0.00%) inverse[map[i] as usize] = i as u32; . } . inverse . } . . impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> { 90 ( 0.00%) fn scalar_pair(&self, a: Scalar, b: Scalar) -> Layout { . let dl = self.data_layout(); 70 ( 0.00%) let b_align = b.value.align(dl); 80 ( 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. 120 ( 0.00%) let largest_niche = Niche::from_scalar(dl, b_offset, b) . .into_iter() 100 ( 0.00%) .chain(Niche::from_scalar(dl, Size::ZERO, a)) . .max_by_key(|niche| niche.available(dl)); . 190 ( 0.00%) Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, . fields: FieldsShape::Arbitrary { 20 ( 0.00%) offsets: vec![Size::ZERO, b_offset], 20 ( 0.00%) memory_index: vec![0, 1], . }, 130 ( 0.00%) abi: Abi::ScalarPair(a, b), 100 ( 0.00%) largest_niche, . align, . size, . } 80 ( 0.00%) } . 252 ( 0.00%) fn univariant_uninterned( . &self, . ty: Ty<'tcx>, . fields: &[TyAndLayout<'_>], . repr: &ReprOptions, . kind: StructKind, . ) -> Result> { . let dl = self.data_layout(); 84 ( 0.00%) let pack = repr.pack; 21 ( 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)); . } . 84 ( 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(); 21 ( 0.00%) if optimize { . let end = 35 ( 0.00%) if let StructKind::MaybeUnsized = kind { fields.len() - 1 } else { fields.len() }; . let optimizing = &mut inverse_memory_index[..end]; 5 ( 0.00%) let field_align = |f: &TyAndLayout<'_>| { 32 ( 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 { 10 ( 0.00%) match kind { . StructKind::AlwaysSized | StructKind::MaybeUnsized => { 25 ( 0.00%) optimizing.sort_by_key(|&x| { . // Place ZSTs first to avoid "interesting offsets", . // especially with only one or two non-ZST fields. 28 ( 0.00%) let f = &fields[x as usize]; 4 ( 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 . optimizing.sort_by_key(|&x| field_align(&fields[x as usize])); . } -- line 386 ---------------------------------------- -- 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; . 63 ( 0.00%) if let StructKind::Prefixed(prefix_size, prefix_align) = kind { . let prefix_align = 112 ( 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); . } . 18 ( 0.00%) for &i in &inverse_memory_index { 229 ( 0.00%) let field = fields[i as usize]; 36 ( 0.00%) if !sized { . self.tcx.sess.delay_span_bug( . DUMMY_SP, . &format!( . "univariant: field #{} of `{}` comes after unsized field", . offsets.len(), . ty . ), . ); . } . 90 ( 0.00%) if field.is_unsized() { . sized = false; . } . . // Invariant: offset < dl.obj_size_bound() <= 1<<61 36 ( 0.00%) let field_align = if let Some(pack) = pack { . field.align.min(AbiAndPrefAlign::new(pack)) . } else { 54 ( 0.00%) field.align . }; . offset = offset.align_to(field_align.abi); . align = align.max(field_align); . . debug!("univariant offset: {:?} field: {:#?}", offset, field); 36 ( 0.00%) offsets[i as usize] = offset; . 18 ( 0.00%) if !repr.hide_niche() { 93 ( 0.00%) if let Some(mut niche) = field.largest_niche { . let available = niche.available(dl); 12 ( 0.00%) if available > largest_niche_available { . largest_niche_available = available; . niche.offset += offset; 48 ( 0.00%) largest_niche = Some(niche); . } . } . } . 18 ( 0.00%) offset = offset.checked_add(field.size, dl).ok_or(LayoutError::SizeOverflow(ty))?; . } . 53 ( 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 = 154 ( 0.00%) if optimize { invert_mapping(&inverse_memory_index) } else { inverse_memory_index }; . . let size = min_size.align_to(align.abi); 42 ( 0.00%) let mut abi = Abi::Aggregate { sized }; . . // Unpack newtype ABIs and find scalar pairs. 84 ( 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()); . 18 ( 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. 24 ( 0.00%) if offsets[i].bytes() == 0 && align.abi == field.align.abi && size == field.size . { . match field.abi { . // For plain scalars, or vectors of them, we can't unpack . // newtypes for `#[repr(C)]`, as that affects C ABIs. . Abi::Scalar(_) | Abi::Vector { .. } if optimize => { . abi = field.abi; . } . // But scalar pairs are Rust-specific and get -- line 494 ---------------------------------------- -- 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. 27 ( 0.00%) let ((i, a), (j, b)) = 21 ( 0.00%) if offsets[i] < offsets[j] { ((i, a), (j, b)) } else { ((j, b), (i, a)) }; 33 ( 0.00%) let pair = self.scalar_pair(a, b); 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!(), . }; 27 ( 0.00%) if offsets[i] == pair_offsets[0] 3 ( 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)]`). 42 ( 0.00%) abi = pair.abi; . } 3 ( 0.00%) } . . _ => {} . } . } . 18 ( 0.00%) if fields.iter().any(|f| f.abi.is_uninhabited()) { . abi = Abi::Uninhabited; . } . 672 ( 0.00%) Ok(Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, 210 ( 0.00%) fields: FieldsShape::Arbitrary { offsets, memory_index }, . abi, 231 ( 0.00%) largest_niche, . align, . size, . }) 210 ( 0.00%) } . 360 ( 0.00%) fn layout_of_uncached(&self, ty: Ty<'tcx>) -> Result<&'tcx Layout, LayoutError<'tcx>> { 72 ( 0.00%) let tcx = self.tcx; 36 ( 0.00%) let param_env = self.param_env; . let dl = self.data_layout(); 50 ( 0.00%) let scalar_unit = |value: Primitive| { 1 ( 0.00%) let size = value.size(dl); 54 ( 0.00%) assert!(size.bits() <= 128); 64 ( 0.00%) Scalar { value, valid_range: WrappingRange { start: 0, end: size.unsigned_int_max() } } 14 ( 0.00%) }; . let scalar = |value: Primitive| tcx.intern_layout(Layout::scalar(self, scalar_unit(value))); . . let univariant = |fields: &[TyAndLayout<'_>], repr: &ReprOptions, kind| { 63 ( 0.00%) Ok(tcx.intern_layout(self.univariant_uninterned(ty, fields, repr, kind)?)) . }; . debug_assert!(!ty.has_infer_types_or_consts()); . 278 ( 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 }, . }, . )), 10 ( 0.00%) ty::Int(ity) => scalar(Int(Integer::from_int_ty(dl, ity), true)), 40 ( 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. 10 ( 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); 80 ( 0.00%) if pointee.is_sized(tcx.at(DUMMY_SP), param_env) { 51 ( 0.00%) return Ok(tcx.intern_layout(Layout::scalar(self, data_ptr))); . } . 28 ( 0.00%) let unsized_part = tcx.struct_tail_erasing_lifetimes(pointee, param_env); 28 ( 0.00%) let metadata = match unsized_part.kind() { . ty::Foreign(..) => { . return Ok(tcx.intern_layout(Layout::scalar(self, data_ptr))); . } 48 ( 0.00%) ty::Slice(_) | ty::Str => scalar_unit(Int(dl.ptr_sized_integer(), false)), . ty::Dynamic(..) => { 2 ( 0.00%) let mut vtable = scalar_unit(Pointer); 2 ( 0.00%) vtable.valid_range = vtable.valid_range.with_start(1); 8 ( 0.00%) vtable . } . _ => return Err(LayoutError::Unknown(unsized_part)), . }; . . // Effectively a (ptr, meta) tuple. 147 ( 0.00%) tcx.intern_layout(self.scalar_pair(data_ptr, metadata)) . } . . // Arrays and slices. 6 ( 0.00%) ty::Array(element, mut count) => { 2 ( 0.00%) if count.has_projections() { . count = tcx.normalize_erasing_regions(param_env, count); . if count.has_projections() { . return Err(LayoutError::Unknown(ty)); . } . } . 8 ( 0.00%) let count = count.try_eval_usize(tcx, param_env).ok_or(LayoutError::Unknown(ty))?; 10 ( 0.00%) let element = self.layout_of(element)?; . let size = 10 ( 0.00%) element.size.checked_mul(count, dl).ok_or(LayoutError::SizeOverflow(ty))?; . . let abi = 16 ( 0.00%) if count != 0 && tcx.conservative_is_privately_uninhabited(param_env.and(ty)) { . Abi::Uninhabited . } else { . Abi::Aggregate { sized: true } . }; . 22 ( 0.00%) let largest_niche = if count != 0 { element.largest_niche } else { None }; . 44 ( 0.00%) tcx.intern_layout(Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, 2 ( 0.00%) fields: FieldsShape::Array { stride: element.size, count }, . abi, . largest_niche, 2 ( 0.00%) align: element.align, . size, . }) . } 4 ( 0.00%) ty::Slice(element) => { 6 ( 0.00%) let element = self.layout_of(element)?; 22 ( 0.00%) tcx.intern_layout(Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, 2 ( 0.00%) fields: FieldsShape::Array { stride: element.size, count: 0 }, . abi: Abi::Aggregate { sized: false }, . largest_niche: None, 2 ( 0.00%) align: element.align, . size: Size::ZERO, . }) . } 6 ( 0.00%) 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, 1 ( 0.00%) align: dl.i8_align, . size: Size::ZERO, . }), . . // Odd unit types. . ty::FnDef(..) => univariant(&[], &ReprOptions::default(), StructKind::AlwaysSized)?, . ty::Dynamic(..) | ty::Foreign(..) => { . let mut unit = self.univariant_uninterned( . ty, -- line 687 ---------------------------------------- -- line 702 ---------------------------------------- . let tys = substs.as_closure().upvar_tys(); . univariant( . &tys.map(|ty| self.layout_of(ty)).collect::, _>>()?, . &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. 8 ( 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. 8 ( 0.00%) ty::Adt(def, substs) => { . // Cache the field layouts. 8 ( 0.00%) let variants = def . .variants . .iter() . .map(|v| { . v.fields . .iter() 92 ( 0.00%) .map(|field| self.layout_of(field.ty(tcx, substs))) . .collect::, _>>() . }) . .collect::, _>>()?; . 4 ( 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<'_>]| { 6 ( 0.00%) let uninhabited = fields.iter().any(|f| f.abi.is_uninhabited()); . let is_zst = fields.iter().all(|f| f.is_zst()); . uninhabited && is_zst . }; . let (present_first, present_second) = { . let mut present_variants = variants . .iter_enumerated() 24 ( 0.00%) .filter_map(|(i, v)| if absent(v) { None } else { Some(i) }); . (present_variants.next(), present_variants.next()) . }; 8 ( 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), . }; . 4 ( 0.00%) let is_struct = !def.is_enum() || . // Only one variant is present. 2 ( 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; 2 ( 0.00%) let kind = if def.is_enum() || variants[v].is_empty() { . StructKind::AlwaysSized . } else { 6 ( 0.00%) let param_env = tcx.param_env(def.did); 2 ( 0.00%) let last_field = def.variants[v].fields.last().unwrap(); . let always_sized = 12 ( 0.00%) tcx.type_of(last_field.did).is_sized(tcx.at(DUMMY_SP), param_env); 4 ( 0.00%) if !always_sized { . StructKind::MaybeUnsized . } else { . StructKind::AlwaysSized . } . }; . 26 ( 0.00%) let mut st = self.univariant_uninterned(ty, &variants[v], &def.repr, kind)?; 10 ( 0.00%) st.variants = Variants::Single { index: v }; 14 ( 0.00%) let (start, end) = self.tcx.layout_scalar_valid_range(def.did); 8 ( 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 -- line 985 ---------------------------------------- -- line 1013 ---------------------------------------- . st.largest_niche = Some(niche); . } . } . None => st.largest_niche = Some(niche), . } . } . } . _ => assert!( 6 ( 0.00%) start == Bound::Unbounded && end == Bound::Unbounded, . "nonscalar layout for layout_scalar_valid_range type {:?}: {:#?}", . def, . st, . ), . } . 18 ( 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())); . 4 ( 0.00%) let mut niche_filling_layout = None; . . // Niche-filling enum optimization. 4 ( 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. . 'variants: for (v, fields) in variants.iter_enumerated() { . if absent(fields) { . continue 'variants; . } -- line 1055 ---------------------------------------- -- line 1151 ---------------------------------------- . largest_niche, . size, . align, . }); . } . } . } . 10 ( 0.00%) let (mut min, mut max) = (i128::MAX, i128::MIN); 16 ( 0.00%) let discr_type = def.repr.discr_type(); 6 ( 0.00%) let bits = Integer::from_attr(self, discr_type).size().bits(); 38 ( 0.00%) for (i, discr) in def.discriminants(tcx) { 6 ( 0.00%) if variants[i].iter().any(|f| f.abi.is_uninhabited()) { . continue; . } . let mut x = discr.val as i128; 16 ( 0.00%) if discr_type.is_signed() { . // sign extend the raw representation to be an i128 . x = (x << (128 - bits)) >> (128 - bits); . } 64 ( 0.00%) if x < min { 8 ( 0.00%) min = x; . } 64 ( 0.00%) if x > max { 48 ( 0.00%) max = x; . } . } . // We might have no inhabited variants, so pretend there's at least one. 2 ( 0.00%) if (min, max) == (i128::MAX, i128::MIN) { . min = 0; . max = 0; . } 10 ( 0.00%) assert!(min <= max, "discriminant range is {}...{}", min, max); 18 ( 0.00%) let (min_ity, signed) = Integer::repr_discr(tcx, ty, &def.repr, min, max); . 4 ( 0.00%) let mut align = dl.aggregate_align; 2 ( 0.00%) let mut size = Size::ZERO; . . // We're interested in the smallest alignment, so start large. 4 ( 0.00%) let mut start_align = Align::from_bytes(256).unwrap(); 10 ( 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.) 26 ( 0.00%) let mut prefix_align = min_ity.align(dl).abi; 2 ( 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. 4 ( 0.00%) let mut layout_variants = variants . .iter_enumerated() . .map(|(i, field_layouts)| { 304 ( 0.00%) let mut st = self.univariant_uninterned( 16 ( 0.00%) ty, . &field_layouts, 32 ( 0.00%) &def.repr, 64 ( 0.00%) StructKind::Prefixed(min_ity.size(), prefix_align), . )?; 48 ( 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 220 ( 0.00%) st.fields.index_by_increasing_offset().map(|j| field_layouts[j]) . { 6 ( 0.00%) if !field.is_zst() || field.align.abi.bytes() != 1 { 12 ( 0.00%) start_align = start_align.min(field.align.abi); . break; . } . } 64 ( 0.00%) size = cmp::max(size, st.size); 48 ( 0.00%) align = align.max(st.align); 96 ( 0.00%) Ok(st) . }) . .collect::, _>>()?; . . // Align the maximum variant size to the largest alignment. 10 ( 0.00%) size = size.align_to(align.abi); . 8 ( 0.00%) if size.bytes() >= dl.obj_size_bound() { . return Err(LayoutError::SizeOverflow(ty)); . } . 8 ( 0.00%) let typeck_ity = Integer::from_attr(dl, def.repr.discr_type()); 6 ( 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 6 ( 0.00%) let mut ity = if def.repr.c() || def.repr.int.is_some() { . min_ity . } else { . 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. . if ity <= min_ity { -- line 1279 ---------------------------------------- -- line 1296 ---------------------------------------- . variant.size = new_ity_size; . } . } . _ => bug!(), . } . } . } . 2 ( 0.00%) let tag_mask = ity.size().unsigned_int_max(); . let tag = Scalar { . value: Int(ity, signed), . valid_range: WrappingRange { 10 ( 0.00%) start: (min as u128 & tag_mask), 8 ( 0.00%) end: (max as u128 & tag_mask), . }, . }; . let mut abi = Abi::Aggregate { sized: true }; 12 ( 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; . } . }; 6 ( 0.00%) let prim = match field.abi { . Abi::Scalar(scalar) => scalar.value, . _ => { . common_prim = None; . break; . } . }; . if let Some(pair) = common_prim { . // This is pretty conservative. We could go fancier -- line 1341 ---------------------------------------- -- line 1370 ---------------------------------------- . } . } . } . . if layout_variants.iter().all(|v| v.abi.is_uninhabited()) { . abi = Abi::Uninhabited; . } . 32 ( 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 { 10 ( 0.00%) offsets: vec![Size::ZERO], 8 ( 0.00%) memory_index: vec![0], . }, . largest_niche, . abi, 4 ( 0.00%) align, 2 ( 0.00%) size, . }; . 6 ( 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)) . }) . } 122 ( 0.00%) (tagged_layout, None) => tagged_layout, . }; . 18 ( 0.00%) tcx.intern_layout(best_layout) 8 ( 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)); . } . }) 288 ( 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. 180 ( 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 { 597,686 ( 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> { 18 ( 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> { 18 ( 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 { 192,592 ( 0.01%) 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] 513,094 ( 0.02%) fn layout_of(&self, ty: Ty<'tcx>) -> Self::LayoutOfResult { . self.spanned_layout_of(ty, DUMMY_SP) 513,088 ( 0.02%) } . . /// 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 2216 ---------------------------------------- . err . } . } . . impl<'tcx, C> TyAbiInterface<'tcx, C> for Ty<'tcx> . where . C: HasTyCtxt<'tcx> + HasParamEnv<'tcx>, . { 380,320 ( 0.02%) fn ty_and_layout_for_variant( . this: TyAndLayout<'tcx>, . cx: &C, . variant_index: VariantIdx, . ) -> TyAndLayout<'tcx> { 76,064 ( 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], . }; . 304,256 ( 0.01%) assert_eq!(layout.variants, Variants::Single { index: variant_index }); . . TyAndLayout { ty: this.ty, layout } 380,320 ( 0.02%) } . 2,619,120 ( 0.10%) fn ty_and_layout_field(this: TyAndLayout<'tcx>, cx: &C, i: usize) -> TyAndLayout<'tcx> { . enum TyMaybeWithLayout<'tcx> { . Ty(Ty<'tcx>), . TyAndLayout(TyAndLayout<'tcx>), . } . 2,095,296 ( 0.08%) 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> { 901,712 ( 0.04%) let layout = Layout::scalar(cx, tag); 732,641 ( 0.03%) TyAndLayout { layout: tcx.intern_layout(layout), ty: tag.value.to_ty(tcx) } . }; . 523,824 ( 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 2350 ---------------------------------------- . */ . } . _ => bug!("TyAndLayout::field({:?}): not applicable", this), . } . } . . // Arrays and slices. . ty::Array(element, _) | ty::Slice(element) => TyMaybeWithLayout::Ty(element), 8 ( 0.00%) ty::Str => TyMaybeWithLayout::Ty(tcx.types.u8), . . // Tuples, generators and closures. . ty::Closure(_, ref substs) => field_ty_or_layout( . TyAndLayout { ty: substs.as_closure().tupled_upvars_ty(), ..this }, . cx, . i, . ), . -- line 2366 ---------------------------------------- -- 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()) . } . }, . 60,232 ( 0.00%) ty::Tuple(tys) => TyMaybeWithLayout::Ty(tys[i].expect_ty()), . . // ADTs. 93,248 ( 0.00%) ty::Adt(def, substs) => { 299,210 ( 0.01%) match this.variants { 93,248 ( 0.00%) Variants::Single { index } => { 372,992 ( 0.01%) TyMaybeWithLayout::Ty(def.variants[index].fields[i].ty(tcx, substs)) . } . . // Discriminant field for enums (where applicable). . Variants::Multiple { tag, .. } => { 112,714 ( 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), . } 1,571,472 ( 0.06%) } . 698,432 ( 0.03%) match field_ty_or_layout(this, cx, i) { 236,502 ( 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 . ) . }) . } 169,071 ( 0.01%) TyMaybeWithLayout::TyAndLayout(field_layout) => field_layout, . } 1,396,864 ( 0.06%) } . . 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 ---------------------------------------- 573,286 ( 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);)*) => { 32,126 ( 0.00%) $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> { . self.opaque.$name(value) 38,552 ( 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 { 466 ( 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)?; 134 ( 0.00%) if self.meta == 0 { . return Ok(()); . } 352 ( 0.00%) e.emit_lazy_distance(*self) . } . } . . 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 { 1,561 ( 0.00%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 2,568 ( 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()) 1,338 ( 0.00%) } . } . . impl<'a, 'tcx> Encodable> for DefIndex { 1,105 ( 0.00%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . s.emit_u32(self.as_u32()) 1,326 ( 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 { 443,920 ( 0.02%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 266,352 ( 0.01%) rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s) 532,704 ( 0.02%) } . } . . impl<'a, 'tcx> Encodable> for ExpnId { . fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 190 ( 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. 640 ( 0.00%) s.hygiene_ctxt.schedule_expn_data_for_encoding(*self); . } 435 ( 0.00%) self.krate.encode(s)?; . self.local_id.encode(s) . } . } . . impl<'a, 'tcx> Encodable> for Span { 710,056 ( 0.03%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 532,542 ( 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. 177,514 ( 0.01%) if s.is_proc_macro { . SyntaxContext::root().encode(s)?; . } else { 88,757 ( 0.00%) span.ctxt.encode(s)?; . } . 88,757 ( 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); . 443,586 ( 0.02%) if !s.source_file_cache.0.contains(span.lo) { 94 ( 0.00%) let source_map = s.tcx.sess.source_map(); 188 ( 0.00%) let source_file_index = source_map.lookup_source_file_idx(span.lo); 94 ( 0.00%) s.source_file_cache = 188 ( 0.00%) (source_map.files()[source_file_index].clone(), source_file_index); . } . 266,366 ( 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` 88,726 ( 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. 532,356 ( 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' . // Span that can be used without any additional trouble. . let external_start_pos = { . // Introduce a new scope so that we drop the 'lock()' temporary 42 ( 0.00%) match &*s.source_file_cache.0.external_src.lock() { 14 ( 0.00%) ExternalSource::Foreign { original_start_pos, .. } => *original_start_pos, . src => panic!("Unexpected external source {:?}", src), . } . }; 42 ( 0.00%) let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos; 14 ( 0.00%) let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos; . . (TAG_VALID_SPAN_FOREIGN, lo, hi) . } else { 266,136 ( 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)?; . 177,452 ( 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)` 56 ( 0.00%) let cnum = s.source_file_cache.0.cnum; 42 ( 0.00%) cnum.encode(s)?; . } . . Ok(()) 710,056 ( 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 { 1,524 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { 666 ( 0.00%) self.encode(ecx).unwrap() . } . } . . impl<'a, 'tcx, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, T> for T { 3,274 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { 1,874 ( 0.00%) self.encode(ecx).unwrap() 1,953 ( 0.00%) } . } . . impl<'a, 'tcx, I, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, [T]> for I . where . I: IntoIterator, . I::Item: EncodeContentsForLazy<'a, 'tcx, T>, . { 224 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize { 618 ( 0.00%) self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count() 288 ( 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> { 870 ( 0.00%) fn emit_lazy_distance( . &mut self, . lazy: Lazy, . ) -> Result<(), ::Error> { . let pos = lazy.position.get(); 612 ( 0.00%) let distance = match self.lazy_state { . LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"), 129 ( 0.00%) LazyState::NodeStart(start) => { . let start = start.get(); 258 ( 0.00%) assert!(pos <= start); . start - pos . } 45 ( 0.00%) LazyState::Previous(last_pos) => { 45 ( 0.00%) assert!( . last_pos <= lazy.position, . "make sure that the calls to `lazy*` \ . are in the same order as the metadata fields", . ); 135 ( 0.00%) lazy.position.get() - last_pos.get() . } . }; 348 ( 0.00%) self.lazy_state = LazyState::Previous(NonZeroUsize::new(pos).unwrap()); . self.emit_usize(distance) 870 ( 0.00%) } . 1,874 ( 0.00%) fn lazy( . &mut self, . value: impl EncodeContentsForLazy<'a, 'tcx, T>, . ) -> Lazy { . let pos = NonZeroUsize::new(self.position()).unwrap(); . 2,229 ( 0.00%) assert_eq!(self.lazy_state, LazyState::NoNode); 6,551 ( 0.00%) self.lazy_state = LazyState::NodeStart(pos); 4,581 ( 0.00%) let meta = value.encode_contents_for_lazy(self); 2,671 ( 0.00%) self.lazy_state = LazyState::NoNode; . 4,607 ( 0.00%) assert!(pos.get() <= self.position()); . . Lazy::from_position_and_meta(pos, meta) 2,737 ( 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); 824 ( 0.00%) self.tables.def_keys.set(def_index, def_key); 824 ( 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` 1,175 ( 0.00%) required_source_files.contains(*idx) && . // Don't serialize imported `SourceFile`s, unless . // we're in a proc-macro crate. 52 ( 0.00%) (!source_file.is_imported() || self.is_proc_macro) . }) . .map(|(_, source_file)| { 12 ( 0.00%) let mut adapted = match source_file.name { . FileName::Real(ref realname) => { 8 ( 0.00%) let mut adapted = (**source_file).clone(); 64 ( 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. 8 ( 0.00%) let working_dir = &self.tcx.sess.opts.working_dir; 8 ( 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); 28 ( 0.00%) let (joined, remapped) = 44 ( 0.00%) source_map.path_mapping().map_prefix(joined); 8 ( 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(), . } . } . }); 8 ( 0.00%) adapted.name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 4 ( 0.00%) adapted.name.hash(&mut hasher); . hasher.finish::() . }; 4 ( 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. 8 ( 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. 621 ( 0.00%) fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) { 345 ( 0.00%) match tcx.def_kind(def_id) { . // Constructors . DefKind::Ctor(_, _) => { 18 ( 0.00%) 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); 250 ( 0.00%) let needs_inline = (generics.requires_monomorphization(tcx) 82 ( 0.00%) || tcx.codegen_fn_attrs(def_id).requests_inline()) 42 ( 0.00%) && tcx.sess.opts.output_types.should_codegen(); . // The function has a `const` modifier or is annotated with `default_method_body_is_const`. 42 ( 0.00%) let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id()) 210 ( 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; 84 ( 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); 44 ( 0.00%) let needs_inline = (generics.requires_monomorphization(tcx) . || tcx.codegen_fn_attrs(def_id).requests_inline()) 22 ( 0.00%) && tcx.sess.opts.output_types.should_codegen(); 22 ( 0.00%) let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir; 22 ( 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), . } 621 ( 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); 1,236 ( 0.00%) let def_kind = if let Some(def_kind) = def_kind { def_kind } else { continue }; 2,880 ( 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, . }); 540 ( 0.00%) record!(self.tables.span[def_id] <- tcx.def_span(def_id)); 2,160 ( 0.00%) record!(self.tables.attributes[def_id] <- tcx.get_attrs(def_id)); 1,440 ( 0.00%) record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id)); . if should_encode_visibility(def_kind) { 948 ( 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); 840 ( 0.00%) self.encode_deprecation(def_id); . } . if should_encode_variances(def_kind) { 132 ( 0.00%) let v = self.tcx.variances_of(def_id); 462 ( 0.00%) record!(self.tables.variances[def_id] <- v); . } . if should_encode_generics(def_kind) { . let g = tcx.generics_of(def_id); 592 ( 0.00%) record!(self.tables.generics[def_id] <- g); 1,776 ( 0.00%) record!(self.tables.explicit_predicates[def_id] <- self.tcx.explicit_predicates_of(def_id)); 148 ( 0.00%) let inferred_outlives = self.tcx.inferred_outlives_of(def_id); 157 ( 0.00%) if !inferred_outlives.is_empty() { . record!(self.tables.inferred_outlives[def_id] <- inferred_outlives); . } . } 1,260 ( 0.00%) if let DefKind::Trait | DefKind::TraitAlias = def_kind { . 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() { 4 ( 0.00%) if implementations.is_empty() { . continue; . } 36 ( 0.00%) record!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| { 4 ( 0.00%) assert!(def_id.is_local()); . def_id.index . })); . } . } . 1,029 ( 0.00%) fn encode_item_type(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_item_type({:?})", def_id); 882 ( 0.00%) record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id)); 1,176 ( 0.00%) } . . fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) { . let tcx = self.tcx; . let variant = &def.variants[index]; 32 ( 0.00%) let def_id = variant.def_id; . debug!("EncodeContext::encode_enum_variant_info({:?})", def_id); . 48 ( 0.00%) let data = VariantData { 8 ( 0.00%) ctor_kind: variant.ctor_kind, . discr: variant.discr, 8 ( 0.00%) ctor: variant.ctor_def_id.map(|did| did.index), 8 ( 0.00%) is_non_exhaustive: variant.is_field_list_non_exhaustive(), . }; . . record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data))); . record!(self.tables.children[def_id] <- variant.fields.iter().map(|f| { 3 ( 0.00%) assert!(f.did.is_local()); . f.did.index . })); 8 ( 0.00%) self.encode_ident_span(def_id, variant.ident(tcx)); 8 ( 0.00%) self.encode_item_type(def_id); 8 ( 0.00%) if variant.ctor_kind == CtorKind::Fn { . // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`. 12 ( 0.00%) if let Some(ctor_def_id) = variant.ctor_def_id { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id)); . } . } . } . . fn encode_enum_variant_ctor(&mut self, def: &ty::AdtDef, index: VariantIdx) { . let tcx = self.tcx; . let variant = &def.variants[index]; 40 ( 0.00%) let def_id = variant.ctor_def_id.unwrap(); . debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id); . . // FIXME(eddyb) encode only the `CtorKind` for constructors. . let data = VariantData { 8 ( 0.00%) ctor_kind: variant.ctor_kind, . discr: variant.discr, . ctor: Some(def_id.index), 8 ( 0.00%) is_non_exhaustive: variant.is_field_list_non_exhaustive(), . }; . 32 ( 0.00%) record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data))); 24 ( 0.00%) self.encode_item_type(def_id); 8 ( 0.00%) 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() 390 ( 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]; . let field = &variant.fields[field_index]; . . let def_id = field.did; . debug!("EncodeContext::encode_field({:?})", def_id); . . record!(self.tables.kind[def_id] <- EntryKind::Field); 72 ( 0.00%) self.encode_ident_span(def_id, field.ident(self.tcx)); 108 ( 0.00%) self.encode_item_type(def_id); . } . . fn encode_struct_ctor(&mut self, adt_def: &ty::AdtDef, def_id: DefId) { . debug!("EncodeContext::encode_struct_ctor({:?})", def_id); . let tcx = self.tcx; . let variant = adt_def.non_enum_variant(); . . let data = VariantData { -- line 1150 ---------------------------------------- -- line 1234 ---------------------------------------- . } . 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); 56 ( 0.00%) let tcx = self.tcx; . 168 ( 0.00%) let ast_item = self.tcx.hir().expect_impl_item(def_id.expect_local()); 28 ( 0.00%) let impl_item = self.tcx.associated_item(def_id); . 112 ( 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)") . } . }; . 168 ( 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 => { 52 ( 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 26 ( 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)); . } . } 84 ( 0.00%) self.encode_ident_span(def_id, impl_item.ident(self.tcx)); 140 ( 0.00%) self.encode_item_type(def_id); 112 ( 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); . } 28 ( 0.00%) if impl_item.kind == ty::AssocKind::Fn { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . 128 ( 0.00%) fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> { 262 ( 0.00%) self.lazy(self.tcx.hir().body_param_names(body_id)) 128 ( 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| { 345 ( 0.00%) let (encode_const, encode_opt) = should_encode_mir(self.tcx, def_id); 255 ( 0.00%) if encode_const || encode_opt { 32 ( 0.00%) Some((def_id, encode_const, encode_opt)) . } else { . None . } 138 ( 0.00%) }) . .collect::>(); 85 ( 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); 16 ( 0.00%) if encode_opt { . record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id)); . } 16 ( 0.00%) if encode_const { 64 ( 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` 16 ( 0.00%) let abstract_const = self.tcx.thir_abstract_const(def_id); 64 ( 0.00%) if let Ok(Some(abstract_const)) = abstract_const { . record!(self.tables.thir_abstract_consts[def_id.to_def_id()] <- abstract_const); . } . } 64 ( 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())); 16 ( 0.00%) let unused = self.tcx.unused_generic_params(instance); 16 ( 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. 1,120 ( 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. 980 ( 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) . } . } . } . 840 ( 0.00%) fn encode_deprecation(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_deprecation({:?})", def_id); 700 ( 0.00%) if let Some(depr) = self.tcx.lookup_deprecation(def_id) { . record!(self.tables.deprecation[def_id] <- depr); . } 700 ( 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%) } . 522 ( 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); . 370 ( 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)) . } 32 ( 0.00%) hir::ItemKind::Fn(ref sig, .., body) => { . let data = FnData { 16 ( 0.00%) asyncness: sig.header.asyncness, 16 ( 0.00%) constness: sig.header.constness, 32 ( 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 . } 6 ( 0.00%) hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr), . hir::ItemKind::Struct(ref struct_def, _) => { 14 ( 0.00%) let adt_def = self.tcx.adt_def(def_id); 21 ( 0.00%) let variant = adt_def.non_enum_variant(); . . // Encode def_ids for each field and method . // for methods, write all the stuff get_trait_method . // needs to know 28 ( 0.00%) let ctor = struct_def . .ctor_hir_id() . .map(|ctor_hir_id| self.tcx.hir().local_def_id(ctor_hir_id).local_def_index); . . EntryKind::Struct( . self.lazy(VariantData { 7 ( 0.00%) ctor_kind: variant.ctor_kind, 28 ( 0.00%) discr: variant.discr, . ctor, . is_non_exhaustive: variant.is_field_list_non_exhaustive(), . }), 21 ( 0.00%) adt_def.repr, . ) . } . hir::ItemKind::Union(..) => { . let adt_def = self.tcx.adt_def(def_id); . let variant = adt_def.non_enum_variant(); . . EntryKind::Union( . self.lazy(VariantData { -- line 1461 ---------------------------------------- -- line 1462 ---------------------------------------- . ctor_kind: variant.ctor_kind, . discr: variant.discr, . ctor: None, . is_non_exhaustive: variant.is_field_list_non_exhaustive(), . }), . adt_def.repr, . ) . } 76 ( 0.00%) hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => { 68 ( 0.00%) let trait_ref = self.tcx.impl_trait_ref(def_id); 38 ( 0.00%) let polarity = self.tcx.impl_polarity(def_id); 38 ( 0.00%) let parent = if let Some(trait_ref) = trait_ref { 15 ( 0.00%) let trait_def = self.tcx.trait_def(trait_ref.def_id); 90 ( 0.00%) trait_def.ancestors(self.tcx, def_id).ok().and_then(|mut an| { 90 ( 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| { 90 ( 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 1518 ---------------------------------------- . } . 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. 280 ( 0.00%) match item.kind { . hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <- 2 ( 0.00%) self.tcx.adt_def(def_id).variants.iter().map(|v| { 8 ( 0.00%) assert!(v.def_id.is_local()); . v.def_id.index . }) . ), . hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => { . record!(self.tables.children[def_id] <- 21 ( 0.00%) self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| { 33 ( 0.00%) assert!(f.did.is_local()); . f.did.index . }) . ) . } . hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => { 38 ( 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| { 28 ( 0.00%) assert!(def_id.is_local()); . def_id.index . }) . ); . } . _ => {} . } 139 ( 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(..) 224 ( 0.00%) | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id), . _ => {} . } 168 ( 0.00%) if let hir::ItemKind::Fn(..) = item.kind { 64 ( 0.00%) record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } 128 ( 0.00%) if let hir::ItemKind::Impl { .. } = item.kind { 95 ( 0.00%) if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) { 75 ( 0.00%) record!(self.tables.impl_trait_ref[def_id] <- trait_ref); . } . } 448 ( 0.00%) } . . fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) { 3 ( 0.00%) record!(self.tables.kind[def_id] <- kind); 1 ( 0.00%) if encode_type { . self.encode_item_type(def_id); . } . } . . fn encode_info_for_closure(&mut self, hir_id: hir::HirId) { 66 ( 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. 33 ( 0.00%) let ty = self.tcx.typeck(def_id).node_type(hir_id); . 33 ( 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"), . } 44 ( 0.00%) self.encode_item_type(def_id.to_def_id()); 44 ( 0.00%) if let ty::Closure(def_id, substs) = *ty.kind() { 99 ( 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() { 32 ( 0.00%) expn_data_table.set(index.as_raw(), this.lazy(expn_data)); 32 ( 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 { 24 ( 0.00%) name: self.tcx.crate_name(cnum), 24 ( 0.00%) hash: self.tcx.crate_hash(cnum), 24 ( 0.00%) host_hash: self.tcx.crate_host_hash(cnum), 24 ( 0.00%) kind: self.tcx.dep_kind(cnum), 24 ( 0.00%) extra_filename: self.tcx.extra_filename(cnum), . }; 120 ( 0.00%) (cnum, dep) . }) . .collect::>(); . . { . // Sanity-check the crate numbers . let mut expected_cnum = 1; 48 ( 0.00%) for &(n, _) in &deps { 60 ( 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 9 ( 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() 135 ( 0.00%) .map(|(trait_def_id, mut impls)| { . // Bring everything into deterministic order for hashing 3 ( 0.00%) impls.sort_by_cached_key(|&(index, _)| { 9 ( 0.00%) tcx.hir().def_path_hash(LocalDefId { local_def_index: index }) . }); . 36 ( 0.00%) TraitImpls { . trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index), 27 ( 0.00%) impls: self.lazy(&impls), . } 72 ( 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 { 66 ( 0.00%) self.tcx.hir() . } 403,839 ( 0.02%) fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) { 44,871 ( 0.00%) intravisit::walk_expr(self, ex); . self.encode_info_for_expr(ex); 358,968 ( 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>) { 237 ( 0.00%) intravisit::walk_item(self, item); 158 ( 0.00%) match item.kind { . hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these 232 ( 0.00%) _ => self.encode_info_for_item(item.def_id.to_def_id(), item), . } 316 ( 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); . } 639 ( 0.00%) fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) { . intravisit::walk_generics(self, generics); . self.encode_info_for_generics(generics); 568 ( 0.00%) } . } . . impl<'a, 'tcx> EncodeContext<'a, 'tcx> { 56 ( 0.00%) 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); . } . } 64 ( 0.00%) } . . fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) { . for param in generics.params { 54 ( 0.00%) let def_id = self.tcx.hir().local_def_id(param.hir_id); 65 ( 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<'_>) { 89,742 ( 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. 711 ( 0.00%) fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) { 395 ( 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(..) . | hir::ItemKind::Use(..) . | hir::ItemKind::TyAlias(..) . | hir::ItemKind::OpaqueTy(..) . | hir::ItemKind::TraitAlias(..) => { . // no sub-item recording needed in these cases . } . hir::ItemKind::Enum(..) => { 1 ( 0.00%) let def = self.tcx.adt_def(item.def_id.to_def_id()); 2 ( 0.00%) self.encode_fields(def); . . for (i, variant) in def.variants.iter_enumerated() { . self.encode_enum_variant_info(def, i); . 24 ( 0.00%) if let Some(_ctor_def_id) = variant.ctor_def_id { . self.encode_enum_variant_ctor(def, i); . } . } . } . hir::ItemKind::Struct(ref struct_def, _) => { 7 ( 0.00%) let def = self.tcx.adt_def(item.def_id.to_def_id()); 14 ( 0.00%) self.encode_fields(def); . . // If the struct has a constructor, encode it. 28 ( 0.00%) if let Some(ctor_hir_id) = struct_def.ctor_hir_id() { . let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id); . 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 { .. } => { 112 ( 0.00%) for &trait_item_def_id in 19 ( 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(..) => { . 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); . } . } . } 632 ( 0.00%) } . } . . struct ImplsVisitor<'tcx> { . tcx: TyCtxt<'tcx>, . impls: FxHashMap)>>, . } . . impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplsVisitor<'tcx> { 553 ( 0.00%) fn visit_item(&mut self, item: &hir::Item<'_>) { 158 ( 0.00%) match item.kind { . hir::ItemKind::Impl(..) => { 68 ( 0.00%) if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id.to_def_id()) { 90 ( 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)); . } . } . _ => {} . } 632 ( 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<'_>) { 316 ( 0.00%) if let hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) = item.kind { . 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. . visitor.traits.sort_by_cached_key(|&def_id| tcx.def_path_hash(def_id)); . tcx.arena.alloc_slice(&visitor.traits) . }, . . ..*providers . }; . } -- line 2257 ---------------------------------------- 186,845 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/into_iter.rs -------------------------------------------------------------------------------- Ir -- line 51 ---------------------------------------- . /// let vec = vec!['a', 'b', 'c']; . /// let mut into_iter = vec.into_iter(); . /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']); . /// let _ = into_iter.next().unwrap(); . /// assert_eq!(into_iter.as_slice(), &['b', 'c']); . /// ``` . #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")] . pub fn as_slice(&self) -> &[T] { 3,138 ( 0.00%) unsafe { slice::from_raw_parts(self.ptr, self.len()) } . } . . /// Returns the remaining items of this iterator as a mutable slice. . /// . /// # Examples . /// . /// ``` . /// let vec = vec!['a', 'b', 'c']; -- line 67 ---------------------------------------- -- line 80 ---------------------------------------- . /// Returns a reference to the underlying allocator. . #[unstable(feature = "allocator_api", issue = "32838")] . #[inline] . pub fn allocator(&self) -> &A { . &self.alloc . } . . fn as_raw_mut_slice(&mut self) -> *mut [T] { 900,261 ( 0.04%) ptr::slice_from_raw_parts_mut(self.ptr as *mut T, self.len()) . } . . /// Drops remaining elements and relinquishes the backing allocation. . /// . /// This is roughly equivalent to the following, but more efficient . /// . /// ``` . /// # let mut into_iter = Vec::::with_capacity(10).into_iter(); -- line 96 ---------------------------------------- -- line 99 ---------------------------------------- . /// ``` . #[cfg(not(no_global_oom_handling))] . pub(super) fn forget_allocation_drop_remaining(&mut self) { . let remaining = self.as_raw_mut_slice(); . . // overwrite the individual fields instead of creating a new . // struct and then overwriting &mut self. . // this creates less assembly 205 ( 0.00%) self.cap = 0; 410 ( 0.00%) self.buf = unsafe { NonNull::new_unchecked(RawVec::NEW.ptr()) }; 274 ( 0.00%) self.ptr = self.buf.as_ptr(); 271 ( 0.00%) self.end = self.buf.as_ptr(); . . unsafe { . ptr::drop_in_place(remaining); . } . } . } . . #[stable(feature = "vec_intoiter_as_ref", since = "1.46.0")] -- line 118 ---------------------------------------- -- line 128 ---------------------------------------- . unsafe impl Sync for IntoIter {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for IntoIter { . type Item = T; . . #[inline] . fn next(&mut self) -> Option { 1,875,901 ( 0.07%) if self.ptr as *const _ == self.end { 55,614 ( 0.00%) None 90 ( 0.00%) } else if mem::size_of::() == 0 { . // purposefully don't use 'ptr.offset' because for . // vectors with 0-size elements this would return the . // same pointer. . self.ptr = unsafe { arith_offset(self.ptr as *const i8, 1) as *mut T }; . . // Make up a value of this ZST. . Some(unsafe { mem::zeroed() }) . } else { . let old = self.ptr; 243,678 ( 0.01%) self.ptr = unsafe { self.ptr.offset(1) }; . 160,851 ( 0.01%) Some(unsafe { ptr::read(old) }) . } 2 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { . let exact = if mem::size_of::() == 0 { . (self.end as usize).wrapping_sub(self.ptr as usize) . } else { . unsafe { self.end.offset_from(self.ptr) as usize } . }; 3 ( 0.00%) (exact, Some(exact)) . } . . #[inline] . fn advance_by(&mut self, n: usize) -> Result<(), usize> { . let step_size = self.len().min(n); . let to_drop = ptr::slice_from_raw_parts_mut(self.ptr as *mut T, step_size); . if mem::size_of::() == 0 { . // SAFETY: due to unchecked casts of unsigned amounts to signed offsets the wraparound -- line 169 ---------------------------------------- -- line 181 ---------------------------------------- . if step_size < n { . return Err(step_size); . } . Ok(()) . } . . #[inline] . fn count(self) -> usize { 2 ( 0.00%) self.len() . } . . #[doc(hidden)] . unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> Self::Item . where . Self: TrustedRandomAccessNoCoerce, . { . // SAFETY: the caller must guarantee that `i` is in bounds of the -- line 197 ---------------------------------------- -- line 207 ---------------------------------------- . } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl DoubleEndedIterator for IntoIter { . #[inline] . fn next_back(&mut self) -> Option { 30,162 ( 0.00%) if self.end == self.ptr { . None . } else if mem::size_of::() == 0 { . // See above for why 'ptr.offset' isn't used . self.end = unsafe { arith_offset(self.end as *const i8, -1) as *mut T }; . . // Make up a value of this ZST. . Some(unsafe { mem::zeroed() }) . } else { 814 ( 0.00%) self.end = unsafe { self.end.offset(-1) }; . 77 ( 0.00%) Some(unsafe { ptr::read(self.end) }) . } . } . . #[inline] . fn advance_back_by(&mut self, n: usize) -> Result<(), usize> { . let step_size = self.len().min(n); . if mem::size_of::() == 0 { . // SAFETY: same as for advance_by() -- line 234 ---------------------------------------- -- line 295 ---------------------------------------- . #[cfg(test)] . fn clone(&self) -> Self { . crate::slice::to_vec(self.as_slice(), self.alloc.clone()).into_iter() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl<#[may_dangle] T, A: Allocator> Drop for IntoIter { 2,861,997 ( 0.11%) fn drop(&mut self) { . struct DropGuard<'a, T, A: Allocator>(&'a mut IntoIter); . . impl Drop for DropGuard<'_, T, A> { . fn drop(&mut self) { . unsafe { . // `IntoIter::alloc` is not used anymore after this . let alloc = ptr::read(&self.0.alloc); . // RawVec handles deallocation 518,848 ( 0.02%) let _ = RawVec::from_raw_parts_in(self.0.buf.as_ptr(), self.0.cap, alloc); . } . } . } . . let guard = DropGuard(self); . // destroy the remaining elements . unsafe { 8 ( 0.00%) ptr::drop_in_place(guard.0.as_raw_mut_slice()); . } . // now `guard` will be dropped and do the rest 2,380,287 ( 0.09%) } . } . . #[unstable(issue = "none", feature = "inplace_iteration")] . #[doc(hidden)] . unsafe impl InPlaceIterable for IntoIter {} . . #[unstable(issue = "none", feature = "inplace_iteration")] . #[doc(hidden)] -- line 331 ---------------------------------------- 629,124 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/freshen.rs -------------------------------------------------------------------------------- Ir -- line 47 ---------------------------------------- . const_freshen_count: u32, . ty_freshen_map: FxHashMap>, . const_freshen_map: FxHashMap, &'tcx ty::Const<'tcx>>, . keep_static: bool, . } . . impl<'a, 'tcx> TypeFreshener<'a, 'tcx> { . pub fn new(infcx: &'a InferCtxt<'a, 'tcx>, keep_static: bool) -> TypeFreshener<'a, 'tcx> { 758,790 ( 0.03%) TypeFreshener { . infcx, . ty_freshen_count: 0, . const_freshen_count: 0, . ty_freshen_map: Default::default(), . const_freshen_map: Default::default(), . keep_static, . } . } . 459,640 ( 0.02%) fn freshen_ty( . &mut self, . opt_ty: Option>, . key: ty::InferTy, . freshener: F, . ) -> Ty<'tcx> . where . F: FnOnce(u32) -> ty::InferTy, . { 114,910 ( 0.00%) if let Some(ty) = opt_ty { . return ty.fold_with(self); . } . 4,446 ( 0.00%) match self.ty_freshen_map.entry(key) { 296 ( 0.00%) Entry::Occupied(entry) => *entry.get(), . Entry::Vacant(entry) => { 1,927 ( 0.00%) let index = self.ty_freshen_count; 7,708 ( 0.00%) self.ty_freshen_count += 1; 3,854 ( 0.00%) let t = self.infcx.tcx.mk_ty_infer(freshener(index)); . entry.insert(t); . t . } . } 20,007 ( 0.00%) } . . fn freshen_const( . &mut self, . opt_ct: Option<&'tcx ty::Const<'tcx>>, . key: ty::InferConst<'tcx>, . freshener: F, . ty: Ty<'tcx>, . ) -> &'tcx ty::Const<'tcx> -- line 96 ---------------------------------------- -- line 111 ---------------------------------------- . ct . } . } . } . } . . impl<'a, 'tcx> TypeFolder<'tcx> for TypeFreshener<'a, 'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { 126,042 ( 0.00%) self.infcx.tcx 58,567 ( 0.00%) } . . fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { 9,864 ( 0.00%) match *r { . ty::ReLateBound(..) => { . // leave bound regions alone . r . } . . ty::ReEarlyBound(..) . | ty::ReFree(_) . | ty::ReVar(_) . | ty::RePlaceholder(..) . | ty::ReEmpty(_) . | ty::ReErased => { . // replace all free regions with 'erased . self.tcx().lifetimes.re_erased . } . ty::ReStatic => { 96 ( 0.00%) if self.keep_static { . r . } else { . self.tcx().lifetimes.re_erased . } . } . } 128 ( 0.00%) } . 1,047,270 ( 0.04%) fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 523,635 ( 0.02%) if !t.needs_infer() && !t.has_erasable_regions() { . return t; . } . . let tcx = self.infcx.tcx; . 583,154 ( 0.02%) match *t.kind() { 57,223 ( 0.00%) ty::Infer(ty::TyVar(v)) => { 457,784 ( 0.02%) let opt_ty = self.infcx.inner.borrow_mut().type_variables().probe(v).known(); 515,007 ( 0.02%) self.freshen_ty(opt_ty, ty::TyVar(v), ty::FreshTy) . } . 928 ( 0.00%) ty::Infer(ty::IntVar(v)) => self.freshen_ty( 1,856 ( 0.00%) self.infcx . .inner . .borrow_mut() . .int_unification_table() . .probe_value(v) . .map(|v| v.to_type(tcx)), . ty::IntVar(v), . ty::FreshIntTy, . ), -- line 170 ---------------------------------------- -- line 210 ---------------------------------------- . | ty::Dynamic(..) . | ty::Never . | ty::Tuple(..) . | ty::Projection(..) . | ty::Foreign(..) . | ty::Param(..) . | ty::Closure(..) . | ty::GeneratorWitness(..) 22,944 ( 0.00%) | ty::Opaque(..) => t.super_fold_with(self), . . ty::Placeholder(..) | ty::Bound(..) => bug!("unexpected type {:?}", t), . } 801,178 ( 0.03%) } . 84 ( 0.00%) fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 84 ( 0.00%) match ct.val { . ty::ConstKind::Infer(ty::InferConst::Var(v)) => { . let opt_ct = self . .infcx . .inner . .borrow_mut() . .const_unification_table() . .probe_value(v) . .val -- line 233 ---------------------------------------- -- line 256 ---------------------------------------- . } . . ty::ConstKind::Param(_) . | ty::ConstKind::Value(_) . | ty::ConstKind::Unevaluated(..) . | ty::ConstKind::Error(_) => {} . } . 112 ( 0.00%) ct.super_fold_with(self) . } . } 189,497 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/unicode-xid-0.2.2/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 70 ---------------------------------------- . /// mostly similar to 'ID_Continue' but modified for closure under NFKx. . fn is_xid_continue(self) -> bool; . } . . impl UnicodeXID for char { . #[inline] . fn is_xid_start(self) -> bool { . // Fast-path for ascii idents 658,385 ( 0.03%) ('a' <= self && self <= 'z') . || ('A' <= self && self <= 'Z') 231,698 ( 0.01%) || (self > '\x7f' && derived_property::XID_Start(self)) . } . . #[inline] . fn is_xid_continue(self) -> bool { . // Fast-path for ascii idents 2,239,819 ( 0.09%) ('a' <= self && self <= 'z') . || ('A' <= self && self <= 'Z') . || ('0' <= self && self <= '9') . || self == '_' 66,948 ( 0.00%) || (self > '\x7f' && derived_property::XID_Continue(self)) . } . } 435,684 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/regionck.rs -------------------------------------------------------------------------------- Ir -- line 125 ---------------------------------------- . /// fn foo<'a, 'b, T>(x: &'a &'b [T]) { } . /// ``` . /// . /// we can assume in the caller's body that `'b: 'a` and that `T: . /// 'b` (and hence, transitively, that `T: 'a`). This method would . /// add those assumptions into the outlives-environment. . /// . /// Tests: `src/test/ui/regions/regions-free-region-ordering-*.rs` 2,340 ( 0.00%) fn add_implied_bounds<'a>( . &mut self, . infcx: &InferCtxt<'a, 'tcx>, . fn_sig_tys: FxHashSet>, . body_id: hir::HirId, . span: Span, . ) { . debug!("add_implied_bounds()"); . 4,069 ( 0.00%) for ty in fn_sig_tys { . let ty = infcx.resolve_vars_if_possible(ty); . debug!("add_implied_bounds: ty = {}", ty); 3,393 ( 0.00%) let implied_bounds = infcx.implied_outlives_bounds(self.param_env, body_id, ty, span); . self.add_outlives_bounds(Some(infcx), implied_bounds) . } 1,560 ( 0.00%) } . } . . /////////////////////////////////////////////////////////////////////////// . // PUBLIC ENTRY POINTS . . impl<'a, 'tcx> FnCtxt<'a, 'tcx> { 117 ( 0.00%) pub fn regionck_expr(&self, body: &'tcx hir::Body<'tcx>) { 91 ( 0.00%) let subject = self.tcx.hir().body_owner_def_id(body.id()); 26 ( 0.00%) let id = body.value.hir_id; 91 ( 0.00%) let mut rcx = RegionCtxt::new(self, id, Subject(subject), self.param_env); . . // There are no add'l implied bounds when checking a . // standalone expr (e.g., the `E` in a type like `[u32; E]`). 65 ( 0.00%) rcx.outlives_environment.save_implied_bounds(id); . 13 ( 0.00%) if !self.errors_reported_since_creation() { . // regionck assumes typeck succeeded . rcx.visit_body(body); . rcx.visit_region_obligations(id); . } 26 ( 0.00%) rcx.resolve_regions_and_report_errors(RegionckMode::for_item_body(self.tcx)); 117 ( 0.00%) } . . /// Region checking during the WF phase for items. `wf_tys` are the . /// types from which we should derive implied bounds, if any. 1,200 ( 0.00%) pub fn regionck_item(&self, item_id: hir::HirId, span: Span, wf_tys: FxHashSet>) { . debug!("regionck_item(item.id={:?}, wf_tys={:?})", item_id, wf_tys); 400 ( 0.00%) let subject = self.tcx.hir().local_def_id(item_id); 700 ( 0.00%) let mut rcx = RegionCtxt::new(self, item_id, Subject(subject), self.param_env); 1,100 ( 0.00%) rcx.outlives_environment.add_implied_bounds(self, wf_tys, item_id, span); 400 ( 0.00%) rcx.outlives_environment.save_implied_bounds(item_id); . rcx.visit_region_obligations(item_id); . rcx.resolve_regions_and_report_errors(RegionckMode::default()); 900 ( 0.00%) } . . /// Region check a function body. Not invoked on closures, but . /// only on the "root" fn item (in which closures may be . /// embedded). Walks the function body and adds various add'l . /// constraints that are needed for region inference. This is . /// separated both to isolate "pure" region constraints from the . /// rest of type check and because sometimes we need type . /// inference to have completed before we can determine which . /// constraints to add. 546 ( 0.00%) pub(crate) fn regionck_fn( . &self, . fn_id: hir::HirId, . body: &'tcx hir::Body<'tcx>, . span: Span, . wf_tys: FxHashSet>, . ) { . debug!("regionck_fn(id={})", fn_id); 252 ( 0.00%) let subject = self.tcx.hir().body_owner_def_id(body.id()); 84 ( 0.00%) let hir_id = body.value.hir_id; 210 ( 0.00%) let mut rcx = RegionCtxt::new(self, hir_id, Subject(subject), self.param_env); . // We need to add the implied bounds from the function signature 504 ( 0.00%) rcx.outlives_environment.add_implied_bounds(self, wf_tys, fn_id, span); 168 ( 0.00%) rcx.outlives_environment.save_implied_bounds(fn_id); . 42 ( 0.00%) if !self.errors_reported_since_creation() { . // regionck assumes typeck succeeded 462 ( 0.00%) rcx.visit_fn_body(fn_id, body, self.tcx.hir().span(fn_id)); . } . 84 ( 0.00%) rcx.resolve_regions_and_report_errors(RegionckMode::for_item_body(self.tcx)); 378 ( 0.00%) } . } . . /////////////////////////////////////////////////////////////////////////// . // INTERNALS . . pub struct RegionCtxt<'a, 'tcx> { . pub fcx: &'a FnCtxt<'a, 'tcx>, . -- line 221 ---------------------------------------- -- line 229 ---------------------------------------- . . // id of AST node being analyzed (the subject of the analysis). . subject_def_id: LocalDefId, . } . . impl<'a, 'tcx> Deref for RegionCtxt<'a, 'tcx> { . type Target = FnCtxt<'a, 'tcx>; . fn deref(&self) -> &Self::Target { 137,398 ( 0.01%) self.fcx . } . } . . pub struct Subject(LocalDefId); . . impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { 1,705 ( 0.00%) pub fn new( . fcx: &'a FnCtxt<'a, 'tcx>, . initial_body_id: hir::HirId, . Subject(subject): Subject, . param_env: ty::ParamEnv<'tcx>, . ) -> RegionCtxt<'a, 'tcx> { 155 ( 0.00%) let region_scope_tree = fcx.tcx.region_scope_tree(subject); 310 ( 0.00%) let outlives_environment = OutlivesEnvironment::new(param_env); 1,085 ( 0.00%) RegionCtxt { . fcx, . region_scope_tree, . body_id: initial_body_id, . body_owner: subject, . subject_def_id: subject, 620 ( 0.00%) outlives_environment, . } 1,395 ( 0.00%) } . . /// Try to resolve the type for the given node, returning `t_err` if an error results. Note that . /// we never care about the details of the error, the same error will be detected and reported . /// in the writeback phase. . /// . /// Note one important point: we do not attempt to resolve *region variables* here. This is . /// because regionck is essentially adding constraints to those region variables and so may yet . /// influence how they are resolved. -- line 268 ---------------------------------------- -- line 283 ---------------------------------------- . /// of b will be `&.i32` and then `*b` will require that `` be bigger than the let and . /// the `*b` expression, so we will effectively resolve `` to be the block B. . pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> { . self.resolve_vars_if_possible(unresolved_ty) . } . . /// Try to resolve the type for the given node. . fn resolve_node_type(&self, id: hir::HirId) -> Ty<'tcx> { 259 ( 0.00%) let t = self.node_ty(id); 229 ( 0.00%) self.resolve_type(t) . } . . /// This is the "main" function when region-checking a function item or a . /// closure within a function item. It begins by updating various fields . /// (e.g., `outlives_environment`) to be appropriate to the function and . /// then adds constraints derived from the function body. . /// . /// Note that it does **not** restore the state of the fields that . /// it updates! This is intentional, since -- for the main . /// function -- we wish to be able to read the final . /// `outlives_environment` and other fields from the caller. For . /// closures, however, we save and restore any "scoped state" . /// before we invoke this function. (See `visit_fn` in the . /// `intravisit::Visitor` impl below.) 742 ( 0.00%) fn visit_fn_body( . &mut self, . id: hir::HirId, // the id of the fn itself . body: &'tcx hir::Body<'tcx>, . span: Span, . ) { . // When we enter a function, we can derive . debug!("visit_fn_body(id={:?})", id); . 212 ( 0.00%) let body_id = body.id(); 106 ( 0.00%) self.body_id = body_id.hir_id; 371 ( 0.00%) self.body_owner = self.tcx.hir().body_owner_def_id(body_id); . . let fn_sig = { 530 ( 0.00%) match self.typeck_results.borrow().liberated_fn_sigs().get(id) { 106 ( 0.00%) Some(f) => *f, . None => { . bug!("No fn-sig entry for id={:?}", id); . } . } . }; . . // Collect the types from which we create inferred bounds. . // For the return type, if diverging, substitute `bool` just . // because it will have no effect. . // . // FIXME(#27579) return types should not be implied bounds . let fn_sig_tys: FxHashSet<_> = 265 ( 0.00%) fn_sig.inputs().iter().cloned().chain(Some(fn_sig.output())).collect(); . 689 ( 0.00%) self.outlives_environment.add_implied_bounds(self.fcx, fn_sig_tys, body_id.hir_id, span); 265 ( 0.00%) self.outlives_environment.save_implied_bounds(body_id.hir_id); 106 ( 0.00%) self.link_fn_params(body.params); . self.visit_body(body); . self.visit_region_obligations(body_id.hir_id); 424 ( 0.00%) } . . fn visit_inline_const(&mut self, id: hir::HirId, body: &'tcx hir::Body<'tcx>) { . debug!("visit_inline_const(id={:?})", id); . . // Save state of current function. We will restore afterwards. . let old_body_id = self.body_id; . let old_body_owner = self.body_owner; . let env_snapshot = self.outlives_environment.push_snapshot_pre_typeck_child(); -- line 350 ---------------------------------------- -- line 365 ---------------------------------------- . } . . fn visit_region_obligations(&mut self, hir_id: hir::HirId) { . debug!("visit_region_obligations: hir_id={:?}", hir_id); . . // region checking can introduce new pending obligations . // which, when processed, might generate new region . // obligations. So make sure we process those. 166 ( 0.00%) self.select_all_obligations_or_error(); . } . . fn resolve_regions_and_report_errors(&self, mode: RegionckMode) { 465 ( 0.00%) self.infcx.process_registered_region_obligations( 310 ( 0.00%) self.outlives_environment.region_bound_pairs_map(), 310 ( 0.00%) Some(self.tcx.lifetimes.re_root_empty), 155 ( 0.00%) self.param_env, . ); . 775 ( 0.00%) self.fcx.resolve_regions_and_report_errors( 155 ( 0.00%) self.subject_def_id.to_def_id(), . &self.outlives_environment, . mode, . ); . } . . fn constrain_bindings_in_pat(&mut self, pat: &hir::Pat<'_>) { . debug!("regionck::visit_pat(pat={:?})", pat); . pat.each_binding(|_, hir_id, span, _| { 160 ( 0.00%) let typ = self.resolve_node_type(hir_id); 320 ( 0.00%) let body_id = self.body_id; 640 ( 0.00%) dropck::check_drop_obligations(self, typ, span, body_id); . }) . } . } . . impl<'a, 'tcx> Visitor<'tcx> for RegionCtxt<'a, 'tcx> { . // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local, . // However, right now we run into an issue whereby some free . // regions are not properly related if they appear within the -- line 403 ---------------------------------------- -- line 416 ---------------------------------------- . ) { . assert!( . matches!(fk, intravisit::FnKind::Closure), . "visit_fn invoked for something other than a closure" . ); . . // Save state of current function before invoking . // `visit_fn_body`. We will restore afterwards. 22 ( 0.00%) let old_body_id = self.body_id; 22 ( 0.00%) let old_body_owner = self.body_owner; 44 ( 0.00%) let env_snapshot = self.outlives_environment.push_snapshot_pre_typeck_child(); . 66 ( 0.00%) let body = self.tcx.hir().body(body_id); 66 ( 0.00%) self.visit_fn_body(hir_id, body, span); . . // Restore state from previous function. 44 ( 0.00%) self.outlives_environment.pop_snapshot_post_typeck_child(env_snapshot); 22 ( 0.00%) self.body_id = old_body_id; 22 ( 0.00%) self.body_owner = old_body_owner; . } . . //visit_pat: visit_pat, // (..) see above . . fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) { . // see above 742 ( 0.00%) self.constrain_bindings_in_pat(arm.pat); . intravisit::walk_arm(self, arm); . } . 680 ( 0.00%) fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) { . // see above 595 ( 0.00%) self.constrain_bindings_in_pat(l.pat); . self.link_local(l); . intravisit::walk_local(self, l); 595 ( 0.00%) } . 358,968 ( 0.01%) fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { . // Check any autoderefs or autorefs that appear. . let cmt_result = self.constrain_adjustments(expr); . . // If necessary, constrain destructors in this expression. This will be . // the adjusted form if there is an adjustment. 90,183 ( 0.00%) match cmt_result { 403,839 ( 0.02%) Ok(head_cmt) => { . self.check_safety_of_rvalue_destructor_if_necessary(&head_cmt, expr.span); . } . Err(..) => { . self.tcx.sess.delay_span_bug(expr.span, "cat_expr Errd"); . } . } . 314,107 ( 0.01%) match expr.kind { . hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, ref base) => { . self.link_addr_of(expr, m, base); . . intravisit::walk_expr(self, expr); . } . . hir::ExprKind::Match(ref discr, arms, _) => { . self.link_match(discr, arms); -- line 475 ---------------------------------------- -- line 479 ---------------------------------------- . . hir::ExprKind::ConstBlock(anon_const) => { . let body = self.tcx.hir().body(anon_const.body); . self.visit_inline_const(anon_const.hir_id, body); . } . . _ => intravisit::walk_expr(self, expr), . } 358,968 ( 0.01%) } . } . . impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { . /// Creates a temporary `MemCategorizationContext` and pass it to the closure. . fn with_mc(&self, f: F) -> R . where . F: for<'b> FnOnce(mc::MemCategorizationContext<'b, 'tcx>) -> R, . { 466,043 ( 0.02%) f(mc::MemCategorizationContext::new( . &self.infcx, . self.outlives_environment.param_env, . self.body_owner, 46,026 ( 0.00%) &self.typeck_results.borrow(), . )) . } . . /// Invoked on any adjustments that occur. Checks that if this is a region pointer being . /// dereferenced, the lifetime of the pointer includes the deref expr. . fn constrain_adjustments( . &mut self, . expr: &hir::Expr<'_>, . ) -> mc::McResult> { . debug!("constrain_adjustments(expr={:?})", expr); . 89,742 ( 0.00%) let mut place = self.with_mc(|mc| mc.cat_expr_unadjusted(expr))?; . 44,871 ( 0.00%) let typeck_results = self.typeck_results.borrow(); 44,871 ( 0.00%) let adjustments = typeck_results.expr_adjustments(expr); 44,871 ( 0.00%) if adjustments.is_empty() { 399,870 ( 0.02%) return Ok(place); . } . . debug!("constrain_adjustments: adjustments={:?}", adjustments); . . // If necessary, constrain destructors in the unadjusted form of this . // expression. . self.check_safety_of_rvalue_destructor_if_necessary(&place, expr.span); . . for adjustment in adjustments { . debug!("constrain_adjustments: adjustment={:?}, place={:?}", adjustment, place); . 2,643 ( 0.00%) if let adjustment::Adjust::Deref(Some(deref)) = adjustment.kind { 30 ( 0.00%) self.link_region( 6 ( 0.00%) expr.span, . deref.region, 24 ( 0.00%) ty::BorrowKind::from_mutbl(deref.mutbl), . &place, . ); . } . 816 ( 0.00%) if let adjustment::Adjust::Borrow(ref autoref) = adjustment.kind { . self.link_autoref(expr, &place, autoref); . } . 9,570 ( 0.00%) place = self.with_mc(|mc| mc.cat_expr_adjusted(expr, place, adjustment))?; . } . 4,410 ( 0.00%) Ok(place) . } . . fn check_safety_of_rvalue_destructor_if_necessary( . &mut self, . place_with_id: &PlaceWithHirId<'tcx>, . span: Span, . ) { 90,624 ( 0.00%) if let PlaceBase::Rvalue = place_with_id.place.base { 44,639 ( 0.00%) if place_with_id.place.projections.is_empty() { 45,147 ( 0.00%) let typ = self.resolve_type(place_with_id.place.ty()); 89,252 ( 0.00%) let body_id = self.body_id; 178,504 ( 0.01%) dropck::check_drop_obligations(self, typ, span, body_id); . } . } . } . /// Adds constraints to inference such that `T: 'a` holds (or . /// reports an error if it cannot). . /// . /// # Parameters . /// -- line 565 ---------------------------------------- -- line 567 ---------------------------------------- . /// - `ty`, the type `T` . /// - `region`, the region `'a` . pub fn type_must_outlive( . &self, . origin: infer::SubregionOrigin<'tcx>, . ty: Ty<'tcx>, . region: ty::Region<'tcx>, . ) { 1,191 ( 0.00%) self.infcx.register_region_obligation( 1,191 ( 0.00%) self.body_id, 3,176 ( 0.00%) RegionObligation { sub_region: region, sup_type: ty, origin }, . ); . } . . /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the . /// resulting pointer is linked to the lifetime of its guarantor (if any). . fn link_addr_of( . &mut self, . expr: &hir::Expr<'_>, . mutability: hir::Mutability, . base: &hir::Expr<'_>, . ) { . debug!("link_addr_of(expr={:?}, base={:?})", expr, base); . 594 ( 0.00%) let cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(base))); . . debug!("link_addr_of: cmt={:?}", cmt); . 162 ( 0.00%) self.link_region_from_node_type(expr.span, expr.hir_id, mutability, &cmt); . } . . /// Computes the guarantors for any ref bindings in a `let` and . /// then ensures that the lifetime of the resulting pointer is . /// linked to the lifetime of the initialization expression. . fn link_local(&self, local: &hir::Local<'_>) { . debug!("regionck::for_local()"); 255 ( 0.00%) let init_expr = match local.init { . None => { . return; . } . Some(expr) => &*expr, . }; 800 ( 0.00%) let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(init_expr))); 640 ( 0.00%) self.link_pattern(discr_cmt, local.pat); . } . . /// Computes the guarantors for any ref bindings in a match and . /// then ensures that the lifetime of the resulting pointer is . /// linked to the lifetime of its guarantor (if any). . fn link_match(&self, discr: &hir::Expr<'_>, arms: &[hir::Arm<'_>]) { . debug!("regionck::for_match()"); 490 ( 0.00%) let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(discr))); . debug!("discr_cmt={:?}", discr_cmt); . for arm in arms { 424 ( 0.00%) self.link_pattern(discr_cmt.clone(), arm.pat); . } . } . . /// Computes the guarantors for any ref bindings in a match and . /// then ensures that the lifetime of the resulting pointer is . /// linked to the lifetime of its guarantor (if any). . fn link_fn_params(&self, params: &[hir::Param<'_>]) { . for param in params { 296 ( 0.00%) let param_ty = self.node_ty(param.hir_id); . let param_cmt = 148 ( 0.00%) self.with_mc(|mc| mc.cat_rvalue(param.hir_id, param.pat.span, param_ty)); . debug!("param_ty={:?} param_cmt={:?} param={:?}", param_ty, param_cmt, param); 888 ( 0.00%) self.link_pattern(param_cmt, param.pat); . } . } . . /// Link lifetimes of any ref bindings in `root_pat` to the pointers found . /// in the discriminant, if needed. 1,560 ( 0.00%) fn link_pattern(&self, discr_cmt: PlaceWithHirId<'tcx>, root_pat: &hir::Pat<'_>) { . debug!("link_pattern(discr_cmt={:?}, root_pat={:?})", discr_cmt, root_pat); . ignore_err!(self.with_mc(|mc| { 780 ( 0.00%) mc.cat_pattern(discr_cmt, root_pat, |sub_cmt, hir::Pat { kind, span, hir_id, .. }| { . // `ref x` pattern 798 ( 0.00%) if let PatKind::Binding(..) = kind { 939 ( 0.00%) if let Some(ty::BindByReference(mutbl)) = 3,234 ( 0.00%) mc.typeck_results.extract_binding_mode(self.tcx.sess, *hir_id, *span) . { . self.link_region_from_node_type(*span, *hir_id, mutbl, sub_cmt); . } . } . }) . })); 1,560 ( 0.00%) } . . /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being . /// autoref'd. . fn link_autoref( . &self, . expr: &hir::Expr<'_>, . expr_cmt: &PlaceWithHirId<'tcx>, . autoref: &adjustment::AutoBorrow<'tcx>, . ) { . debug!("link_autoref(autoref={:?}, expr_cmt={:?})", autoref, expr_cmt); . 644 ( 0.00%) match *autoref { 644 ( 0.00%) adjustment::AutoBorrow::Ref(r, m) => { 3,220 ( 0.00%) self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m.into()), expr_cmt); . } . . adjustment::AutoBorrow::RawPtr(_) => {} . } . } . . /// Like `link_region()`, except that the region is extracted from the type of `id`, . /// which must be some reference (`&T`, `&str`, etc). -- line 676 ---------------------------------------- -- line 682 ---------------------------------------- . cmt_borrowed: &PlaceWithHirId<'tcx>, . ) { . debug!( . "link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})", . id, mutbl, cmt_borrowed . ); . . let rptr_ty = self.resolve_node_type(id); 138 ( 0.00%) if let ty::Ref(r, _, _) = rptr_ty.kind() { . debug!("rptr_ty={}", rptr_ty); 513 ( 0.00%) self.link_region(span, r, ty::BorrowKind::from_mutbl(mutbl), cmt_borrowed); . } . } . . /// Informs the inference engine that `borrow_cmt` is being borrowed with . /// kind `borrow_kind` and lifetime `borrow_region`. . /// In order to ensure borrowck is satisfied, this may create constraints . /// between regions, as explained in `link_reborrowed_region()`. 4,367 ( 0.00%) fn link_region( . &self, . span: Span, . borrow_region: ty::Region<'tcx>, . borrow_kind: ty::BorrowKind, . borrow_place: &PlaceWithHirId<'tcx>, . ) { 1,191 ( 0.00%) let origin = infer::DataBorrowed(borrow_place.place.ty(), span); 2,382 ( 0.00%) self.type_must_outlive(origin, borrow_place.place.ty(), borrow_region); . 2,227 ( 0.00%) for pointer_ty in borrow_place.place.deref_tys() { . debug!( . "link_region(borrow_region={:?}, borrow_kind={:?}, pointer_ty={:?})", . borrow_region, borrow_kind, borrow_place . ); 726 ( 0.00%) match *pointer_ty.kind() { . ty::RawPtr(_) => return, 2,178 ( 0.00%) ty::Ref(ref_region, _, ref_mutability) => { 242 ( 0.00%) if self.link_reborrowed_region(span, borrow_region, ref_region, ref_mutability) . { . return; . } . } . _ => assert!(pointer_ty.is_box(), "unexpected built-in deref type {}", pointer_ty), . } . } 503 ( 0.00%) if let PlaceBase::Upvar(upvar_id) = borrow_place.place.base { . self.link_upvar_region(span, borrow_region, upvar_id); . } 3,176 ( 0.00%) } . . /// This is the most complicated case: the path being borrowed is . /// itself the referent of a borrowed pointer. Let me give an . /// example fragment of code to make clear(er) the situation: . /// . /// ```ignore (incomplete Rust code) . /// let r: &'a mut T = ...; // the original reference "r" has lifetime 'a . /// ... -- line 737 ---------------------------------------- -- line 764 ---------------------------------------- . fn link_reborrowed_region( . &self, . span: Span, . borrow_region: ty::Region<'tcx>, . ref_region: ty::Region<'tcx>, . ref_mutability: hir::Mutability, . ) -> bool { . debug!("link_reborrowed_region: {:?} <= {:?}", borrow_region, ref_region); 1,210 ( 0.00%) self.sub_regions(infer::Reborrow(span), borrow_region, ref_region); . . // Decide whether we need to recurse and link any regions within . // the `ref_cmt`. This is concerned for the case where the value . // being reborrowed is in fact a borrowed pointer found within . // another borrowed pointer. For example: . // . // let p: &'b &'a mut T = ...; . // ... -- line 780 ---------------------------------------- -- line 834 ---------------------------------------- . borrow_region: ty::Region<'tcx>, . upvar_id: ty::UpvarId, . ) { . debug!("link_upvar_region(borrorw_region={:?}, upvar_id={:?}", borrow_region, upvar_id); . // A by-reference upvar can't be borrowed for longer than the . // upvar is borrowed from the environment. . let closure_local_def_id = upvar_id.closure_expr_id; . let mut all_captures_are_imm_borrow = true; 1 ( 0.00%) for captured_place in self . .typeck_results . .borrow() . .closure_min_captures . .get(&closure_local_def_id.to_def_id()) . .and_then(|root_var_min_cap| root_var_min_cap.get(&upvar_id.var_path.hir_id)) . .into_iter() . .flatten() . { 5 ( 0.00%) match captured_place.info.capture_kind { . ty::UpvarCapture::ByRef(upvar_borrow) => { 1 ( 0.00%) self.sub_regions( 7 ( 0.00%) infer::ReborrowUpvar(span, upvar_id), . borrow_region, 1 ( 0.00%) captured_place.region.unwrap(), . ); 6 ( 0.00%) if let ty::ImmBorrow = upvar_borrow { . debug!("link_upvar_region: capture by shared ref"); . } else { . all_captures_are_imm_borrow = false; . } . } . ty::UpvarCapture::ByValue => { . all_captures_are_imm_borrow = false; . } . } . } 2 ( 0.00%) if all_captures_are_imm_borrow { . return; . } . let fn_hir_id = self.tcx.hir().local_def_id_to_hir_id(closure_local_def_id); . let ty = self.resolve_node_type(fn_hir_id); . debug!("link_upvar_region: ty={:?}", ty); . . // A closure capture can't be borrowed for longer than the . // reference to the closure. -- line 877 ---------------------------------------- 364,582 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_hir/src/intravisit.rs -------------------------------------------------------------------------------- Ir -- line 48 ---------------------------------------- . } . } . . impl<'v, 'hir, V> ItemLikeVisitor<'hir> for DeepVisitor<'v, V> . where . V: Visitor<'hir>, . { . fn visit_item(&mut self, item: &'hir Item<'hir>) { 948 ( 0.00%) self.visitor.visit_item(item); . } . . fn visit_trait_item(&mut self, trait_item: &'hir TraitItem<'hir>) { . self.visitor.visit_trait_item(trait_item); . } . . fn visit_impl_item(&mut self, impl_item: &'hir ImplItem<'hir>) { 168 ( 0.00%) self.visitor.visit_impl_item(impl_item); . } . . fn visit_foreign_item(&mut self, foreign_item: &'hir ForeignItem<'hir>) { . self.visitor.visit_foreign_item(foreign_item); . } . } . . pub trait IntoVisitor<'hir> { -- line 72 ---------------------------------------- -- line 106 ---------------------------------------- . Method(Ident, &'a FnSig<'a>, Option<&'a Visibility<'a>>), . . /// `|x, y| {}` . Closure, . } . . impl<'a> FnKind<'a> { . pub fn header(&self) -> Option<&FnHeader> { 178 ( 0.00%) match *self { 16 ( 0.00%) FnKind::ItemFn(_, _, ref header, _) => Some(header), 78 ( 0.00%) FnKind::Method(_, ref sig, _) => Some(&sig.header), . FnKind::Closure => None, . } . } . . pub fn constness(self) -> Constness { 84 ( 0.00%) self.header().map_or(Constness::NotConst, |header| header.constness) 42 ( 0.00%) } . . pub fn asyncness(self) -> IsAsync { . self.header().map_or(IsAsync::NotAsync, |header| header.asyncness) . } . } . . /// An abstract representation of the HIR `rustc_middle::hir::map::Map`. . pub trait Map<'hir> { -- line 131 ---------------------------------------- -- line 248 ---------------------------------------- . /// Invoked when a nested item is encountered. By default does . /// nothing unless you override `nested_visit_map` to return other than . /// `None`, in which case it will walk the item. **You probably . /// don't want to override this method** -- instead, override . /// `nested_visit_map` or use the "shallow" or "deep" visit . /// patterns described on `itemlikevisit::ItemLikeVisitor`. The only . /// reason to override this method is if you want a nested pattern . /// but cannot supply a `Map`; see `nested_visit_map` for advice. 1,264 ( 0.00%) fn visit_nested_item(&mut self, id: ItemId) { . if Self::NestedFilter::INTER { 3,079 ( 0.00%) let item = self.nested_visit_map().item(id); 1,422 ( 0.00%) self.visit_item(item); . } 1,264 ( 0.00%) } . . /// Like `visit_nested_item()`, but for trait items. See . /// `visit_nested_item()` for advice on when to override this . /// method. . fn visit_nested_trait_item(&mut self, id: TraitItemId) { . if Self::NestedFilter::INTER { . let item = self.nested_visit_map().trait_item(id); . self.visit_trait_item(item); . } . } . . /// Like `visit_nested_item()`, but for impl items. See . /// `visit_nested_item()` for advice on when to override this . /// method. 448 ( 0.00%) fn visit_nested_impl_item(&mut self, id: ImplItemId) { . if Self::NestedFilter::INTER { 1,092 ( 0.00%) let item = self.nested_visit_map().impl_item(id); 252 ( 0.00%) self.visit_impl_item(item); . } 448 ( 0.00%) } . . /// Like `visit_nested_item()`, but for foreign items. See . /// `visit_nested_item()` for advice on when to override this . /// method. . fn visit_nested_foreign_item(&mut self, id: ForeignItemId) { . if Self::NestedFilter::INTER { . let item = self.nested_visit_map().foreign_item(id); . self.visit_foreign_item(item); . } . } . . /// Invoked to visit the body of a function, method or closure. Like . /// visit_nested_item, does nothing by default unless you override . /// `nested_visit_map` to return other than `None`, in which case it will walk . /// the body. 540 ( 0.00%) fn visit_nested_body(&mut self, id: BodyId) { . if Self::NestedFilter::INTRA { 5,981 ( 0.00%) let body = self.nested_visit_map().body(id); 211 ( 0.00%) self.visit_body(body); . } 540 ( 0.00%) } . . fn visit_param(&mut self, param: &'v Param<'v>) { . walk_param(self, param) . } . . /// Visits the top-level item and (optionally) nested items / impl items. See . /// `visit_nested_item` for details. . fn visit_item(&mut self, i: &'v Item<'v>) { 2,056 ( 0.00%) walk_item(self, i) . } . . fn visit_body(&mut self, b: &'v Body<'v>) { 689 ( 0.00%) walk_body(self, b); . } . . /// When invoking `visit_all_item_likes()`, you need to supply an . /// item-like visitor. This method converts an "intra-visit" . /// visitor into an item-like visitor that walks the entire tree. . /// If you use this, you probably don't want to process the . /// contents of nested item-like things, since the outer loop will . /// visit them as well. -- line 323 ---------------------------------------- -- line 332 ---------------------------------------- . } . fn visit_name(&mut self, _span: Span, _name: Symbol) { . // Nothing to do. . } . fn visit_ident(&mut self, ident: Ident) { . walk_ident(self, ident) . } . fn visit_mod(&mut self, m: &'v Mod<'v>, _s: Span, n: HirId) { 21 ( 0.00%) walk_mod(self, m, n) . } . fn visit_foreign_item(&mut self, i: &'v ForeignItem<'v>) { . walk_foreign_item(self, i) . } . fn visit_local(&mut self, l: &'v Local<'v>) { 850 ( 0.00%) walk_local(self, l) . } . fn visit_block(&mut self, b: &'v Block<'v>) { . walk_block(self, b) . } . fn visit_stmt(&mut self, s: &'v Stmt<'v>) { 9,963 ( 0.00%) walk_stmt(self, s) . } . fn visit_arm(&mut self, a: &'v Arm<'v>) { 1,288 ( 0.00%) walk_arm(self, a) . } . fn visit_pat(&mut self, p: &'v Pat<'v>) { 23,880 ( 0.00%) walk_pat(self, p) . } . fn visit_array_length(&mut self, len: &'v ArrayLen) { . walk_array_len(self, len) . } . fn visit_anon_const(&mut self, c: &'v AnonConst) { . walk_anon_const(self, c) . } . fn visit_expr(&mut self, ex: &'v Expr<'v>) { 1,471,946 ( 0.06%) walk_expr(self, ex) . } . fn visit_let_expr(&mut self, lex: &'v Let<'v>) { 270 ( 0.00%) walk_let_expr(self, lex) . } . fn visit_ty(&mut self, t: &'v Ty<'v>) { 18,568 ( 0.00%) walk_ty(self, t) . } . fn visit_generic_param(&mut self, p: &'v GenericParam<'v>) { 405 ( 0.00%) walk_generic_param(self, p) . } . fn visit_const_param_default(&mut self, _param: HirId, ct: &'v AnonConst) { . walk_const_param_default(self, ct) . } . fn visit_generics(&mut self, g: &'v Generics<'v>) { 358 ( 0.00%) walk_generics(self, g) . } . fn visit_where_predicate(&mut self, predicate: &'v WherePredicate<'v>) { 75 ( 0.00%) walk_where_predicate(self, predicate) . } . fn visit_fn_decl(&mut self, fd: &'v FnDecl<'v>) { 212 ( 0.00%) walk_fn_decl(self, fd) . } . fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl<'v>, b: BodyId, s: Span, id: HirId) { 9,250 ( 0.00%) walk_fn(self, fk, fd, b, s, id) . } . fn visit_use(&mut self, path: &'v Path<'v>, hir_id: HirId) { . walk_use(self, path, hir_id) . } . fn visit_trait_item(&mut self, ti: &'v TraitItem<'v>) { . walk_trait_item(self, ti) . } . fn visit_trait_item_ref(&mut self, ii: &'v TraitItemRef) { . walk_trait_item_ref(self, ii) . } . fn visit_impl_item(&mut self, ii: &'v ImplItem<'v>) { 1,404 ( 0.00%) walk_impl_item(self, ii) . } . fn visit_foreign_item_ref(&mut self, ii: &'v ForeignItemRef) { . walk_foreign_item_ref(self, ii) . } . fn visit_impl_item_ref(&mut self, ii: &'v ImplItemRef) { 112 ( 0.00%) walk_impl_item_ref(self, ii) . } 165 ( 0.00%) fn visit_trait_ref(&mut self, t: &'v TraitRef<'v>) { 90 ( 0.00%) walk_trait_ref(self, t) 120 ( 0.00%) } . fn visit_param_bound(&mut self, bounds: &'v GenericBound<'v>) { 216 ( 0.00%) walk_param_bound(self, bounds) . } . fn visit_poly_trait_ref(&mut self, t: &'v PolyTraitRef<'v>, m: TraitBoundModifier) { 14 ( 0.00%) walk_poly_trait_ref(self, t, m) . } . fn visit_variant_data( . &mut self, . s: &'v VariantData<'v>, . _: Symbol, . _: &'v Generics<'v>, . _parent_id: HirId, . _: Span, . ) { 940 ( 0.00%) walk_struct_def(self, s) . } . fn visit_field_def(&mut self, s: &'v FieldDef<'v>) { 108 ( 0.00%) walk_field_def(self, s) . } . fn visit_enum_def( . &mut self, . enum_definition: &'v EnumDef<'v>, . generics: &'v Generics<'v>, . item_id: HirId, . _: Span, . ) { 48 ( 0.00%) walk_enum_def(self, enum_definition, generics, item_id) . } . fn visit_variant(&mut self, v: &'v Variant<'v>, g: &'v Generics<'v>, item_id: HirId) { 336 ( 0.00%) walk_variant(self, v, g, item_id) . } . fn visit_label(&mut self, label: &'v Label) { . walk_label(self, label) . } . fn visit_infer(&mut self, inf: &'v InferArg) { . walk_inf(self, inf); . } 1,758 ( 0.00%) fn visit_generic_arg(&mut self, generic_arg: &'v GenericArg<'v>) { 11,969 ( 0.00%) match generic_arg { 8 ( 0.00%) GenericArg::Lifetime(lt) => self.visit_lifetime(lt), 559 ( 0.00%) GenericArg::Type(ty) => self.visit_ty(ty), . GenericArg::Const(ct) => self.visit_anon_const(&ct.value), . GenericArg::Infer(inf) => self.visit_infer(inf), . } 1,264 ( 0.00%) } . fn visit_lifetime(&mut self, lifetime: &'v Lifetime) { . walk_lifetime(self, lifetime) . } . fn visit_qpath(&mut self, qpath: &'v QPath<'v>, id: HirId, span: Span) { 2,690,714 ( 0.11%) walk_qpath(self, qpath, id, span) . } 1,194 ( 0.00%) fn visit_path(&mut self, path: &'v Path<'v>, _id: HirId) { 389,088 ( 0.02%) walk_path(self, path) 1,404 ( 0.00%) } 2,105 ( 0.00%) fn visit_path_segment(&mut self, path_span: Span, path_segment: &'v PathSegment<'v>) { . walk_path_segment(self, path_span, path_segment) 2,349 ( 0.00%) } 4,372 ( 0.00%) fn visit_generic_args(&mut self, path_span: Span, generic_args: &'v GenericArgs<'v>) { 5 ( 0.00%) walk_generic_args(self, path_span, generic_args) 3,866 ( 0.00%) } . fn visit_assoc_type_binding(&mut self, type_binding: &'v TypeBinding<'v>) { 81 ( 0.00%) walk_assoc_type_binding(self, type_binding) . } . fn visit_attribute(&mut self, _id: HirId, _attr: &'v Attribute) {} . fn visit_vis(&mut self, vis: &'v Visibility<'v>) { 873 ( 0.00%) walk_vis(self, vis) . } . fn visit_associated_item_kind(&mut self, kind: &'v AssocItemKind) { . walk_associated_item_kind(self, kind); . } . fn visit_defaultness(&mut self, defaultness: &'v Defaultness) { . walk_defaultness(self, defaultness); . } . } . 21 ( 0.00%) pub fn walk_mod<'v, V: Visitor<'v>>(visitor: &mut V, module: &'v Mod<'v>, mod_hir_id: HirId) { . visitor.visit_id(mod_hir_id); 1,059 ( 0.00%) for &item_id in module.item_ids { 312 ( 0.00%) visitor.visit_nested_item(item_id); . } 24 ( 0.00%) } . 2,408 ( 0.00%) pub fn walk_body<'v, V: Visitor<'v>>(visitor: &mut V, body: &'v Body<'v>) { 2,737 ( 0.00%) walk_list!(visitor, visit_param, body.params); 4,774 ( 0.00%) visitor.visit_expr(&body.value); 1,248 ( 0.00%) } . 3,910 ( 0.00%) pub fn walk_local<'v, V: Visitor<'v>>(visitor: &mut V, local: &'v Local<'v>) { . // Intentionally visiting the expr first - the initialization expr . // dominates the local's definition. 5,134 ( 0.00%) walk_list!(visitor, visit_expr, &local.init); 340 ( 0.00%) visitor.visit_id(local.hir_id); 3,229 ( 0.00%) visitor.visit_pat(&local.pat); 2,854 ( 0.00%) walk_list!(visitor, visit_ty, &local.ty); 3,240 ( 0.00%) } . . pub fn walk_ident<'v, V: Visitor<'v>>(visitor: &mut V, ident: Ident) { . visitor.visit_name(ident.span, ident.name); . } . . pub fn walk_label<'v, V: Visitor<'v>>(visitor: &mut V, label: &'v Label) { . visitor.visit_ident(label.ident); . } . . pub fn walk_lifetime<'v, V: Visitor<'v>>(visitor: &mut V, lifetime: &'v Lifetime) { 318 ( 0.00%) visitor.visit_id(lifetime.hir_id); 204 ( 0.00%) match lifetime.name { 36 ( 0.00%) LifetimeName::Param(ParamName::Plain(ident)) => { . visitor.visit_ident(ident); . } . LifetimeName::Param(ParamName::Fresh(_)) . | LifetimeName::Param(ParamName::Error) . | LifetimeName::Static . | LifetimeName::Error . | LifetimeName::Implicit(_) . | LifetimeName::ImplicitObjectLifetimeDefault . | LifetimeName::Underscore => {} . } . } . 18 ( 0.00%) pub fn walk_poly_trait_ref<'v, V: Visitor<'v>>( . visitor: &mut V, . trait_ref: &'v PolyTraitRef<'v>, . _modifier: TraitBoundModifier, . ) { . walk_list!(visitor, visit_generic_param, trait_ref.bound_generic_params); 46 ( 0.00%) visitor.visit_trait_ref(&trait_ref.trait_ref); 16 ( 0.00%) } . 147 ( 0.00%) pub fn walk_trait_ref<'v, V: Visitor<'v>>(visitor: &mut V, trait_ref: &'v TraitRef<'v>) { 219 ( 0.00%) visitor.visit_id(trait_ref.hir_ref_id); 875 ( 0.00%) visitor.visit_path(&trait_ref.path, trait_ref.hir_ref_id) 168 ( 0.00%) } . . pub fn walk_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v Param<'v>) { 296 ( 0.00%) visitor.visit_id(param.hir_id); 3,032 ( 0.00%) visitor.visit_pat(¶m.pat); . } . 19,222 ( 0.00%) pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item<'v>) { 474 ( 0.00%) visitor.visit_vis(&item.vis); 237 ( 0.00%) visitor.visit_ident(item.ident); 10,696 ( 0.00%) match item.kind { 2 ( 0.00%) ItemKind::ExternCrate(orig_name) => { . visitor.visit_id(item.hir_id()); 4 ( 0.00%) if let Some(orig_name) = orig_name { . visitor.visit_name(item.span, orig_name); . } . } . ItemKind::Use(ref path, _) => { 677 ( 0.00%) visitor.visit_use(path, item.hir_id()); . } . ItemKind::Static(ref typ, _, body) | ItemKind::Const(ref typ, body) => { 39 ( 0.00%) visitor.visit_id(item.hir_id()); 494 ( 0.00%) visitor.visit_ty(typ); 962 ( 0.00%) visitor.visit_nested_body(body); . } 1,605 ( 0.00%) ItemKind::Fn(ref sig, ref generics, body_id) => visitor.visit_fn( 1,744 ( 0.00%) FnKind::ItemFn(item.ident, generics, sig.header, &item.vis), 439 ( 0.00%) &sig.decl, . body_id, 64 ( 0.00%) item.span, 192 ( 0.00%) item.hir_id(), . ), . ItemKind::Macro(_) => { . visitor.visit_id(item.hir_id()); . } 2 ( 0.00%) ItemKind::Mod(ref module) => { . // `visit_mod()` takes care of visiting the `Item`'s `HirId`. . visitor.visit_mod(module, item.span, item.hir_id()) . } . ItemKind::ForeignMod { abi: _, items } => { . visitor.visit_id(item.hir_id()); . walk_list!(visitor, visit_foreign_item_ref, items); . } . ItemKind::GlobalAsm(asm) => { -- line 589 ---------------------------------------- -- line 595 ---------------------------------------- . visitor.visit_ty(ty); . visitor.visit_generics(generics) . } . ItemKind::OpaqueTy(OpaqueTy { ref generics, bounds, .. }) => { . visitor.visit_id(item.hir_id()); . walk_generics(visitor, generics); . walk_list!(visitor, visit_param_bound, bounds); . } 8 ( 0.00%) ItemKind::Enum(ref enum_definition, ref generics) => { 6 ( 0.00%) visitor.visit_generics(generics); . // `visit_enum_def()` takes care of visiting the `Item`'s `HirId`. 7 ( 0.00%) visitor.visit_enum_def(enum_definition, generics, item.hir_id(), item.span) . } . ItemKind::Impl(Impl { . unsafety: _, . defaultness: _, . polarity: _, . constness: _, . defaultness_span: _, 133 ( 0.00%) ref generics, 30 ( 0.00%) ref of_trait, . ref self_ty, 684 ( 0.00%) items, . }) => { 57 ( 0.00%) visitor.visit_id(item.hir_id()); 114 ( 0.00%) visitor.visit_generics(generics); 652 ( 0.00%) walk_list!(visitor, visit_trait_ref, of_trait); 665 ( 0.00%) visitor.visit_ty(self_ty); . walk_list!(visitor, visit_impl_item_ref, items); . } . ItemKind::Struct(ref struct_definition, ref generics) . | ItemKind::Union(ref struct_definition, ref generics) => { 38 ( 0.00%) visitor.visit_generics(generics); 28 ( 0.00%) visitor.visit_id(item.hir_id()); 49 ( 0.00%) visitor.visit_variant_data( . struct_definition, 7 ( 0.00%) item.ident.name, . generics, . item.hir_id(), 7 ( 0.00%) item.span, . ); . } . ItemKind::Trait(.., ref generics, bounds, trait_item_refs) => { . visitor.visit_id(item.hir_id()); . visitor.visit_generics(generics); . walk_list!(visitor, visit_param_bound, bounds); . walk_list!(visitor, visit_trait_item_ref, trait_item_refs); . } . ItemKind::TraitAlias(ref generics, bounds) => { . visitor.visit_id(item.hir_id()); . visitor.visit_generics(generics); . walk_list!(visitor, visit_param_bound, bounds); . } . } 11,480 ( 0.00%) } . . fn walk_inline_asm<'v, V: Visitor<'v>>(visitor: &mut V, asm: &'v InlineAsm<'v>) { . for (op, _op_sp) in asm.operands { . match op { . InlineAsmOperand::In { expr, .. } . | InlineAsmOperand::InOut { expr, .. } . | InlineAsmOperand::Sym { expr, .. } => visitor.visit_expr(expr), . InlineAsmOperand::Out { expr, .. } => { -- line 657 ---------------------------------------- -- line 667 ---------------------------------------- . } . InlineAsmOperand::Const { anon_const } => visitor.visit_anon_const(anon_const), . } . } . } . . pub fn walk_use<'v, V: Visitor<'v>>(visitor: &mut V, path: &'v Path<'v>, hir_id: HirId) { . visitor.visit_id(hir_id); 1,370 ( 0.00%) visitor.visit_path(path, hir_id); . } . 30 ( 0.00%) pub fn walk_enum_def<'v, V: Visitor<'v>>( . visitor: &mut V, . enum_definition: &'v EnumDef<'v>, . generics: &'v Generics<'v>, . item_id: HirId, . ) { . visitor.visit_id(item_id); 171 ( 0.00%) walk_list!(visitor, visit_variant, enum_definition.variants, generics, item_id); 32 ( 0.00%) } . 688 ( 0.00%) pub fn walk_variant<'v, V: Visitor<'v>>( . visitor: &mut V, . variant: &'v Variant<'v>, . generics: &'v Generics<'v>, . parent_item_id: HirId, . ) { 32 ( 0.00%) visitor.visit_ident(variant.ident); 32 ( 0.00%) visitor.visit_id(variant.id); 56 ( 0.00%) visitor.visit_variant_data( . &variant.data, . variant.ident.name, . generics, . parent_item_id, 8 ( 0.00%) variant.span, . ); 186 ( 0.00%) walk_list!(visitor, visit_anon_const, &variant.disr_expr); 608 ( 0.00%) } . 82,259 ( 0.00%) pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty<'v>) { 14,160 ( 0.00%) visitor.visit_id(typ.hir_id); . 50,173 ( 0.00%) match typ.kind { 83 ( 0.00%) TyKind::Slice(ref ty) => visitor.visit_ty(ty), . TyKind::Ptr(ref mutable_type) => visitor.visit_ty(&mutable_type.ty), 1,260 ( 0.00%) TyKind::Rptr(ref lifetime, ref mutable_type) => { 128 ( 0.00%) visitor.visit_lifetime(lifetime); 472 ( 0.00%) visitor.visit_ty(&mutable_type.ty) . } . TyKind::Never => {} 426 ( 0.00%) TyKind::Tup(tuple_element_types) => { 102 ( 0.00%) walk_list!(visitor, visit_ty, tuple_element_types); . } . TyKind::BareFn(ref function_declaration) => { . walk_list!(visitor, visit_generic_param, function_declaration.generic_params); . visitor.visit_fn_decl(&function_declaration.decl); . } 7,193 ( 0.00%) TyKind::Path(ref qpath) => { 9,883 ( 0.00%) visitor.visit_qpath(qpath, typ.hir_id, typ.span); . } . TyKind::OpaqueDef(item_id, lifetimes) => { . visitor.visit_nested_item(item_id); . walk_list!(visitor, visit_generic_arg, lifetimes); . } . TyKind::Array(ref ty, ref length) => { . visitor.visit_ty(ty); . visitor.visit_array_length(length) -- line 733 ---------------------------------------- -- line 736 ---------------------------------------- . for bound in bounds { . visitor.visit_poly_trait_ref(bound, TraitBoundModifier::None); . } . visitor.visit_lifetime(lifetime); . } . TyKind::Typeof(ref expression) => visitor.visit_anon_const(expression), . TyKind::Infer | TyKind::Err => {} . } 14,784 ( 0.00%) } . . pub fn walk_inf<'v, V: Visitor<'v>>(visitor: &mut V, inf: &'v InferArg) { . visitor.visit_id(inf.hir_id); . } . 4,097,791 ( 0.16%) pub fn walk_qpath<'v, V: Visitor<'v>>( . visitor: &mut V, . qpath: &'v QPath<'v>, . id: HirId, . span: Span, . ) { 1,530,203 ( 0.06%) match *qpath { . QPath::Resolved(ref maybe_qself, ref path) => { 504,199 ( 0.02%) walk_list!(visitor, visit_ty, maybe_qself); 632,258 ( 0.03%) visitor.visit_path(path, id) . } . QPath::TypeRelative(ref qself, ref segment) => { 1,523 ( 0.00%) visitor.visit_ty(qself); 1,900 ( 0.00%) visitor.visit_path_segment(span, segment); . } . QPath::LangItem(..) => {} . } 3,459,104 ( 0.14%) } . 353,335 ( 0.01%) pub fn walk_path<'v, V: Visitor<'v>>(visitor: &mut V, path: &'v Path<'v>) { . for segment in path.segments { 60,784 ( 0.00%) visitor.visit_path_segment(path.span, segment); . } 412,196 ( 0.02%) } . 200 ( 0.00%) pub fn walk_path_segment<'v, V: Visitor<'v>>( . visitor: &mut V, . path_span: Span, . segment: &'v PathSegment<'v>, . ) { 45,885 ( 0.00%) visitor.visit_ident(segment.ident); 91,488 ( 0.00%) walk_list!(visitor, visit_id, segment.hir_id); 1,507,617 ( 0.06%) if let Some(ref args) = segment.args { 2,023 ( 0.00%) visitor.visit_generic_args(path_span, args); . } 240 ( 0.00%) } . 16 ( 0.00%) pub fn walk_generic_args<'v, V: Visitor<'v>>( . visitor: &mut V, . _path_span: Span, . generic_args: &'v GenericArgs<'v>, . ) { 924 ( 0.00%) walk_list!(visitor, visit_generic_arg, generic_args.args); 1,769 ( 0.00%) walk_list!(visitor, visit_assoc_type_binding, generic_args.bindings); 14 ( 0.00%) } . 234 ( 0.00%) pub fn walk_assoc_type_binding<'v, V: Visitor<'v>>( . visitor: &mut V, . type_binding: &'v TypeBinding<'v>, . ) { 4 ( 0.00%) visitor.visit_id(type_binding.hir_id); 3 ( 0.00%) visitor.visit_ident(type_binding.ident); 42 ( 0.00%) visitor.visit_generic_args(type_binding.span, type_binding.gen_args); 56 ( 0.00%) match type_binding.kind { 56 ( 0.00%) TypeBindingKind::Equality { ref term } => match term { 46 ( 0.00%) Term::Ty(ref ty) => visitor.visit_ty(ty), . Term::Const(ref c) => visitor.visit_anon_const(c), . }, . TypeBindingKind::Constraint { bounds } => walk_list!(visitor, visit_param_bound, bounds), . } 15 ( 0.00%) } . 126,892 ( 0.01%) pub fn walk_pat<'v, V: Visitor<'v>>(visitor: &mut V, pattern: &'v Pat<'v>) { 12,962 ( 0.00%) visitor.visit_id(pattern.hir_id); 71,232 ( 0.00%) match pattern.kind { 2,682 ( 0.00%) PatKind::TupleStruct(ref qpath, children, _) => { 1,204 ( 0.00%) visitor.visit_qpath(qpath, pattern.hir_id, pattern.span); 636 ( 0.00%) walk_list!(visitor, visit_pat, children); . } 1,448 ( 0.00%) PatKind::Path(ref qpath) => { 4,342 ( 0.00%) visitor.visit_qpath(qpath, pattern.hir_id, pattern.span); . } 3,292 ( 0.00%) PatKind::Struct(ref qpath, fields, _) => { 1,480 ( 0.00%) visitor.visit_qpath(qpath, pattern.hir_id, pattern.span); . for field in fields { 188 ( 0.00%) visitor.visit_id(field.hir_id); 188 ( 0.00%) visitor.visit_ident(field.ident); 2,232 ( 0.00%) visitor.visit_pat(&field.pat) . } . } 594 ( 0.00%) PatKind::Or(pats) => walk_list!(visitor, visit_pat, pats), . PatKind::Tuple(tuple_elements, _) => { 462 ( 0.00%) walk_list!(visitor, visit_pat, tuple_elements); . } . PatKind::Box(ref subpattern) | PatKind::Ref(ref subpattern, _) => { 138 ( 0.00%) visitor.visit_pat(subpattern) . } 936 ( 0.00%) PatKind::Binding(_, _hir_id, ident, ref optional_subpattern) => { . visitor.visit_ident(ident); 7,386 ( 0.00%) walk_list!(visitor, visit_pat, optional_subpattern); . } 86 ( 0.00%) PatKind::Lit(ref expression) => visitor.visit_expr(expression), . PatKind::Range(ref lower_bound, ref upper_bound, _) => { 467 ( 0.00%) walk_list!(visitor, visit_expr, lower_bound); 77 ( 0.00%) walk_list!(visitor, visit_expr, upper_bound); . } . PatKind::Wild => (), . PatKind::Slice(prepatterns, ref slice_pattern, postpatterns) => { . walk_list!(visitor, visit_pat, prepatterns); . walk_list!(visitor, visit_pat, slice_pattern); . walk_list!(visitor, visit_pat, postpatterns); . } . } 96,872 ( 0.00%) } . . pub fn walk_foreign_item<'v, V: Visitor<'v>>(visitor: &mut V, foreign_item: &'v ForeignItem<'v>) { . visitor.visit_id(foreign_item.hir_id()); . visitor.visit_vis(&foreign_item.vis); . visitor.visit_ident(foreign_item.ident); . . match foreign_item.kind { . ForeignItemKind::Fn(ref function_declaration, param_names, ref generics) => { -- line 861 ---------------------------------------- -- line 865 ---------------------------------------- . visitor.visit_ident(param_name); . } . } . ForeignItemKind::Static(ref typ, _) => visitor.visit_ty(typ), . ForeignItemKind::Type => (), . } . } . 458 ( 0.00%) pub fn walk_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v GenericBound<'v>) { 166 ( 0.00%) match *bound { 6 ( 0.00%) GenericBound::Trait(ref typ, modifier) => { 20 ( 0.00%) visitor.visit_poly_trait_ref(typ, modifier); . } . GenericBound::LangItemTrait(_, span, hir_id, args) => { . visitor.visit_id(hir_id); . visitor.visit_generic_args(span, args); . } . GenericBound::Outlives(ref lifetime) => visitor.visit_lifetime(lifetime), . } 276 ( 0.00%) } . 1,512 ( 0.00%) pub fn walk_generic_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v GenericParam<'v>) { 36 ( 0.00%) visitor.visit_id(param.hir_id); 18 ( 0.00%) match param.name { 27 ( 0.00%) ParamName::Plain(ident) => visitor.visit_ident(ident), . ParamName::Error | ParamName::Fresh(_) => {} . } 792 ( 0.00%) match param.kind { . GenericParamKind::Lifetime { .. } => {} 30 ( 0.00%) GenericParamKind::Type { ref default, .. } => walk_list!(visitor, visit_ty, default), . GenericParamKind::Const { ref ty, ref default } => { . visitor.visit_ty(ty); . if let Some(ref default) = default { . visitor.visit_const_param_default(param.hir_id, default); . } . } . } 246 ( 0.00%) walk_list!(visitor, visit_param_bound, param.bounds); 1,332 ( 0.00%) } . . pub fn walk_const_param_default<'v, V: Visitor<'v>>(visitor: &mut V, ct: &'v AnonConst) { . visitor.visit_anon_const(ct) . } . 1,917 ( 0.00%) pub fn walk_generics<'v, V: Visitor<'v>>(visitor: &mut V, generics: &'v Generics<'v>) { 519 ( 0.00%) walk_list!(visitor, visit_generic_param, generics.params); 1,951 ( 0.00%) walk_list!(visitor, visit_where_predicate, generics.where_clause.predicates); 1,704 ( 0.00%) } . 243 ( 0.00%) pub fn walk_where_predicate<'v, V: Visitor<'v>>( . visitor: &mut V, . predicate: &'v WherePredicate<'v>, . ) { 81 ( 0.00%) match *predicate { . WherePredicate::BoundPredicate(WhereBoundPredicate { . ref bounded_ty, 55 ( 0.00%) bounds, 56 ( 0.00%) bound_generic_params, . .. . }) => { 29 ( 0.00%) visitor.visit_ty(bounded_ty); . walk_list!(visitor, visit_param_bound, bounds); . walk_list!(visitor, visit_generic_param, bound_generic_params); . } . WherePredicate::RegionPredicate(WhereRegionPredicate { ref lifetime, bounds, .. }) => { . visitor.visit_lifetime(lifetime); . walk_list!(visitor, visit_param_bound, bounds); . } . WherePredicate::EqPredicate(WhereEqPredicate { . hir_id, ref lhs_ty, ref rhs_ty, .. . }) => { . visitor.visit_id(hir_id); . visitor.visit_ty(lhs_ty); . visitor.visit_ty(rhs_ty); . } . } 216 ( 0.00%) } . . pub fn walk_fn_ret_ty<'v, V: Visitor<'v>>(visitor: &mut V, ret_ty: &'v FnRetTy<'v>) { 2,974 ( 0.00%) if let FnRetTy::Return(ref output_ty) = *ret_ty { 1,341 ( 0.00%) visitor.visit_ty(output_ty) . } . } . 954 ( 0.00%) pub fn walk_fn_decl<'v, V: Visitor<'v>>(visitor: &mut V, function_declaration: &'v FnDecl<'v>) { 1,437 ( 0.00%) for ty in function_declaration.inputs { 477 ( 0.00%) visitor.visit_ty(ty) . } . walk_fn_ret_ty(visitor, &function_declaration.output) 600 ( 0.00%) } . . pub fn walk_fn_kind<'v, V: Visitor<'v>>(visitor: &mut V, function_kind: FnKind<'v>) { 1,990 ( 0.00%) match function_kind { . FnKind::ItemFn(_, generics, ..) => { 133 ( 0.00%) visitor.visit_generics(generics); . } . FnKind::Method(..) | FnKind::Closure => {} . } . } . 10,593 ( 0.00%) pub fn walk_fn<'v, V: Visitor<'v>>( . visitor: &mut V, . function_kind: FnKind<'v>, . function_declaration: &'v FnDecl<'v>, . body_id: BodyId, . _span: Span, . id: HirId, . ) { . visitor.visit_id(id); . visitor.visit_fn_decl(function_declaration); . walk_fn_kind(visitor, function_kind); 1,934 ( 0.00%) visitor.visit_nested_body(body_id) 6,280 ( 0.00%) } . . pub fn walk_trait_item<'v, V: Visitor<'v>>(visitor: &mut V, trait_item: &'v TraitItem<'v>) { . visitor.visit_ident(trait_item.ident); . visitor.visit_generics(&trait_item.generics); . match trait_item.kind { . TraitItemKind::Const(ref ty, default) => { . visitor.visit_id(trait_item.hir_id()); . visitor.visit_ty(ty); -- line 985 ---------------------------------------- -- line 1013 ---------------------------------------- . // N.B., deliberately force a compilation error if/when new fields are added. . let TraitItemRef { id, ident, ref kind, span: _, ref defaultness } = *trait_item_ref; . visitor.visit_nested_trait_item(id); . visitor.visit_ident(ident); . visitor.visit_associated_item_kind(kind); . visitor.visit_defaultness(defaultness); . } . 6,661 ( 0.00%) pub fn walk_impl_item<'v, V: Visitor<'v>>(visitor: &mut V, impl_item: &'v ImplItem<'v>) { . // N.B., deliberately force a compilation error if/when new fields are added. 288 ( 0.00%) let ImplItem { def_id: _, ident, ref vis, ref defaultness, ref generics, ref kind, span: _ } = . *impl_item; . . visitor.visit_ident(ident); 28 ( 0.00%) visitor.visit_vis(vis); . visitor.visit_defaultness(defaultness); 276 ( 0.00%) visitor.visit_generics(generics); 3,815 ( 0.00%) match *kind { . ImplItemKind::Const(ref ty, body) => { . visitor.visit_id(impl_item.hir_id()); . visitor.visit_ty(ty); . visitor.visit_nested_body(body); . } 1,857 ( 0.00%) ImplItemKind::Fn(ref sig, body_id) => { 416 ( 0.00%) visitor.visit_fn( 2,406 ( 0.00%) FnKind::Method(impl_item.ident, sig, Some(&impl_item.vis)), 709 ( 0.00%) &sig.decl, . body_id, 104 ( 0.00%) impl_item.span, 312 ( 0.00%) impl_item.hir_id(), . ); . } . ImplItemKind::TyAlias(ref ty) => { 6 ( 0.00%) visitor.visit_id(impl_item.hir_id()); 86 ( 0.00%) visitor.visit_ty(ty); . } . } 4,768 ( 0.00%) } . . pub fn walk_foreign_item_ref<'v, V: Visitor<'v>>( . visitor: &mut V, . foreign_item_ref: &'v ForeignItemRef, . ) { . // N.B., deliberately force a compilation error if/when new fields are added. . let ForeignItemRef { id, ident, span: _ } = *foreign_item_ref; . visitor.visit_nested_foreign_item(id); . visitor.visit_ident(ident); . } . 224 ( 0.00%) pub fn walk_impl_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, impl_item_ref: &'v ImplItemRef) { . // N.B., deliberately force a compilation error if/when new fields are added. 392 ( 0.00%) let ImplItemRef { id, ident, ref kind, span: _, ref defaultness, trait_item_def_id: _ } = . *impl_item_ref; 140 ( 0.00%) visitor.visit_nested_impl_item(id); . visitor.visit_ident(ident); . visitor.visit_associated_item_kind(kind); . visitor.visit_defaultness(defaultness); 224 ( 0.00%) } . 1,440 ( 0.00%) pub fn walk_struct_def<'v, V: Visitor<'v>>( . visitor: &mut V, . struct_definition: &'v VariantData<'v>, . ) { 898 ( 0.00%) walk_list!(visitor, visit_id, struct_definition.ctor_hir_id()); 1,457 ( 0.00%) walk_list!(visitor, visit_field_def, struct_definition.fields()); 1,275 ( 0.00%) } . 144 ( 0.00%) pub fn walk_field_def<'v, V: Visitor<'v>>(visitor: &mut V, field: &'v FieldDef<'v>) { 144 ( 0.00%) visitor.visit_id(field.hir_id); 108 ( 0.00%) visitor.visit_vis(&field.vis); 108 ( 0.00%) visitor.visit_ident(field.ident); 1,182 ( 0.00%) visitor.visit_ty(&field.ty); . } . 22,931 ( 0.00%) pub fn walk_block<'v, V: Visitor<'v>>(visitor: &mut V, block: &'v Block<'v>) { 764 ( 0.00%) visitor.visit_id(block.hir_id); 6,348 ( 0.00%) walk_list!(visitor, visit_stmt, block.stmts); 12,160 ( 0.00%) walk_list!(visitor, visit_expr, &block.expr); 11,696 ( 0.00%) } . 22,180 ( 0.00%) pub fn walk_stmt<'v, V: Visitor<'v>>(visitor: &mut V, statement: &'v Stmt<'v>) { 1,112 ( 0.00%) visitor.visit_id(statement.hir_id); 44,044 ( 0.00%) match statement.kind { 4,329 ( 0.00%) StmtKind::Local(ref local) => visitor.visit_local(local), 29 ( 0.00%) StmtKind::Item(item) => visitor.visit_nested_item(item), . StmtKind::Expr(ref expression) | StmtKind::Semi(ref expression) => { 16,013 ( 0.00%) visitor.visit_expr(expression) . } . } 10,024 ( 0.00%) } . . pub fn walk_array_len<'v, V: Visitor<'v>>(visitor: &mut V, len: &'v ArrayLen) { . match len { . &ArrayLen::Infer(hir_id, _span) => visitor.visit_id(hir_id), . ArrayLen::Body(c) => visitor.visit_anon_const(c), . } . } . . pub fn walk_anon_const<'v, V: Visitor<'v>>(visitor: &mut V, constant: &'v AnonConst) { . visitor.visit_id(constant.hir_id); . visitor.visit_nested_body(constant.body); . } . 230 ( 0.00%) pub fn walk_let_expr<'v, V: Visitor<'v>>(visitor: &mut V, let_expr: &'v Let<'v>) { . // match the visit order in walk_local 338 ( 0.00%) visitor.visit_expr(let_expr.init); 20 ( 0.00%) visitor.visit_id(let_expr.hir_id); 224 ( 0.00%) visitor.visit_pat(let_expr.pat); 532 ( 0.00%) walk_list!(visitor, visit_ty, let_expr.ty); 200 ( 0.00%) } . 13,834,971 ( 0.55%) pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr<'v>) { 2,961,504 ( 0.12%) visitor.visit_id(expression.hir_id); 7,622,587 ( 0.30%) match expression.kind { . ExprKind::Box(ref subexpression) => visitor.visit_expr(subexpression), . ExprKind::Array(subexpressions) => { 477,552 ( 0.02%) walk_list!(visitor, visit_expr, subexpressions); . } . ExprKind::ConstBlock(ref anon_const) => visitor.visit_anon_const(anon_const), . ExprKind::Repeat(ref element, ref count) => { . visitor.visit_expr(element); . visitor.visit_array_length(count) . } 484,892 ( 0.02%) ExprKind::Struct(ref qpath, fields, ref optional_base) => { 473,193 ( 0.02%) visitor.visit_qpath(qpath, expression.hir_id, expression.span); . for field in fields { 70,100 ( 0.00%) visitor.visit_id(field.hir_id); 52,575 ( 0.00%) visitor.visit_ident(field.ident); 1,174,111 ( 0.05%) visitor.visit_expr(&field.expr) . } 111,007 ( 0.00%) walk_list!(visitor, visit_expr, optional_base); . } . ExprKind::Tup(subexpressions) => { 182,679 ( 0.01%) walk_list!(visitor, visit_expr, subexpressions); . } 429,558 ( 0.02%) ExprKind::Call(ref callee_expression, arguments) => { 393,511 ( 0.02%) visitor.visit_expr(callee_expression); 382,024 ( 0.02%) walk_list!(visitor, visit_expr, arguments); . } 8,478 ( 0.00%) ExprKind::MethodCall(ref segment, arguments, _) => { 5,346 ( 0.00%) visitor.visit_path_segment(expression.span, segment); 11,344 ( 0.00%) walk_list!(visitor, visit_expr, arguments); . } 1,964 ( 0.00%) ExprKind::Binary(_, ref left_expression, ref right_expression) => { 10,353 ( 0.00%) visitor.visit_expr(left_expression); 4,840 ( 0.00%) visitor.visit_expr(right_expression) . } . ExprKind::AddrOf(_, _, ref subexpression) | ExprKind::Unary(_, ref subexpression) => { 372 ( 0.00%) visitor.visit_expr(subexpression) . } . ExprKind::Cast(ref subexpression, ref typ) | ExprKind::Type(ref subexpression, ref typ) => { 1,168 ( 0.00%) visitor.visit_expr(subexpression); 1,079 ( 0.00%) visitor.visit_ty(typ) . } 830 ( 0.00%) ExprKind::DropTemps(ref subexpression) => { 219 ( 0.00%) visitor.visit_expr(subexpression); . } 174 ( 0.00%) ExprKind::Let(ref let_expr) => visitor.visit_let_expr(let_expr), . ExprKind::If(ref cond, ref then, ref else_opt) => { 5,496 ( 0.00%) visitor.visit_expr(cond); 4,312 ( 0.00%) visitor.visit_expr(then); 980 ( 0.00%) walk_list!(visitor, visit_expr, else_opt); . } . ExprKind::Loop(ref block, ref opt_label, _, _) => { 20 ( 0.00%) walk_list!(visitor, visit_label, opt_label); 947 ( 0.00%) visitor.visit_block(block); . } 2,412 ( 0.00%) ExprKind::Match(ref subexpression, arms, _) => { 3,289 ( 0.00%) visitor.visit_expr(subexpression); 1,588 ( 0.00%) walk_list!(visitor, visit_arm, arms); . } 613 ( 0.00%) ExprKind::Closure(_, ref function_declaration, body, _fn_decl_span, _gen) => visitor . .visit_fn( 11 ( 0.00%) FnKind::Closure, 334 ( 0.00%) function_declaration, . body, 77 ( 0.00%) expression.span, 66 ( 0.00%) expression.hir_id, . ), . ExprKind::Block(ref block, ref opt_label) => { 171 ( 0.00%) walk_list!(visitor, visit_label, opt_label); 6,365 ( 0.00%) visitor.visit_block(block); . } 556 ( 0.00%) ExprKind::Assign(ref lhs, ref rhs, _) => { 622 ( 0.00%) visitor.visit_expr(rhs); 86 ( 0.00%) visitor.visit_expr(lhs) . } 334 ( 0.00%) ExprKind::AssignOp(_, ref left_expression, ref right_expression) => { 375 ( 0.00%) visitor.visit_expr(right_expression); 52 ( 0.00%) visitor.visit_expr(left_expression); . } 1,110 ( 0.00%) ExprKind::Field(ref subexpression, ident) => { 280 ( 0.00%) visitor.visit_expr(subexpression); . visitor.visit_ident(ident); . } 138 ( 0.00%) ExprKind::Index(ref main_expression, ref index_expression) => { 399 ( 0.00%) visitor.visit_expr(main_expression); 22 ( 0.00%) visitor.visit_expr(index_expression) . } 270,854 ( 0.01%) ExprKind::Path(ref qpath) => { 830,058 ( 0.03%) visitor.visit_qpath(qpath, expression.hir_id, expression.span); . } . ExprKind::Break(ref destination, ref opt_expr) => { 23 ( 0.00%) walk_list!(visitor, visit_label, &destination.label); 327 ( 0.00%) walk_list!(visitor, visit_expr, opt_expr); . } . ExprKind::Continue(ref destination) => { 8 ( 0.00%) walk_list!(visitor, visit_label, &destination.label); . } . ExprKind::Ret(ref optional_expression) => { 509 ( 0.00%) walk_list!(visitor, visit_expr, optional_expression); . } . ExprKind::InlineAsm(ref asm) => { . walk_inline_asm(visitor, asm); . } . ExprKind::Yield(ref subexpression, _) => { . visitor.visit_expr(subexpression); . } . ExprKind::Lit(_) | ExprKind::Err => {} . } 9,664,504 ( 0.38%) } . 6,282 ( 0.00%) pub fn walk_arm<'v, V: Visitor<'v>>(visitor: &mut V, arm: &'v Arm<'v>) { 424 ( 0.00%) visitor.visit_id(arm.hir_id); 6,813 ( 0.00%) visitor.visit_pat(&arm.pat); 21,645 ( 0.00%) if let Some(ref g) = arm.guard { . match g { 100 ( 0.00%) Guard::If(ref e) => visitor.visit_expr(e), . Guard::IfLet(ref pat, ref e) => { . visitor.visit_pat(pat); . visitor.visit_expr(e); . } . } . } 8,253 ( 0.00%) visitor.visit_expr(&arm.body); 2,544 ( 0.00%) } . 2,410 ( 0.00%) pub fn walk_vis<'v, V: Visitor<'v>>(visitor: &mut V, vis: &'v Visibility<'v>) { 7,548 ( 0.00%) if let VisibilityKind::Restricted { ref path, hir_id } = vis.node { . visitor.visit_id(hir_id); . visitor.visit_path(path, hir_id) . } 2,836 ( 0.00%) } . . pub fn walk_associated_item_kind<'v, V: Visitor<'v>>(_: &mut V, _: &'v AssocItemKind) { . // No visitable content here: this fn exists so you can call it if . // the right thing to do, should content be added in the future, . // would be to walk it. . } . . pub fn walk_defaultness<'v, V: Visitor<'v>>(_: &mut V, _: &'v Defaultness) { -- line 1263 ---------------------------------------- 2,033,204 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/leb128.rs -------------------------------------------------------------------------------- Ir -- line 17 ---------------------------------------- . #[inline] . pub fn $fn_name( . out: &mut [::std::mem::MaybeUninit; max_leb128_len!($int_ty)], . mut value: $int_ty, . ) -> &[u8] { . let mut i = 0; . . loop { 2,723,329 ( 0.11%) if value < 0x80 { . unsafe { 1,023,945 ( 0.04%) *out.get_unchecked_mut(i).as_mut_ptr() = value as u8; . } . 1,465,318 ( 0.06%) i += 1; . break; . } else { . unsafe { 1,608,884 ( 0.06%) *out.get_unchecked_mut(i).as_mut_ptr() = ((value & 0x7f) | 0x80) as u8; . } . 615,571 ( 0.02%) value >>= 7; . i += 1; . } . } . . unsafe { ::std::mem::MaybeUninit::slice_assume_init_ref(&out.get_unchecked(..i)) } . } . }; . } -- line 45 ---------------------------------------- -- line 53 ---------------------------------------- . macro_rules! impl_read_unsigned_leb128 { . ($fn_name:ident, $int_ty:ty) => { . #[inline] . pub fn $fn_name(slice: &[u8], position: &mut usize) -> $int_ty { . // The first iteration of this loop is unpeeled. This is a . // performance win because this code is hot and integer values less . // than 128 are very common, typically occurring 50-80% or more of . // the time, even for u64 and u128. 1,836,724 ( 0.07%) let byte = slice[*position]; 918,362 ( 0.04%) *position += 1; 918,362 ( 0.04%) if (byte & 0x80) == 0 { 156 ( 0.00%) return byte as $int_ty; . } 1,180 ( 0.00%) let mut result = (byte & 0x7F) as $int_ty; . let mut shift = 7; . loop { 694,242 ( 0.03%) let byte = slice[*position]; 455,513 ( 0.02%) *position += 1; 462,828 ( 0.02%) if (byte & 0x80) == 0 { 387,311 ( 0.02%) result |= (byte as $int_ty) << shift; . return result; . } else { . result |= ((byte & 0x7F) as $int_ty) << shift; . } . shift += 7; . } . } . }; -- line 80 ---------------------------------------- 1,037,049 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs -------------------------------------------------------------------------------- Ir -- line 71 ---------------------------------------- . AlreadyParsed(P), . } . . impl From> for LhsExpr { . /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)` . /// and `None` into `LhsExpr::NotYetParsed`. . /// . /// This conversion does not allocate. 5 ( 0.00%) fn from(o: Option) -> Self { 75,798 ( 0.00%) if let Some(attrs) = o { LhsExpr::AttributesParsed(attrs) } else { LhsExpr::NotYetParsed } 5 ( 0.00%) } . } . . impl From> for LhsExpr { . /// Converts the `expr: P` into `LhsExpr::AlreadyParsed(expr)`. . /// . /// This conversion does not allocate. . fn from(expr: P) -> Self { . LhsExpr::AlreadyParsed(expr) -- line 89 ---------------------------------------- -- line 96 ---------------------------------------- . pub fn parse_expr(&mut self) -> PResult<'a, P> { . self.current_closure.take(); . . self.parse_expr_res(Restrictions::empty(), None) . } . . /// Parses an expression, forcing tokens to be collected . pub fn parse_expr_force_collect(&mut self) -> PResult<'a, P> { 6 ( 0.00%) 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 }) . } . 78,360 ( 0.00%) fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P> { 19,590 ( 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), . }, . } 97,950 ( 0.00%) } . . /// Parses a sequence of expressions delimited by parentheses. . fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec>> { 36,018 ( 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> { 123,071 ( 0.00%) self.parse_assoc_expr_with(0, already_parsed_attrs.into()) . } . . /// Parses an associative expression with operators of at least `min_prec` precedence. 342,441 ( 0.01%) pub(super) fn parse_assoc_expr_with( . &mut self, . min_prec: usize, . lhs: LhsExpr, . ) -> PResult<'a, P> { 190,214 ( 0.01%) let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs { 524 ( 0.00%) expr . } else { 75,836 ( 0.00%) let attrs = match lhs { 76,516 ( 0.00%) LhsExpr::AttributesParsed(attrs) => Some(attrs), . _ => None, . }; 37,918 ( 0.00%) if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) { 8 ( 0.00%) return self.parse_prefix_range_expr(attrs); . } else { 454,992 ( 0.02%) self.parse_prefix_expr(attrs)? . } . }; 76,094 ( 0.00%) let last_type_ascription_set = self.last_type_ascription.is_some(); . . if !self.should_continue_as_assoc_expr(&lhs) { 330 ( 0.00%) self.last_type_ascription = None; . return Ok(lhs); . } . . self.expected_tokens.push(TokenType::Operator); 936 ( 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. 1,404 ( 0.00%) let lhs_span = match self.prev_token.kind { . TokenKind::Interpolated(..) => self.prev_token.span, . _ => lhs.span, . }; . 468 ( 0.00%) let cur_op_span = self.token.span; 1,872 ( 0.00%) let restrictions = if op.node.is_assign_like() { . self.restrictions & Restrictions::NO_STRUCT_LITERAL . } else { . self.restrictions . }; 702 ( 0.00%) let prec = op.node.precedence(); 468 ( 0.00%) if prec < min_prec { . break; . } . // Check for deprecated `...` syntax 860 ( 0.00%) if self.token == token::DotDotDot && op.node == AssocOp::DotDotEq { . self.err_dotdotdot_syntax(self.token.span); . } . 860 ( 0.00%) if self.token == token::LArrow { . self.err_larrow_operator(self.token.span); . } . 215 ( 0.00%) self.bump(); 860 ( 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 253 ( 0.00%) if (op.node == AssocOp::Equal || op.node == AssocOp::NotEqual) 38 ( 0.00%) && 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 226 ---------------------------------------- -- line 231 ---------------------------------------- . sugg.to_string(), . Applicability::MachineApplicable, . ) . .emit(); . self.bump(); . } . . // Look for PHP's `<>` and recover 29 ( 0.00%) if op.node == AssocOp::Less 10 ( 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(); . } . 430 ( 0.00%) let op = op.node; . // Special cases: . if op == AssocOp::As { 85 ( 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. 20 ( 0.00%) lhs = self.parse_range_expr(prec, lhs, op, cur_op_span)?; . break; . } . 193 ( 0.00%) let fixity = op.fixity(); 579 ( 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, . }; 386 ( 0.00%) let rhs = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| { 965 ( 0.00%) this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed) . })?; . . let span = self.mk_expr_sp(&lhs, lhs_span, rhs.span); 1,858 ( 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 => { 248 ( 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") . } . }; . 386 ( 0.00%) if let Fixity::None = fixity { . break; . } . } 37,937 ( 0.00%) if last_type_ascription_set { . self.last_type_ascription = None; . } 75,874 ( 0.00%) Ok(lhs) 646,559 ( 0.03%) } . . fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool { 266,549 ( 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> { 419,903 ( 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), . ), . _, 16 ( 0.00%) ) if self.restrictions.contains(Restrictions::CONST_EXPR) => { . return None; . } 468 ( 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 { 82,022 ( 0.00%) self.restrictions.contains(Restrictions::STMT_EXPR) 1,668 ( 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, . op: AssocOp, . cur_op_span: Span, . ) -> PResult<'a, P> { . let rhs = if self.is_at_start_of_range_notation_rhs() { 9 ( 0.00%) Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?) . } else { 8 ( 0.00%) None . }; 2 ( 0.00%) let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span); . let span = self.mk_expr_sp(&lhs, lhs.span, rhs_span); . let limits = . if op == AssocOp::DotDot { RangeLimits::HalfOpen } else { RangeLimits::Closed }; 15 ( 0.00%) let range = self.mk_range(Some(lhs), rhs, limits); . Ok(self.mk_expr(span, range, AttrVec::new())) . } . . fn is_at_start_of_range_notation_rhs(&self) -> bool { 30 ( 0.00%) if self.token.can_begin_expr() { . // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`. 15 ( 0.00%) if self.token == token::OpenDelim(token::Brace) { . return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL); . } . true . } else { . false . } . } . . /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`. . fn parse_prefix_range_expr(&mut self, attrs: Option) -> PResult<'a, P> { . // Check for deprecated `...` syntax. 10 ( 0.00%) if self.token == token::DotDotDot { . self.err_dotdotdot_syntax(self.token.span); . } . . debug_assert!( . [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind), . "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq", . self.token . ); . 6 ( 0.00%) let limits = match self.token.kind { . token::DotDot => RangeLimits::HalfOpen, . _ => RangeLimits::Closed, . }; 4 ( 0.00%) let op = AssocOp::from_token(&self.token); . // FIXME: `parse_prefix_range_expr` is called when the current . // token is `DotDot`, `DotDotDot`, or `DotDotEq`. If we haven't already . // parsed attributes, then trying to parse them here will always fail. . // We should figure out how we want attributes on range expressions to work. 8 ( 0.00%) let attrs = self.parse_or_use_outer_attributes(attrs)?; . self.collect_tokens_for_expr(attrs, |this, attrs| { 4 ( 0.00%) let lo = this.token.span; 4 ( 0.00%) this.bump(); . let (span, opt_end) = if this.is_at_start_of_range_notation_rhs() { . // RHS must be parsed with more associativity than the dots. 20 ( 0.00%) this.parse_assoc_expr_with(op.unwrap().precedence() + 1, LhsExpr::NotYetParsed) 10 ( 0.00%) .map(|x| (lo.to(x.span), Some(x)))? . } else { . (lo, None) . }; 6 ( 0.00%) let range = this.mk_range(None, opt_end, limits); 14 ( 0.00%) Ok(this.mk_expr(span, range, attrs.into())) . }) . } . . /// Parses a prefix-unary-operator expr. 265,825 ( 0.01%) fn parse_prefix_expr(&mut self, attrs: Option) -> PResult<'a, P> { 303,800 ( 0.01%) let attrs = self.parse_or_use_outer_attributes(attrs)?; 189,875 ( 0.01%) let lo = self.token.span; . . macro_rules! make_it { . ($this:ident, $attrs:expr, |this, _| $body:expr) => { 501 ( 0.00%) $this.collect_tokens_for_expr($attrs, |$this, attrs| { 553 ( 0.00%) let (hi, ex) = $body?; 944 ( 0.00%) Ok($this.mk_expr(lo.to(hi), ex, attrs.into())) 560 ( 0.00%) }) . }; . } . . let this = self; . . // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr() 228,058 ( 0.01%) match this.token.uninterpolate().kind { 18 ( 0.00%) 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) => { 12 ( 0.00%) make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Deref)) . } // `*expr` . token::BinOp(token::And) | token::AndAnd => { 58 ( 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` 58,164 ( 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)), . } 379,750 ( 0.02%) } . . fn parse_prefix_expr_common(&mut self, lo: Span) -> PResult<'a, (Span, P)> { 60 ( 0.00%) self.bump(); 120 ( 0.00%) let expr = self.parse_prefix_expr(None); 30 ( 0.00%) let (span, expr) = self.interpolated_or_expr_span(expr)?; 60 ( 0.00%) Ok((lo.to(span), expr)) . } . . fn parse_unary_expr(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> { . let (span, expr) = self.parse_prefix_expr_common(lo)?; . Ok((span, self.mk_unary(op, expr))) . } . . // Recover on `!` suggesting for bitwise negation instead. -- line 598 ---------------------------------------- -- 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(), . }; 58,164 ( 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| { . ( 151,959 ( 0.01%) match self.prev_token.kind { . TokenKind::Interpolated(..) => self.prev_token.span, . _ => e.span, . }, . e, . ) . }) . } . 238 ( 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), 51 ( 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. 34 ( 0.00%) let parser_snapshot_before_type = self.clone(); 51 ( 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) 204 ( 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; 102 ( 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. 102 ( 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()?; 145 ( 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); 116 ( 0.00%) let expr = self.parse_prefix_expr(None); 58 ( 0.00%) let (hi, expr) = self.interpolated_or_expr_span(expr)?; 29 ( 0.00%) let span = lo.to(hi); 58 ( 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) { 58 ( 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)?; 151,664 ( 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 266,329 ( 0.01%) self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| { 266,329 ( 0.01%) expr.map(|mut expr| { 38,047 ( 0.00%) attrs.extend::>(expr.attrs.into()); 76,094 ( 0.00%) expr.attrs = attrs.into(); 532,658 ( 0.02%) expr . }) . }) . } . 1,179,984 ( 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?` 20 ( 0.00%) e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e), AttrVec::new()); . continue; . } . if self.eat(&token::Dot) { . // expr.f 772 ( 0.00%) e = self.parse_dot_suffix_expr(lo, e)?; . continue; . } 696 ( 0.00%) if self.expr_is_complete(&e) { . return Ok(e); . } 129,653 ( 0.01%) e = match self.token.kind { 17,700 ( 0.00%) token::OpenDelim(token::Paren) => self.parse_fn_call_expr(lo, e), 22 ( 0.00%) token::OpenDelim(token::Bracket) => self.parse_index_expr(lo, e)?, 37,954 ( 0.00%) _ => return Ok(e), . } . } 342,576 ( 0.01%) } . . fn look_ahead_type_ascription_as_field(&mut self) -> bool { 41,232 ( 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> { 2,130 ( 0.00%) match self.token.uninterpolate().kind { . token::Ident(..) => self.parse_dot_suffix(base, lo), 6 ( 0.00%) token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => { 9 ( 0.00%) 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)) . } . _ => { . self.error_unexpected_after_dot(); . Ok(base) . } -- line 960 ---------------------------------------- -- line 1071 ---------------------------------------- . // See the FIXME about `TokenCursor` above. . self.error_unexpected_after_dot(); . base . } . _ => panic!("unexpected components in a float token: {:?}", components), . } . } . 13 ( 0.00%) fn parse_tuple_field_access_expr( . &mut self, . lo: Span, . base: P, . field: Symbol, . suffix: Option, . next_token: Option<(Token, Spacing)>, . ) -> P { 2 ( 0.00%) match next_token { . Some(next_token) => self.bump_with(next_token), 3 ( 0.00%) None => self.bump(), . } 1 ( 0.00%) let span = self.prev_token.span; 4 ( 0.00%) let field = ExprKind::Field(base, Ident::new(field, span)); 6 ( 0.00%) self.expect_no_suffix(span, "a tuple index", suffix); 3 ( 0.00%) self.mk_expr(lo.to(span), field, AttrVec::new()) 8 ( 0.00%) } . . /// Parse a function call expression, `expr(...)`. . fn parse_fn_call_expr(&mut self, lo: Span, fun: P) -> P { 29,500 ( 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 { 17,700 ( 0.00%) None . }; 5,900 ( 0.00%) let open_paren = self.token.span; . 11,800 ( 0.00%) let mut seq = self.parse_paren_expr_seq().map(|args| { 17,700 ( 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; . } 29,500 ( 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> { 59,000 ( 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(), . } . } . _ => {} 17,700 ( 0.00%) } . None . } . . /// Parse an indexing expression `expr[...]`. . fn parse_index_expr(&mut self, lo: Span, base: P) -> PResult<'a, P> { 22 ( 0.00%) self.bump(); // `[` 22 ( 0.00%) let index = self.parse_expr()?; 33 ( 0.00%) self.expect(&token::CloseDelim(token::Bracket))?; 33 ( 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> { 384 ( 0.00%) if self.token.uninterpolated_span().rust_2018() && self.eat_keyword(kw::Await) { . return Ok(self.mk_await_expr(self_arg, lo)); . } . 192 ( 0.00%) let fn_span_lo = self.token.span; 1,152 ( 0.00%) let mut segment = self.parse_path_segment(PathStyle::Expr, None)?; 960 ( 0.00%) self.check_trailing_angle_brackets(&segment, &[&token::OpenDelim(token::Paren)]); . self.check_turbofish_missing_angle_brackets(&mut segment); . 960 ( 0.00%) if self.check(&token::OpenDelim(token::Paren)) { . // Method call `expr.f()` 123 ( 0.00%) let mut args = self.parse_paren_expr_seq()?; 492 ( 0.00%) args.insert(0, self_arg); . 369 ( 0.00%) let fn_span = fn_span_lo.to(self.prev_token.span); 369 ( 0.00%) let span = lo.to(self.prev_token.span); 615 ( 0.00%) Ok(self.mk_expr(span, ExprKind::MethodCall(segment, args, fn_span), AttrVec::new())) . } else { . // Field access `expr.f` 138 ( 0.00%) if let Some(args) = segment.args { . self.struct_span_err( . args.span(), . "field expressions cannot have generic arguments", . ) . .emit(); . } . 207 ( 0.00%) let span = lo.to(self.prev_token.span); 345 ( 0.00%) Ok(self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), AttrVec::new())) . } . } . . /// 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> { 95,511 ( 0.00%) maybe_recover_from_interpolated_ty_qpath!(self, true); 113,790 ( 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. 37,913 ( 0.00%) let attrs = AttrVec::new(); . . // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`. 16,523 ( 0.00%) let lo = self.token.span; 113,739 ( 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. 85,560 ( 0.00%) self.parse_lit_expr(attrs) 82,615 ( 0.00%) } else if self.check(&token::OpenDelim(token::Paren)) { 5,820 ( 0.00%) self.parse_tuple_parens_expr(attrs) 72,915 ( 0.00%) } else if self.check(&token::OpenDelim(token::Brace)) { 200 ( 0.00%) self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs) 145,525 ( 0.01%) } else if self.check(&token::BinOp(token::Or)) || self.check(&token::OrOr) { 44 ( 0.00%) self.parse_closure_expr(attrs) 72,735 ( 0.00%) } else if self.check(&token::OpenDelim(token::Bracket)) { 30 ( 0.00%) self.parse_array_or_repeat_expr(attrs, token::Bracket) 58,164 ( 0.00%) } else if self.check_path() { 57,324 ( 0.00%) self.parse_path_start_expr(attrs) 2,100 ( 0.00%) } else if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) { . self.parse_closure_expr(attrs) 1,050 ( 0.00%) } else if self.eat_keyword(kw::If) { 236 ( 0.00%) self.parse_if_expr(attrs) 755 ( 0.00%) } else if self.check_keyword(kw::For) { 60 ( 0.00%) 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 { 60 ( 0.00%) assert!(self.eat_keyword(kw::For)); 84 ( 0.00%) self.parse_for_expr(None, self.prev_token.span, attrs) . } 695 ( 0.00%) } else if self.eat_keyword(kw::While) { 21 ( 0.00%) self.parse_while_expr(None, self.prev_token.span, attrs) 544 ( 0.00%) } else if let Some(label) = self.eat_label() { . self.parse_labeled_expr(label, attrs, true) 680 ( 0.00%) } else if self.eat_keyword(kw::Loop) { 49 ( 0.00%) self.parse_loop_expr(None, self.prev_token.span, attrs) 645 ( 0.00%) } else if self.eat_keyword(kw::Continue) { 40 ( 0.00%) let kind = ExprKind::Continue(self.eat_label()); 32 ( 0.00%) Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs)) 484 ( 0.00%) } else if self.eat_keyword(kw::Match) { 44 ( 0.00%) let match_sp = self.prev_token.span; 176 ( 0.00%) self.parse_match_expr(attrs).map_err(|mut err| { . err.span_label(match_sp, "while parsing this match expression"); . err . }) 396 ( 0.00%) } else if self.eat_keyword(kw::Unsafe) { . self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided), attrs) 396 ( 0.00%) } else if self.check_inline_const(0) { . self.parse_const_block(lo.to(self.token.span), false) 297 ( 0.00%) } else if self.is_do_catch_block() { . self.recover_do_catch(attrs) 297 ( 0.00%) } else if self.is_try_block() { . self.expect_keyword(kw::Try)?; . self.parse_try_block(lo, attrs) 396 ( 0.00%) } else if self.eat_keyword(kw::Return) { 112 ( 0.00%) self.parse_return_expr(attrs) 284 ( 0.00%) } else if self.eat_keyword(kw::Break) { 40 ( 0.00%) self.parse_break_expr(attrs) 244 ( 0.00%) } else if self.eat_keyword(kw::Yield) { . self.parse_yield_expr(attrs) 244 ( 0.00%) } else if self.eat_keyword(kw::Let) { 20 ( 0.00%) self.parse_let_expr(attrs) 224 ( 0.00%) } else if self.eat_keyword(kw::Underscore) { . Ok(self.mk_expr(self.prev_token.span, ExprKind::Underscore, attrs)) 56 ( 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)) 112 ( 0.00%) } else if self.token.uninterpolated_span().rust_2018() { . // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly. 200 ( 0.00%) 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) . } 200 ( 0.00%) } else if self.eat_keyword(kw::Await) { . self.recover_incorrect_await_syntax(lo, self.prev_token.span, attrs) . } else { 200 ( 0.00%) self.parse_lit_expr(attrs) . } . } else { 24 ( 0.00%) self.parse_lit_expr(attrs) . } . } . 214,460 ( 0.01%) fn parse_lit_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { 42,892 ( 0.00%) let lo = self.token.span; 85,784 ( 0.00%) match self.parse_opt_lit() { 128,676 ( 0.01%) Some(literal) => { 193,014 ( 0.01%) let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(literal), attrs); 214,460 ( 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> { 3,880 ( 0.00%) let lo = self.token.span; 5,820 ( 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), 7,664 ( 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))), . }; 9,700 ( 0.00%) let kind = if es.len() == 1 && !trailing_comma { . // `(e)` is parenthesized `e`. 81 ( 0.00%) ExprKind::Paren(es.into_iter().next().unwrap()) . } else { . // `(e,)` is a tuple with only one field, `e`. 9,565 ( 0.00%) ExprKind::Tup(es) . }; 5,820 ( 0.00%) let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs); 5,820 ( 0.00%) self.maybe_recover_from_bad_qpath(expr, true) . } . 66 ( 0.00%) fn parse_array_or_repeat_expr( . &mut self, . attrs: AttrVec, . close_delim: token::DelimToken, . ) -> PResult<'a, P> { 18 ( 0.00%) let lo = self.token.span; 6 ( 0.00%) self.bump(); // `[` or other open delim . 18 ( 0.00%) let close = &token::CloseDelim(close_delim); . let kind = if self.eat(close) { . // Empty vector . ExprKind::Array(Vec::new()) . } else { . // Non-empty vector 12 ( 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())?; 6 ( 0.00%) let mut exprs = vec![first_expr]; . exprs.extend(remaining_exprs); 30 ( 0.00%) ExprKind::Array(exprs) . } else { . // Vector with one element . self.expect(close)?; . ExprKind::Array(vec![first_expr]) . } . }; 18 ( 0.00%) let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs); 18 ( 0.00%) self.maybe_recover_from_bad_qpath(expr, true) 60 ( 0.00%) } . 143,310 ( 0.01%) fn parse_path_start_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { 114,648 ( 0.00%) let (qself, path) = if self.eat_lt() { . let (qself, path) = self.parse_qpath(PathStyle::Expr)?; . (Some(qself), path) . } else { 28,662 ( 0.00%) (None, self.parse_path(PathStyle::Expr)?) . }; 14,331 ( 0.00%) let lo = path.span; . . // `!`, as an operator, is prefix, so we know this isn't that. 127,515 ( 0.01%) let (hi, kind) = if self.eat(&token::Not) { . // MACRO INVOCATION expression 4 ( 0.00%) if qself.is_some() { . self.struct_span_err(path.span, "macros cannot use qualified paths").emit(); . } 24 ( 0.00%) let mac = MacCall { 28 ( 0.00%) path, . args: self.parse_mac_args()?, . prior_type_ascription: self.last_type_ascription, . }; 88 ( 0.00%) (self.prev_token.span, ExprKind::MacCall(mac)) 71,635 ( 0.00%) } else if self.check(&token::OpenDelim(token::Brace)) { 11,660 ( 0.00%) if let Some(expr) = self.maybe_parse_struct_expr(qself.as_ref(), &path, &attrs) { 5,830 ( 0.00%) 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)) . }; . 17,002 ( 0.00%) let expr = self.mk_expr(lo.to(hi), kind, attrs); 25,503 ( 0.00%) self.maybe_recover_from_bad_qpath(expr, true) 160,312 ( 0.01%) } . . /// 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 1507 ---------------------------------------- . .note("following RFC #2388, the new non-placeholder syntax is `try`") . .emit(); . . self.parse_try_block(lo, attrs) . } . . /// Parse an expression if the token can begin one. . fn parse_expr_opt(&mut self) -> PResult<'a, Option>> { 177 ( 0.00%) Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None }) . } . . /// Parse `"return" expr?`. 280 ( 0.00%) fn parse_return_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { 28 ( 0.00%) let lo = self.prev_token.span; 56 ( 0.00%) let kind = ExprKind::Ret(self.parse_expr_opt()?); 84 ( 0.00%) let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs); 168 ( 0.00%) self.maybe_recover_from_bad_qpath(expr, true) 280 ( 0.00%) } . . /// Parse `"break" (('label (:? expr)?) | expr?)` with `"break"` token already eaten. . /// If the label is followed immediately by a `:` token, the label and `:` are . /// parsed as part of the expression (i.e. a labeled loop). The language team has . /// decided in #87026 to require parentheses as a visual aid to avoid confusion if . /// the break expression of an unlabeled break is a labeled loop (as in . /// `break 'lbl: loop {}`); a labeled break with an unlabeled loop as its value . /// expression only gets a warning for compatibility reasons; and a labeled break . /// with a labeled loop does not even get a warning because there is no ambiguity. 100 ( 0.00%) fn parse_break_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { 20 ( 0.00%) let lo = self.prev_token.span; . let mut label = self.eat_label(); . let kind = if label.is_some() && self.token == token::Colon { . // The value expression can be a labeled loop, see issue #86948, e.g.: . // `loop { break 'label: loop { break 'label 42; }; }` . let lexpr = self.parse_labeled_expr(label.take().unwrap(), AttrVec::new(), true)?; . self.struct_span_err( . lexpr.span, . "parentheses are required around this expression to avoid confusion with a labeled break expression", -- line 1543 ---------------------------------------- -- line 1547 ---------------------------------------- . vec![ . (lexpr.span.shrink_to_lo(), "(".to_string()), . (lexpr.span.shrink_to_hi(), ")".to_string()), . ], . Applicability::MachineApplicable, . ) . .emit(); . Some(lexpr) 20 ( 0.00%) } else if self.token != token::OpenDelim(token::Brace) . || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL) . { . let expr = self.parse_expr_opt()?; . if let Some(ref expr) = expr { . if label.is_some() . && matches!( . expr.kind, . ExprKind::While(_, _, None) -- line 1563 ---------------------------------------- -- line 1570 ---------------------------------------- . BREAK_WITH_LABEL_AND_LOOP, . lo.to(expr.span), . ast::CRATE_NODE_ID, . "this labeled break expression is easy to confuse with an unlabeled break with a labeled value expression", . BuiltinLintDiagnostics::BreakWithLabelAndLoop(expr.span), . ); . } . } 20 ( 0.00%) expr . } else { . None . }; 30 ( 0.00%) let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind), attrs); 50 ( 0.00%) self.maybe_recover_from_bad_qpath(expr, true) 100 ( 0.00%) } . . /// Parse `"yield" expr?`. . fn parse_yield_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { . let lo = self.prev_token.span; . let kind = ExprKind::Yield(self.parse_expr_opt()?); . let span = lo.to(self.prev_token.span); . self.sess.gated_spans.gate(sym::generators, span); . let expr = self.mk_expr(span, kind, attrs); -- line 1592 ---------------------------------------- -- line 1607 ---------------------------------------- . symbol_unescaped, . }), . _ => Err(Some(lit)), . }, . None => Err(None), . } . } . 315 ( 0.00%) pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> { 35 ( 0.00%) self.parse_opt_lit().ok_or_else(|| { 38 ( 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(); . } . } . } 209 ( 0.00%) let msg = format!("unexpected token: {}", super::token_descr(&self.token)); 19 ( 0.00%) self.struct_span_err(self.token.span, &msg) . }) 245 ( 0.00%) } . . /// Matches `lit = true | false | token_lit`. . /// Returns `None` if the next token is not a literal. 193,329 ( 0.01%) pub(super) fn parse_opt_lit(&mut self) -> Option { 21,481 ( 0.00%) let mut recovered = None; 128,886 ( 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); 64,500 ( 0.00%) match Lit::from_token(token) { 128,772 ( 0.01%) Ok(lit) => { 42,924 ( 0.00%) self.bump(); 128,772 ( 0.01%) Some(lit) . } 19 ( 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!())) . } . } 171,848 ( 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 1759 ---------------------------------------- . .emit(); . } . LitError::IntTooLarge => { . self.struct_span_err(span, "integer literal is too large").emit(); . } . } . } . 7 ( 0.00%) pub(super) fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option) { 2 ( 0.00%) if let Some(suf) = suffix { . let mut err = if kind == "a tuple index" . && [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf) . { . // #59553: warn instead of reject out of hand to allow the fix to percolate . // through the ecosystem when people fix their macros . let mut err = self . .sess . .span_diagnostic -- line 1776 ---------------------------------------- -- line 1791 ---------------------------------------- . ); . err . } else { . self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind)) . }; . err.span_label(sp, format!("invalid suffix `{}`", suf)); . err.emit(); . } 6 ( 0.00%) } . . /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`). . /// Keep this in sync with `Token::can_begin_literal_maybe_minus`. 128 ( 0.00%) pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P> { 32 ( 0.00%) maybe_whole_expr!(self); . 16 ( 0.00%) let lo = self.token.span; . let minus_present = self.eat(&token::BinOp(token::Minus)); 32 ( 0.00%) let lit = self.parse_lit()?; 16 ( 0.00%) let expr = self.mk_expr(lit.span, ExprKind::Lit(lit), AttrVec::new()); . 32 ( 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) . } 144 ( 0.00%) } . . fn is_array_like_block(&mut self) -> bool { 65 ( 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. 350 ( 0.00%) pub(super) fn parse_block_expr( . &mut self, . opt_label: Option::C`, in which case the given . /// substitutions and environment are used to resolve the constant. Alternatively if the . /// constant has generic parameters in scope the substitutions are used to evaluate the value of . /// the constant. For example in `fn foo() { let _ = [0; bar::()]; }` the repeat count . /// constant `bar::()` requires a substitution for `T`, if the substitution for `T` is still -- line 1576 ---------------------------------------- -- line 1606 ---------------------------------------- . // variables, thus we don't need to substitute back the original values. . self.tcx.const_eval_resolve(param_env_erased, unevaluated, span) . } . . /// If `typ` is a type variable of some kind, resolve it one level . /// (but do not resolve types found in the result). If `typ` is . /// not a type variable, just return it unmodified. . // FIXME(eddyb) inline into `ShallowResolver::visit_ty`. 1,794,928 ( 0.07%) fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> { 562,783 ( 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`. 121,348 ( 0.00%) let known = self.inner.borrow_mut().type_variables().probe(v).known(); . known.map_or(typ, |t| self.shallow_resolve_ty(t)) . } . 4,320 ( 0.00%) ty::Infer(ty::IntVar(v)) => self . .inner . .borrow_mut() . .int_unification_table() . .probe_value(v) 1,215 ( 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, . } 2,019,294 ( 0.08%) } . . /// `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))`. 70,031 ( 0.00%) match self.inner.borrow_mut().type_variables().inlined_probe(v) { . TypeVariableValue::Unknown { .. } => false, . TypeVariableValue::Known { .. } => true, . } . } . . TyOrConstInferVar::TyInt(v) => { . // If `inlined_probe_value` returns a value it's always a . // `ty::Int(_)` or `ty::UInt(_)`, which never matches a . // `ty::Infer(_)`. 2,408 ( 0.00%) self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some() . } . . TyOrConstInferVar::TyFloat(v) => { . // If `probe_value` returns a value it's always a . // `ty::Float(_)`, which never matches a `ty::Infer(_)`. . // . // Not `inlined_probe_value(v)` because this call site is colder. . self.inner.borrow_mut().float_unification_table().probe_value(v).is_some() -- line 1688 ---------------------------------------- -- 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`). 1,115 ( 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, . } 1,115 ( 0.00%) } . . /// Tries to extract an inference variable from a type, returns `None` . /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`). 66 ( 0.00%) pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option { 10,541 ( 0.00%) match *ty.kind() { 2,274 ( 0.00%) ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)), 88 ( 0.00%) ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)), . ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)), . _ => None, . } 66 ( 0.00%) } . . /// Tries to extract an inference variable from a constant, returns `None` . /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`). . pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option { . match ct.val { . ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)), . _ => None, . } -- line 1749 ---------------------------------------- -- 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> { 427,817 ( 0.02%) self.infcx.shallow_resolve_ty(ty) . } . 952 ( 0.00%) fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 946 ( 0.00%) if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct { 1,175 ( 0.00%) self.infcx . .inner . .borrow_mut() . .const_unification_table() 705 ( 0.00%) .probe_value(*vid) . .val . .known() . .unwrap_or(ct) . } else { . ct . } 1,190 ( 0.00%) } . } . . impl<'tcx> TypeTrace<'tcx> { . pub fn span(&self) -> Span { 12 ( 0.00%) self.cause.span . } . . pub fn types( . cause: &ObligationCause<'tcx>, . a_is_expected: bool, . a: Ty<'tcx>, . b: Ty<'tcx>, . ) -> TypeTrace<'tcx> { -- line 1792 ---------------------------------------- -- line 1800 ---------------------------------------- . b: &'tcx ty::Const<'tcx>, . ) -> TypeTrace<'tcx> { . TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) } . } . } . . impl<'tcx> SubregionOrigin<'tcx> { . pub fn span(&self) -> Span { 30 ( 0.00%) match *self { 6 ( 0.00%) Subtype(ref a) => a.span(), . RelateObjectBound(a) => a, . RelateParamBound(a, ..) => a, . RelateRegionParamBound(a) => a, . Reborrow(a) => a, . ReborrowUpvar(a, _) => a, . DataBorrowed(_, a) => a, . ReferenceOutlivesReferent(_, a) => a, . CompareImplMethodObligation { span, .. } => span, -- line 1817 ---------------------------------------- -- line 1818 ---------------------------------------- . CompareImplTypeObligation { span, .. } => span, . } . } . . pub fn from_obligation_cause(cause: &traits::ObligationCause<'tcx>, default: F) -> Self . where . F: FnOnce() -> Self, . { 2,511 ( 0.00%) match *cause.code() { 438 ( 0.00%) traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => { 2,190 ( 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 ---------------------------------------- 712,423 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/hir/map/mod.rs -------------------------------------------------------------------------------- Ir -- line 17 ---------------------------------------- . use rustc_span::hygiene::MacroKind; . use rustc_span::source_map::Spanned; . use rustc_span::symbol::{kw, sym, Ident, Symbol}; . use rustc_span::Span; . use rustc_target::spec::abi::Abi; . use std::collections::VecDeque; . . fn fn_decl<'hir>(node: Node<'hir>) -> Option<&'hir FnDecl<'hir>> { 635 ( 0.00%) match node { . Node::Item(Item { kind: ItemKind::Fn(sig, _, _), .. }) . | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(sig, _), .. }) . | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(sig, _), .. }) => Some(&sig.decl), . Node::Expr(Expr { kind: ExprKind::Closure(_, fn_decl, ..), .. }) . | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, ..), .. }) => { . Some(fn_decl) . } . _ => None, . } . } . . pub fn fn_sig<'hir>(node: Node<'hir>) -> Option<&'hir FnSig<'hir>> { 104 ( 0.00%) match &node { . Node::Item(Item { kind: ItemKind::Fn(sig, _, _), .. }) . | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(sig, _), .. }) . | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(sig, _), .. }) => Some(sig), . _ => None, . } . } . . pub fn associated_body<'hir>(node: Node<'hir>) -> Option { 9,679 ( 0.00%) match node { . Node::Item(Item { . kind: ItemKind::Const(_, body) | ItemKind::Static(.., body) | ItemKind::Fn(.., body), . .. . }) . | Node::TraitItem(TraitItem { . kind: . TraitItemKind::Const(_, Some(body)) | TraitItemKind::Fn(_, TraitFn::Provided(body)), . .. . }) . | Node::ImplItem(ImplItem { . kind: ImplItemKind::Const(_, body) | ImplItemKind::Fn(_, body), . .. . }) 1,745 ( 0.00%) | Node::Expr(Expr { kind: ExprKind::Closure(.., body, _, _), .. }) => Some(*body), . . Node::AnonConst(constant) => Some(constant.body), . . _ => None, . } . } . . fn is_body_owner<'hir>(node: Node<'hir>, hir_id: HirId) -> bool { -- line 69 ---------------------------------------- -- line 83 ---------------------------------------- . pub struct ParentHirIterator<'hir> { . current_id: HirId, . map: Map<'hir>, . } . . impl<'hir> Iterator for ParentHirIterator<'hir> { . type Item = (HirId, Node<'hir>); . 469 ( 0.00%) fn next(&mut self) -> Option { 95 ( 0.00%) if self.current_id == CRATE_HIR_ID { . return None; . } . loop { . // There are nodes that do not have entries, so we need to skip them. . let parent_id = self.map.get_parent_node(self.current_id); . 297 ( 0.00%) if parent_id == self.current_id { . self.current_id = CRATE_HIR_ID; . return None; . } . 226 ( 0.00%) self.current_id = parent_id; 804 ( 0.00%) if let Some(node) = self.map.find(parent_id) { 268 ( 0.00%) return Some((parent_id, node)); . } . // If this `HirId` doesn't have an entry, skip it and look for its `parent_id`. . } 603 ( 0.00%) } . } . . /// An iterator that walks up the ancestor tree of a given `HirId`. . /// Constructed using `tcx.hir().parent_owner_iter(hir_id)`. . pub struct ParentOwnerIterator<'hir> { . current_id: HirId, . map: Map<'hir>, . } . . impl<'hir> Iterator for ParentOwnerIterator<'hir> { . type Item = (LocalDefId, OwnerNode<'hir>); . 6,489 ( 0.00%) fn next(&mut self) -> Option { 2,163 ( 0.00%) if self.current_id.local_id.index() != 0 { 451 ( 0.00%) self.current_id.local_id = ItemLocalId::new(0); 1,804 ( 0.00%) if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) { . return Some((self.current_id.owner, node.node)); . } . } 270 ( 0.00%) if self.current_id == CRATE_HIR_ID { 6 ( 0.00%) return None; . } . loop { . // There are nodes that do not have entries, so we need to skip them. . let parent_id = self.map.def_key(self.current_id.owner).parent; . . let parent_id = parent_id.map_or(CRATE_HIR_ID.owner, |local_def_index| { . let def_id = LocalDefId { local_def_index }; . self.map.local_def_id_to_hir_id(def_id).owner . }); 534 ( 0.00%) self.current_id = HirId::make_owner(parent_id); . . // If this `HirId` doesn't have an entry, skip it and look for its `parent_id`. 534 ( 0.00%) if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) { . return Some((self.current_id.owner, node.node)); . } . } 5,768 ( 0.00%) } . } . . impl<'hir> Map<'hir> { 210 ( 0.00%) pub fn krate(&self) -> &'hir Crate<'hir> { 30 ( 0.00%) self.tcx.hir_crate(()) 240 ( 0.00%) } . 7 ( 0.00%) pub fn root_module(&self) -> &'hir Mod<'hir> { 1 ( 0.00%) match self.tcx.hir_owner(CRATE_DEF_ID).map(|o| o.node) { . Some(OwnerNode::Crate(item)) => item, . _ => bug!(), . } 8 ( 0.00%) } . . pub fn items(&self) -> impl Iterator> + 'hir { . let krate = self.krate(); . krate.owners.iter().filter_map(|owner| match owner.as_ref()?.node() { . OwnerNode::Item(item) => Some(item), . _ => None, . }) . } -- line 169 ---------------------------------------- -- line 184 ---------------------------------------- . . #[inline] . pub fn def_path_hash(self, def_id: LocalDefId) -> DefPathHash { . // Accessing the DefPathHash is ok, it is incr. comp. stable. . self.tcx.untracked_resolutions.definitions.def_path_hash(def_id) . } . . #[inline] 14,364 ( 0.00%) pub fn local_def_id(&self, hir_id: HirId) -> LocalDefId { 3,090 ( 0.00%) self.opt_local_def_id(hir_id).unwrap_or_else(|| { . bug!( . "local_def_id: no entry for `{:?}`, which has a map of `{:?}`", . hir_id, . self.find(hir_id) . ) . }) 10,773 ( 0.00%) } . . #[inline] 8,240 ( 0.00%) pub fn opt_local_def_id(&self, hir_id: HirId) -> Option { 2,402 ( 0.00%) if hir_id.local_id == ItemLocalId::new(0) { . Some(hir_id.owner) . } else { 1,644 ( 0.00%) self.tcx . .hir_owner_nodes(hir_id.owner)? . .local_id_to_def_id . .get(&hir_id.local_id) . .copied() . } 9,270 ( 0.00%) } . . #[inline] 6 ( 0.00%) pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId { . // FIXME(#85914) is this access safe for incr. comp.? 601 ( 0.00%) self.tcx.untracked_resolutions.definitions.local_def_id_to_hir_id(def_id) 12 ( 0.00%) } . 7 ( 0.00%) pub fn iter_local_def_id(&self) -> impl Iterator + '_ { . // Create a dependency to the crate to be sure we reexcute this when the amount of . // definitions change. 1 ( 0.00%) self.tcx.ensure().hir_crate(()); . self.tcx.untracked_resolutions.definitions.iter_local_def_id() 9 ( 0.00%) } . 1,442 ( 0.00%) pub fn opt_def_kind(&self, local_def_id: LocalDefId) -> Option { . let hir_id = self.local_def_id_to_hir_id(local_def_id); 2,678 ( 0.00%) let def_kind = match self.find(hir_id)? { 316 ( 0.00%) Node::Item(item) => match item.kind { . ItemKind::Static(..) => DefKind::Static, . ItemKind::Const(..) => DefKind::Const, . ItemKind::Fn(..) => DefKind::Fn, . ItemKind::Macro(..) => DefKind::Macro(MacroKind::Bang), . ItemKind::Mod(..) => DefKind::Mod, . ItemKind::OpaqueTy(..) => DefKind::OpaqueTy, . ItemKind::TyAlias(..) => DefKind::TyAlias, . ItemKind::Enum(..) => DefKind::Enum, -- line 239 ---------------------------------------- -- line 252 ---------------------------------------- . ForeignItemKind::Static(..) => DefKind::Static, . ForeignItemKind::Type => DefKind::ForeignTy, . }, . Node::TraitItem(item) => match item.kind { . TraitItemKind::Const(..) => DefKind::AssocConst, . TraitItemKind::Fn(..) => DefKind::AssocFn, . TraitItemKind::Type(..) => DefKind::AssocTy, . }, 28 ( 0.00%) Node::ImplItem(item) => match item.kind { . ImplItemKind::Const(..) => DefKind::AssocConst, . ImplItemKind::Fn(..) => DefKind::AssocFn, . ImplItemKind::TyAlias(..) => DefKind::AssocTy, . }, . Node::Variant(_) => DefKind::Variant, . Node::Ctor(variant_data) => { . // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`? 40 ( 0.00%) assert_ne!(variant_data.ctor_hir_id(), None); . 56 ( 0.00%) let ctor_of = match self.find(self.get_parent_node(hir_id)) { . Some(Node::Item(..)) => def::CtorOf::Struct, . Some(Node::Variant(..)) => def::CtorOf::Variant, . _ => unreachable!(), . }; 16 ( 0.00%) DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data)) 32 ( 0.00%) } . Node::AnonConst(_) => { . let inline = match self.find(self.get_parent_node(hir_id)) { . Some(Node::Expr(&Expr { . kind: ExprKind::ConstBlock(ref anon_const), .. . })) if anon_const.hir_id == hir_id => true, . _ => false, . }; . if inline { DefKind::InlineConst } else { DefKind::AnonConst } . } . Node::Field(_) => DefKind::Field, 55 ( 0.00%) Node::Expr(expr) => match expr.kind { . ExprKind::Closure(.., None) => DefKind::Closure, . ExprKind::Closure(.., Some(_)) => DefKind::Generator, . _ => bug!("def_kind: unsupported node: {}", self.node_to_string(hir_id)), . }, 27 ( 0.00%) Node::GenericParam(param) => match param.kind { . GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam, . GenericParamKind::Type { .. } => DefKind::TyParam, . GenericParamKind::Const { .. } => DefKind::ConstParam, . }, . Node::Crate(_) => DefKind::Mod, . Node::Stmt(_) . | Node::PathSegment(_) . | Node::Ty(_) -- line 300 ---------------------------------------- -- line 304 ---------------------------------------- . | Node::Binding(_) . | Node::Local(_) . | Node::Param(_) . | Node::Arm(_) . | Node::Lifetime(_) . | Node::Visibility(_) . | Node::Block(_) => return None, . }; 720 ( 0.00%) Some(def_kind) 2,060 ( 0.00%) } . . pub fn def_kind(&self, local_def_id: LocalDefId) -> DefKind { . self.opt_def_kind(local_def_id) . .unwrap_or_else(|| bug!("def_kind: unsupported node: {:?}", local_def_id)) . } . 1,459,624 ( 0.06%) pub fn find_parent_node(&self, id: HirId) -> Option { 182,453 ( 0.01%) if id.local_id == ItemLocalId::from_u32(0) { . Some(self.tcx.hir_owner_parent(id.owner)) . } else { 364,124 ( 0.01%) let owner = self.tcx.hir_owner_nodes(id.owner)?; 182,062 ( 0.01%) let node = owner.nodes[id.local_id].as_ref()?; 546,186 ( 0.02%) let hir_id = HirId { owner: id.owner, local_id: node.parent }; . Some(hir_id) . } 1,459,624 ( 0.06%) } . 479 ( 0.00%) pub fn get_parent_node(&self, hir_id: HirId) -> HirId { 1,084,850 ( 0.04%) self.find_parent_node(hir_id).unwrap() 958 ( 0.00%) } . . /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found. 412,544 ( 0.02%) pub fn find(&self, id: HirId) -> Option> { 51,568 ( 0.00%) if id.local_id == ItemLocalId::from_u32(0) { . let owner = self.tcx.hir_owner(id.owner)?; 24,381 ( 0.00%) Some(owner.node.into()) . } else { 54,310 ( 0.00%) let owner = self.tcx.hir_owner_nodes(id.owner)?; 27,155 ( 0.00%) let node = owner.nodes[id.local_id].as_ref()?; 81,465 ( 0.00%) Some(node.node) . } 412,544 ( 0.02%) } . . /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found. . #[inline] . pub fn find_by_def_id(&self, id: LocalDefId) -> Option> { 28,896 ( 0.00%) self.find(self.local_def_id_to_hir_id(id)) . } . . /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found. 5,730 ( 0.00%) pub fn get(&self, id: HirId) -> Node<'hir> { 3,230 ( 0.00%) self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id)) 3,820 ( 0.00%) } . . /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found. . #[inline] . pub fn get_by_def_id(&self, id: LocalDefId) -> Node<'hir> { . self.find_by_def_id(id).unwrap_or_else(|| bug!("couldn't find {:?} in the HIR map", id)) . } . 192 ( 0.00%) pub fn get_if_local(&self, id: DefId) -> Option> { 96 ( 0.00%) id.as_local().and_then(|id| self.find(self.local_def_id_to_hir_id(id))) 192 ( 0.00%) } . . pub fn get_generics(&self, id: LocalDefId) -> Option<&'hir Generics<'hir>> { . let node = self.tcx.hir_owner(id)?; . match node.node { . OwnerNode::ImplItem(impl_item) => Some(&impl_item.generics), . OwnerNode::TraitItem(trait_item) => Some(&trait_item.generics), . OwnerNode::Item(Item { . kind: -- line 374 ---------------------------------------- -- line 381 ---------------------------------------- . | ItemKind::TraitAlias(generics, _) . | ItemKind::Impl(Impl { generics, .. }), . .. . }) => Some(generics), . _ => None, . } . } . 15,085 ( 0.00%) pub fn item(&self, id: ItemId) -> &'hir Item<'hir> { 4,310 ( 0.00%) self.tcx.hir_owner(id.def_id).unwrap().node.expect_item() 17,240 ( 0.00%) } . . pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> { . self.tcx.hir_owner(id.def_id).unwrap().node.expect_trait_item() . } . 5,551 ( 0.00%) pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> { 1,586 ( 0.00%) self.tcx.hir_owner(id.def_id).unwrap().node.expect_impl_item() 6,344 ( 0.00%) } . . pub fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> { . self.tcx.hir_owner(id.def_id).unwrap().node.expect_foreign_item() . } . 15,288 ( 0.00%) pub fn body(&self, id: BodyId) -> &'hir Body<'hir> { 4,368 ( 0.00%) self.tcx.hir_owner_nodes(id.hir_id.owner).unwrap().bodies[&id.hir_id.local_id] 17,472 ( 0.00%) } . 381 ( 0.00%) pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> { 381 ( 0.00%) if let Some(node) = self.find(hir_id) { . fn_decl(node) . } else { . bug!("no node for hir_id `{}`", hir_id) . } 254 ( 0.00%) } . 39 ( 0.00%) pub fn fn_sig_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> { 39 ( 0.00%) if let Some(node) = self.find(hir_id) { . fn_sig(node) . } else { . bug!("no node for hir_id `{}`", hir_id) . } 39 ( 0.00%) } . . pub fn enclosing_body_owner(&self, hir_id: HirId) -> HirId { . for (parent, _) in self.parent_iter(hir_id) { . if let Some(body) = self.maybe_body_owned_by(parent) { . return self.body_owner(body); . } . } . . bug!("no `enclosing_body_owner` for hir_id `{}`", hir_id); . } . . /// Returns the `HirId` that corresponds to the definition of . /// which this is the body of, i.e., a `fn`, `const` or `static` . /// item (possibly associated), a closure, or a `hir::AnonConst`. 10,328 ( 0.00%) pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> HirId { . let parent = self.get_parent_node(hir_id); 7,746 ( 0.00%) assert!(self.find(parent).map_or(false, |n| is_body_owner(n, hir_id))); . parent 10,328 ( 0.00%) } . 3,300 ( 0.00%) pub fn body_owner_def_id(&self, id: BodyId) -> LocalDefId { 5,150 ( 0.00%) self.local_def_id(self.body_owner(id)) 3,300 ( 0.00%) } . . /// Given a `HirId`, returns the `BodyId` associated with it, . /// if the node is a body owner, otherwise returns `None`. 437 ( 0.00%) pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option { 1,443 ( 0.00%) self.find(hir_id).map(associated_body).flatten() 1,311 ( 0.00%) } . . /// Given a body owner's id, returns the `BodyId` associated with it. 1,188 ( 0.00%) pub fn body_owned_by(&self, id: HirId) -> BodyId { . self.maybe_body_owned_by(id).unwrap_or_else(|| { . span_bug!( . self.span(id), . "body_owned_by: {} has no associated body", . self.node_to_string(id) . ); . }) 924 ( 0.00%) } . 42 ( 0.00%) pub fn body_param_names(&self, id: BodyId) -> impl Iterator + 'hir { 378 ( 0.00%) self.body(id).params.iter().map(|arg| match arg.pat.kind { 126 ( 0.00%) PatKind::Binding(_, _, ident, _) => ident, . _ => Ident::empty(), . }) 126 ( 0.00%) } . . /// Returns the `BodyOwnerKind` of this `LocalDefId`. . /// . /// Panics if `LocalDefId` does not have an associated body. 2,025 ( 0.00%) pub fn body_owner_kind(&self, id: HirId) -> BodyOwnerKind { 5,159 ( 0.00%) match self.get(id) { . Node::Item(&Item { kind: ItemKind::Const(..), .. }) . | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. }) . | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. }) . | Node::AnonConst(_) => BodyOwnerKind::Const, . Node::Ctor(..) . | Node::Item(&Item { kind: ItemKind::Fn(..), .. }) . | Node::TraitItem(&TraitItem { kind: TraitItemKind::Fn(..), .. }) . | Node::ImplItem(&ImplItem { kind: ImplItemKind::Fn(..), .. }) => BodyOwnerKind::Fn, 132 ( 0.00%) Node::Item(&Item { kind: ItemKind::Static(_, m, _), .. }) => BodyOwnerKind::Static(m), . Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => BodyOwnerKind::Closure, . node => bug!("{:#?} is not a body node", node), . } 2,025 ( 0.00%) } . . /// Returns the `ConstContext` of the body associated with this `LocalDefId`. . /// . /// Panics if `LocalDefId` does not have an associated body. . /// . /// This should only be used for determining the context of a body, a return . /// value of `Some` does not always suggest that the owner of the body is `const`, . /// just that it has to be checked as if it were. 2,320 ( 0.00%) pub fn body_const_context(&self, did: LocalDefId) -> Option { . let hir_id = self.local_def_id_to_hir_id(did); 3,480 ( 0.00%) let ccx = match self.body_owner_kind(hir_id) { . BodyOwnerKind::Const => ConstContext::Const, 198 ( 0.00%) BodyOwnerKind::Static(mt) => ConstContext::Static(mt), . 168 ( 0.00%) BodyOwnerKind::Fn if self.tcx.is_constructor(did.to_def_id()) => return None, 168 ( 0.00%) BodyOwnerKind::Fn if self.tcx.is_const_fn_raw(did.to_def_id()) => ConstContext::ConstFn, . BodyOwnerKind::Fn 336 ( 0.00%) if self.tcx.has_attr(did.to_def_id(), sym::default_method_body_is_const) => . { . ConstContext::ConstFn . } . BodyOwnerKind::Fn | BodyOwnerKind::Closure => return None, . }; . . Some(ccx) 2,610 ( 0.00%) } . . /// Returns an iterator of the `DefId`s for all body-owners in this . /// crate. If you would prefer to iterate over the bodies . /// themselves, you can do `self.hir().krate().body_ids.iter()`. 21 ( 0.00%) pub fn body_owners(self) -> impl Iterator + 'hir { 3 ( 0.00%) self.krate() . .owners . .iter_enumerated() . .flat_map(move |(owner, owner_info)| { 618 ( 0.00%) let bodies = &owner_info.as_ref()?.nodes.bodies; . Some(bodies.iter().map(move |&(local_id, _)| { 11 ( 0.00%) let hir_id = HirId { owner, local_id }; . let body_id = BodyId { hir_id }; 627 ( 0.00%) self.body_owner_def_id(body_id) . })) . }) . .flatten() 15 ( 0.00%) } . 10 ( 0.00%) pub fn par_body_owners(self, f: F) { . use rustc_data_structures::sync::{par_iter, ParallelIterator}; . #[cfg(parallel_compiler)] . use rustc_rayon::iter::IndexedParallelIterator; . 3 ( 0.00%) par_iter(&self.krate().owners.raw).enumerate().for_each(|(owner, owner_info)| { . let owner = LocalDefId::new(owner); 1,236 ( 0.00%) if let Some(owner_info) = owner_info { . par_iter(owner_info.nodes.bodies.range(..)).for_each(|(local_id, _)| { . let hir_id = HirId { owner, local_id: *local_id }; . let body_id = BodyId { hir_id }; 594 ( 0.00%) f(self.body_owner_def_id(body_id)) . }) . } . }); 8 ( 0.00%) } . . pub fn ty_param_owner(&self, id: HirId) -> LocalDefId { . match self.get(id) { . Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => { . id.expect_owner() . } . Node::GenericParam(_) => self.get_parent_item(id), . _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id)), -- line 558 ---------------------------------------- -- line 564 ---------------------------------------- . Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => { . kw::SelfUpper . } . Node::GenericParam(param) => param.name.ident().name, . _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)), . } . } . 603 ( 0.00%) pub fn trait_impls(&self, trait_did: DefId) -> &'hir [LocalDefId] { 67 ( 0.00%) self.tcx.all_local_trait_impls(()).get(&trait_did).map_or(&[], |xs| &xs[..]) 603 ( 0.00%) } . . /// Gets the attributes on the crate. This is preferable to . /// invoking `krate.attrs` because it registers a tighter . /// dep-graph access. . pub fn krate_attrs(&self) -> &'hir [ast::Attribute] { 20 ( 0.00%) self.attrs(CRATE_HIR_ID) . } . 119 ( 0.00%) pub fn get_module(&self, module: LocalDefId) -> (&'hir Mod<'hir>, Span, HirId) { . let hir_id = HirId::make_owner(module); 85 ( 0.00%) match self.tcx.hir_owner(module).map(|o| o.node) { 12 ( 0.00%) Some(OwnerNode::Item(&Item { span, kind: ItemKind::Mod(ref m), .. })) => { . (m, span, hir_id) . } 33 ( 0.00%) Some(OwnerNode::Crate(item)) => (item, item.inner, hir_id), . node => panic!("not a module: {:?}", node), . } 153 ( 0.00%) } . . /// Walks the contents of a crate. See also `Crate::visit_all_items`. 11 ( 0.00%) pub fn walk_toplevel_module(self, visitor: &mut impl Visitor<'hir>) { 30 ( 0.00%) let (top_mod, span, hir_id) = self.get_module(CRATE_DEF_ID); . visitor.visit_mod(top_mod, span, hir_id); 8 ( 0.00%) } . . /// Walks the attributes in a crate. 20 ( 0.00%) pub fn walk_attributes(self, visitor: &mut impl Visitor<'hir>) { 2 ( 0.00%) let krate = self.krate(); . for (owner, info) in krate.owners.iter_enumerated() { 824 ( 0.00%) if let Some(info) = info { . for (local_id, attrs) in info.attrs.map.iter() { . let id = HirId { owner, local_id: *local_id }; . for a in *attrs { 625 ( 0.00%) visitor.visit_attribute(id, a) . } . } . } . } 16 ( 0.00%) } . . /// Visits all items in the crate in some deterministic (but . /// unspecified) order. If you just need to process every item, . /// but don't care about nesting, this method is the best choice. . /// . /// If you do care about nesting -- usually because your algorithm . /// follows lexical scoping rules -- then you want a different . /// approach. You should override `visit_nested_item` in your . /// visitor and then call `intravisit::walk_crate` instead. 144 ( 0.00%) pub fn visit_all_item_likes(&self, visitor: &mut V) . where . V: itemlikevisit::ItemLikeVisitor<'hir>, . { 20 ( 0.00%) let krate = self.krate(); 70 ( 0.00%) for owner in krate.owners.iter().filter_map(Option::as_ref) { 3,564 ( 0.00%) match owner.node() { 3,397 ( 0.00%) OwnerNode::Item(item) => visitor.visit_item(item), . OwnerNode::ForeignItem(item) => visitor.visit_foreign_item(item), 84 ( 0.00%) OwnerNode::ImplItem(item) => visitor.visit_impl_item(item), . OwnerNode::TraitItem(item) => visitor.visit_trait_item(item), . OwnerNode::Crate(_) => {} . } . } 144 ( 0.00%) } . . /// A parallel version of `visit_all_item_likes`. . pub fn par_visit_all_item_likes(&self, visitor: &V) . where . V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send, . { 1 ( 0.00%) let krate = self.krate(); 2 ( 0.00%) par_for_each_in(&krate.owners.raw, |owner| match owner.as_ref().map(OwnerInfo::node) { 79 ( 0.00%) Some(OwnerNode::Item(item)) => visitor.visit_item(item), . Some(OwnerNode::ForeignItem(item)) => visitor.visit_foreign_item(item), 28 ( 0.00%) Some(OwnerNode::ImplItem(item)) => visitor.visit_impl_item(item), . Some(OwnerNode::TraitItem(item)) => visitor.visit_trait_item(item), . Some(OwnerNode::Crate(_)) | None => {} . }) . } . 258 ( 0.00%) pub fn visit_item_likes_in_module(&self, module: LocalDefId, visitor: &mut V) . where . V: ItemLikeVisitor<'hir>, . { 33 ( 0.00%) let module = self.tcx.hir_module_items(module); . 36 ( 0.00%) for id in module.items.iter() { 3,555 ( 0.00%) visitor.visit_item(self.item(*id)); . } . 36 ( 0.00%) for id in module.trait_items.iter() { . visitor.visit_trait_item(self.trait_item(*id)); . } . 36 ( 0.00%) for id in module.impl_items.iter() { 1,092 ( 0.00%) visitor.visit_impl_item(self.impl_item(*id)); . } . 36 ( 0.00%) for id in module.foreign_items.iter() { . visitor.visit_foreign_item(self.foreign_item(*id)); . } 264 ( 0.00%) } . 46 ( 0.00%) pub fn for_each_module(&self, f: impl Fn(LocalDefId)) { . let mut queue = VecDeque::new(); . queue.push_back(CRATE_DEF_ID); . 24 ( 0.00%) while let Some(id) = queue.pop_front() { . f(id); 9 ( 0.00%) let items = self.tcx.hir_module_items(id); 96 ( 0.00%) queue.extend(items.submodules.iter().copied()) . } 40 ( 0.00%) } . . #[cfg(not(parallel_compiler))] . #[inline] . pub fn par_for_each_module(&self, f: impl Fn(LocalDefId)) { 4 ( 0.00%) self.for_each_module(f) . } . . #[cfg(parallel_compiler)] . pub fn par_for_each_module(&self, f: impl Fn(LocalDefId) + Sync) { . use rustc_data_structures::sync::{par_iter, ParallelIterator}; . par_iter_submodules(self.tcx, CRATE_DEF_ID, &f); . . fn par_iter_submodules(tcx: TyCtxt<'_>, module: LocalDefId, f: &F) -- line 699 ---------------------------------------- -- line 703 ---------------------------------------- . (*f)(module); . let items = tcx.hir_module_items(module); . par_iter(&items.submodules[..]).for_each(|&sm| par_iter_submodules(tcx, sm, f)); . } . } . . /// Returns an iterator for the nodes in the ancestor tree of the `current_id` . /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`. 67 ( 0.00%) pub fn parent_iter(self, current_id: HirId) -> ParentHirIterator<'hir> { . ParentHirIterator { current_id, map: self } 284 ( 0.00%) } . . /// Returns an iterator for the nodes in the ancestor tree of the `current_id` . /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`. . pub fn parent_owner_iter(self, current_id: HirId) -> ParentOwnerIterator<'hir> { . ParentOwnerIterator { current_id, map: self } 2,142 ( 0.00%) } . . /// Checks if the node is left-hand side of an assignment. . pub fn is_lhs(&self, id: HirId) -> bool { . match self.find(self.get_parent_node(id)) { . Some(Node::Expr(expr)) => match expr.kind { . ExprKind::Assign(lhs, _rhs, _span) => lhs.hir_id == id, . _ => false, . }, -- line 727 ---------------------------------------- -- line 752 ---------------------------------------- . /// ``` . /// fn foo(x: usize) -> bool { . /// loop { . /// true // If `get_return_block` gets passed the `id` corresponding . /// } // to this, it will return `None`. . /// false . /// } . /// ``` 36 ( 0.00%) pub fn get_return_block(&self, id: HirId) -> Option { 4 ( 0.00%) let mut iter = self.parent_iter(id).peekable(); . let mut ignore_tail = false; 16 ( 0.00%) if let Some(node) = self.find(id) { 16 ( 0.00%) if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = node { . // When dealing with `return` statements, we don't care about climbing only tail . // expressions. . ignore_tail = true; . } . } 48 ( 0.00%) while let Some((hir_id, node)) = iter.next() { 196 ( 0.00%) if let (Some((_, next_node)), false) = (iter.peek(), ignore_tail) { 3 ( 0.00%) match next_node { . Node::Block(Block { expr: None, .. }) => return None, . // The current node is not the tail expression of its parent. 3 ( 0.00%) Node::Block(Block { expr: Some(e), .. }) if hir_id != e.hir_id => return None, . _ => {} . } . } 210 ( 0.00%) match node { . Node::Item(_) . | Node::ForeignItem(_) . | Node::TraitItem(_) . | Node::Expr(Expr { kind: ExprKind::Closure(..), .. }) . | Node::ImplItem(_) => return Some(hir_id), . // Ignore `return`s on the first iteration . Node::Expr(Expr { kind: ExprKind::Loop(..) | ExprKind::Ret(..), .. }) . | Node::Local(_) => { . return None; . } . _ => {} . } . } . None 40 ( 0.00%) } . . /// Retrieves the `HirId` for `id`'s parent item, or `id` itself if no . /// parent item is in this map. The "parent item" is the closest parent node . /// in the HIR which is recorded by the map and is an item, either an item . /// in a module, trait, or impl. 637 ( 0.00%) pub fn get_parent_item(&self, hir_id: HirId) -> LocalDefId { 5,773 ( 0.00%) if let Some((def_id, _node)) = self.parent_owner_iter(hir_id).next() { . def_id . } else { . CRATE_DEF_ID . } 1,274 ( 0.00%) } . . /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no . /// module parent is in this map. . pub(super) fn get_module_parent_node(&self, hir_id: HirId) -> LocalDefId { 582 ( 0.00%) for (def_id, node) in self.parent_owner_iter(hir_id) { 298 ( 0.00%) if let OwnerNode::Item(&Item { kind: ItemKind::Mod(_), .. }) = node { . return def_id; . } . } . CRATE_DEF_ID . } . . /// When on an if expression, a match arm tail expression or a match arm, give back . /// the enclosing `if` or `match` expression. -- line 820 ---------------------------------------- -- line 885 ---------------------------------------- . } . } . bug!( . "expected foreign mod or inlined parent, found {}", . self.node_to_string(HirId::make_owner(parent)) . ) . } . 2,331 ( 0.00%) pub fn expect_item(&self, id: LocalDefId) -> &'hir Item<'hir> { 999 ( 0.00%) match self.tcx.hir_owner(id) { . Some(Owner { node: OwnerNode::Item(item), .. }) => item, . _ => bug!("expected item, found {}", self.node_to_string(HirId::make_owner(id))), . } 2,664 ( 0.00%) } . 392 ( 0.00%) pub fn expect_impl_item(&self, id: LocalDefId) -> &'hir ImplItem<'hir> { 168 ( 0.00%) match self.tcx.hir_owner(id) { . Some(Owner { node: OwnerNode::ImplItem(item), .. }) => item, . _ => bug!("expected impl item, found {}", self.node_to_string(HirId::make_owner(id))), . } 448 ( 0.00%) } . . pub fn expect_trait_item(&self, id: LocalDefId) -> &'hir TraitItem<'hir> { . match self.tcx.hir_owner(id) { . Some(Owner { node: OwnerNode::TraitItem(item), .. }) => item, . _ => bug!("expected trait item, found {}", self.node_to_string(HirId::make_owner(id))), . } . } . -- line 913 ---------------------------------------- -- line 929 ---------------------------------------- . . pub fn expect_expr(&self, id: HirId) -> &'hir Expr<'hir> { . match self.find(id) { . Some(Node::Expr(expr)) => expr, . _ => bug!("expected expr, found {}", self.node_to_string(id)), . } . } . 432 ( 0.00%) pub fn opt_name(&self, id: HirId) -> Option { 164 ( 0.00%) Some(match self.get(id) { . Node::Item(i) => i.ident.name, . Node::ForeignItem(fi) => fi.ident.name, . Node::ImplItem(ii) => ii.ident.name, . Node::TraitItem(ti) => ti.ident.name, . Node::Variant(v) => v.ident.name, . Node::Field(f) => f.ident.name, . Node::Lifetime(lt) => lt.name.ident().name, 114 ( 0.00%) Node::GenericParam(param) => param.name.ident().name, 20 ( 0.00%) Node::Binding(&Pat { kind: PatKind::Binding(_, _, l, _), .. }) => l.name, . Node::Ctor(..) => self.name(HirId::make_owner(self.get_parent_item(id))), . _ => return None, . }) 240 ( 0.00%) } . 344 ( 0.00%) pub fn name(&self, id: HirId) -> Symbol { 154 ( 0.00%) match self.opt_name(id) { . Some(name) => name, . None => bug!("no name for {}", self.node_to_string(id)), . } 258 ( 0.00%) } . . /// Given a node ID, gets a list of attributes associated with the AST . /// corresponding to the node-ID. 2,686,838 ( 0.11%) pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] { 383,834 ( 0.02%) self.tcx.hir_attrs(id.owner).get(id.local_id) 3,070,672 ( 0.12%) } . . /// Gets the span of the definition of the specified HIR node. . /// This is used by `tcx.get_span` 732 ( 0.00%) pub fn span(&self, hir_id: HirId) -> Span { 68,648 ( 0.00%) self.opt_span(hir_id) . .unwrap_or_else(|| bug!("hir::map::Map::span: id not in map: {:?}", hir_id)) 732 ( 0.00%) } . 122,731 ( 0.00%) pub fn opt_span(&self, hir_id: HirId) -> Option { 122,731 ( 0.00%) let span = match self.find(hir_id)? { . Node::Param(param) => param.span, 334 ( 0.00%) Node::Item(item) => match &item.kind { . ItemKind::Fn(sig, _, _) => sig.span, 206 ( 0.00%) _ => item.span, . }, . Node::ForeignItem(foreign_item) => foreign_item.span, . Node::TraitItem(trait_item) => match &trait_item.kind { . TraitItemKind::Fn(sig, _) => sig.span, . _ => trait_item.span, . }, 212 ( 0.00%) Node::ImplItem(impl_item) => match &impl_item.kind { 208 ( 0.00%) ImplItemKind::Fn(sig, _) => sig.span, 4 ( 0.00%) _ => impl_item.span, . }, 16 ( 0.00%) Node::Variant(variant) => variant.span, 72 ( 0.00%) Node::Field(field) => field.span, . Node::AnonConst(constant) => self.body(constant.body).value.span, . Node::Expr(expr) => expr.span, . Node::Stmt(stmt) => stmt.span, . Node::PathSegment(seg) => seg.ident.span, . Node::Ty(ty) => ty.span, . Node::TraitRef(tr) => tr.path.span, . Node::Binding(pat) => pat.span, . Node::Pat(pat) => pat.span, . Node::Arm(arm) => arm.span, . Node::Block(block) => block.span, 77 ( 0.00%) Node::Ctor(..) => match self.find(self.get_parent_node(hir_id))? { . Node::Item(item) => item.span, . Node::Variant(variant) => variant.span, . _ => unreachable!(), . }, . Node::Lifetime(lifetime) => lifetime.span, . Node::GenericParam(param) => param.span, . Node::Visibility(&Spanned { . node: VisibilityKind::Restricted { ref path, .. }, . .. . }) => path.span, . Node::Infer(i) => i.span, . Node::Visibility(v) => bug!("unexpected Visibility {:?}", v), . Node::Local(local) => local.span, 4 ( 0.00%) Node::Crate(item) => item.inner, . }; . Some(span) 175,330 ( 0.01%) } . . /// Like `hir.span()`, but includes the body of function items . /// (instead of just the function header) . pub fn span_with_body(&self, hir_id: HirId) -> Span { . match self.find(hir_id) { . Some(Node::TraitItem(item)) => item.span, . Some(Node::ImplItem(impl_item)) => impl_item.span, . Some(Node::Item(item)) => item.span, . Some(_) => self.span(hir_id), . _ => bug!("hir::map::Map::span_with_body: id not in map: {:?}", hir_id), . } . } . 38 ( 0.00%) pub fn span_if_local(&self, id: DefId) -> Option { 363 ( 0.00%) id.as_local().and_then(|id| self.opt_span(self.local_def_id_to_hir_id(id))) 57 ( 0.00%) } . . pub fn res_span(&self, res: Res) -> Option { . match res { . Res::Err => None, . Res::Local(id) => Some(self.span(id)), . res => self.span_if_local(res.opt_def_id()?), . } . } -- line 1042 ---------------------------------------- -- line 1062 ---------------------------------------- . } . . impl<'hir> intravisit::Map<'hir> for Map<'hir> { . fn find(&self, hir_id: HirId) -> Option> { . self.find(hir_id) . } . . fn body(&self, id: BodyId) -> &'hir Body<'hir> { 1,274 ( 0.00%) self.body(id) . } . . fn item(&self, id: ItemId) -> &'hir Item<'hir> { 1,025 ( 0.00%) self.item(id) . } . . fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> { . self.trait_item(id) . } . . fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> { 392 ( 0.00%) self.impl_item(id) . } . . fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> { . self.foreign_item(id) . } . } . 7 ( 0.00%) pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh { . debug_assert_eq!(crate_num, LOCAL_CRATE); . let krate = tcx.hir_crate(()); 3 ( 0.00%) let hir_body_hash = krate.hir_hash; . . let upstream_crates = upstream_crates(tcx); . . // We hash the final, remapped names of all local source files so we . // don't have to include the path prefix remapping commandline args. . // If we included the full mapping in the SVH, we could only have . // reproducible builds by compiling from the same directory. So we just . // hash the result of the mapping instead of the mapping itself. 2 ( 0.00%) let mut source_file_names: Vec<_> = tcx . .sess . .source_map() . .files() . .iter() . .filter(|source_file| source_file.cnum == LOCAL_CRATE) 11 ( 0.00%) .map(|source_file| source_file.name_hash) . .collect(); . . source_file_names.sort_unstable(); . . let mut hcx = tcx.create_stable_hashing_context(); . let mut stable_hasher = StableHasher::new(); . hir_body_hash.hash_stable(&mut hcx, &mut stable_hasher); . upstream_crates.hash_stable(&mut hcx, &mut stable_hasher); . source_file_names.hash_stable(&mut hcx, &mut stable_hasher); 3 ( 0.00%) if tcx.sess.opts.debugging_opts.incremental_relative_spans { . let definitions = &tcx.untracked_resolutions.definitions; . let mut owner_spans: Vec<_> = krate . .owners . .iter_enumerated() . .filter_map(|(def_id, info)| { . let _ = info.as_ref()?; . let def_path_hash = definitions.def_path_hash(def_id); . let span = definitions.def_span(def_id); . debug_assert_eq!(span.parent(), None); . Some((def_path_hash, span)) . }) . .collect(); . owner_spans.sort_unstable_by_key(|bn| bn.0); . owner_spans.hash_stable(&mut hcx, &mut stable_hasher); . } 3 ( 0.00%) tcx.sess.opts.dep_tracking_hash(true).hash_stable(&mut hcx, &mut stable_hasher); 2 ( 0.00%) tcx.sess.local_stable_crate_id().hash_stable(&mut hcx, &mut stable_hasher); . . let crate_hash: Fingerprint = stable_hasher.finish(); 1 ( 0.00%) Svh::new(crate_hash.to_smaller_hash()) 9 ( 0.00%) } . . fn upstream_crates(tcx: TyCtxt<'_>) -> Vec<(StableCrateId, Svh)> { . let mut upstream_crates: Vec<_> = tcx . .crates(()) . .iter() . .map(|&cnum| { 120 ( 0.00%) let stable_crate_id = tcx.resolutions(()).cstore.stable_crate_id(cnum); 24 ( 0.00%) let hash = tcx.crate_hash(cnum); . (stable_crate_id, hash) . }) . .collect(); . upstream_crates.sort_unstable_by_key(|&(stable_crate_id, _)| stable_crate_id); . upstream_crates . } . . fn hir_id_to_string(map: &Map<'_>, id: HirId) -> String { -- line 1155 ---------------------------------------- -- line 1238 ---------------------------------------- . Some(Node::Lifetime(_)) => node_str("lifetime"), . Some(Node::GenericParam(ref param)) => format!("generic_param {:?}{}", param, id_str), . Some(Node::Visibility(ref vis)) => format!("visibility {:?}{}", vis, id_str), . Some(Node::Crate(..)) => String::from("root_crate"), . None => format!("unknown node{}", id_str), . } . } . 27 ( 0.00%) pub(super) fn hir_module_items(tcx: TyCtxt<'_>, module_id: LocalDefId) -> ModuleItems { 18 ( 0.00%) let mut collector = ModuleCollector { . tcx, . submodules: Vec::default(), . items: Vec::default(), . trait_items: Vec::default(), . impl_items: Vec::default(), . foreign_items: Vec::default(), . }; . 15 ( 0.00%) let (hir_mod, span, hir_id) = tcx.hir().get_module(module_id); . collector.visit_mod(hir_mod, span, hir_id); . 48 ( 0.00%) let ModuleCollector { submodules, items, trait_items, impl_items, foreign_items, .. } = . collector; 33 ( 0.00%) return ModuleItems { 12 ( 0.00%) submodules: submodules.into_boxed_slice(), 12 ( 0.00%) items: items.into_boxed_slice(), 12 ( 0.00%) trait_items: trait_items.into_boxed_slice(), 12 ( 0.00%) impl_items: impl_items.into_boxed_slice(), 12 ( 0.00%) foreign_items: foreign_items.into_boxed_slice(), . }; . . struct ModuleCollector<'tcx> { . tcx: TyCtxt<'tcx>, . submodules: Vec, . items: Vec, . trait_items: Vec, . impl_items: Vec, . foreign_items: Vec, . } . . impl<'hir> Visitor<'hir> for ModuleCollector<'hir> { . type NestedFilter = nested_filter::All; . . fn nested_visit_map(&mut self) -> Self::Map { 170 ( 0.00%) self.tcx.hir() . } . 395 ( 0.00%) fn visit_item(&mut self, item: &'hir Item<'hir>) { 237 ( 0.00%) self.items.push(item.item_id()); 158 ( 0.00%) if let ItemKind::Mod(..) = item.kind { . // If this declares another module, do not recurse inside it. 2 ( 0.00%) self.submodules.push(item.def_id); . } else { 462 ( 0.00%) intravisit::walk_item(self, item) . } 8 ( 0.00%) } . . fn visit_trait_item(&mut self, item: &'hir TraitItem<'hir>) { . self.trait_items.push(item.trait_item_id()); . intravisit::walk_trait_item(self, item) . } . . fn visit_impl_item(&mut self, item: &'hir ImplItem<'hir>) { 84 ( 0.00%) self.impl_items.push(item.impl_item_id()); 84 ( 0.00%) intravisit::walk_impl_item(self, item) . } . . fn visit_foreign_item(&mut self, item: &'hir ForeignItem<'hir>) { . self.foreign_items.push(item.foreign_item_id()); . intravisit::walk_foreign_item(self, item) . } . } 24 ( 0.00%) } 509,702 ( 0.02%) -------------------------------------------------------------------------------- -- 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 { 13,896 ( 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 { 129 ( 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() . } . 142,002 ( 0.01%) pub fn allocate( . &mut self, . size: Size, . align: Align, . kind: MemoryKind, . ) -> InterpResult<'static, Pointer> { 63,112 ( 0.00%) let alloc = Allocation::uninit(size, align, M::PANIC_ON_ALLOC_FAIL)?; 142,002 ( 0.01%) Ok(self.allocate_with(alloc, kind)) 110,446 ( 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 { 31,556 ( 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)); 378,672 ( 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) = 235,816 ( 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> { 84 ( 0.00%) self.check_and_deref_ptr(ptr, size, Some(align), msg, |alloc_id, _, _| { 40 ( 0.00%) let check = match msg { . CheckInAllocMsg::DerefTest | CheckInAllocMsg::MemoryAccessTest => { . AllocCheck::Dereferenceable . } . CheckInAllocMsg::PointerArithmeticTest | CheckInAllocMsg::InboundsTest => { . AllocCheck::Live . } . }; 20 ( 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. 140 ( 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> { 20 ( 0.00%) fn check_offset_align(offset: u64, align: Align) -> InterpResult<'static> { 50 ( 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, . }) . } 30 ( 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. 315,046 ( 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. 20 ( 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. 20 ( 0.00%) if alloc_align.bytes() < align.bytes() { . throw_ub!(AlignmentCheckFailed { has: alloc_align, required: align }); . } 50 ( 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`. . if size.bytes() == 0 { None } else { Some(ret_val) } . } . }) 150 ( 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`. 910,558 ( 0.04%) fn get_global_alloc( . &self, . id: AllocId, . is_write: bool, . ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> { 745,002 ( 0.03%) let (alloc, def_id) = match self.tcx.get_global_alloc(id) { 82,778 ( 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)) . } . }; 662,224 ( 0.03%) 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), . ); 331,112 ( 0.01%) Ok(alloc) 662,224 ( 0.03%) } . . /// Gives raw access to the `Allocation`, without bounds or alignment checks. . /// The caller is responsible for calling the access hooks! 449,672 ( 0.02%) 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, || { 331,112 ( 0.01%) let alloc = self.get_global_alloc(id, /*is_write*/ false).map_err(Err)?; 165,556 ( 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 59,280 ( 0.00%) match a { . Ok(a) => Ok(&a.1), . Err(a) => a, . } 337,254 ( 0.01%) } . . /// "Safe" (bounds and align-checked) allocation access. 1,182,468 ( 0.05%) 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| { 394,156 ( 0.02%) let alloc = self.get_raw(alloc_id)?; . Ok((alloc.size(), alloc.align, (alloc_id, offset, ptr, alloc))) . }, . )?; 197,078 ( 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)?; 689,773 ( 0.03%) 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) . } 886,851 ( 0.04%) } . . /// 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. 360,600 ( 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`.) 45,075 ( 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())); . } . 45,075 ( 0.00%) let (_kind, alloc) = self.alloc_map.get_mut(id).unwrap(); 45,075 ( 0.00%) if alloc.mutability == Mutability::Not { . throw_ub!(WriteToReadOnly(id)) . } 180,300 ( 0.01%) Ok((alloc, &mut self.extra)) 225,375 ( 0.01%) } . . /// "Safe" (bounds and align-checked) allocation access. 374,352 ( 0.01%) 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)?; 62,392 ( 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`. 93,588 ( 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)?; 187,176 ( 0.01%) Ok(Some(AllocRefMut { alloc, range, tcx, alloc_id })) . } else { . Ok(None) . } 280,764 ( 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`. 648,604 ( 0.03%) 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 294,820 ( 0.01%) if let Some((_, alloc)) = self.alloc_map.get(id) { 58,954 ( 0.00%) return Ok((alloc.size(), alloc.align)); . } . . // # Function pointers . // (both global from `alloc_map` and local from `extra_fn_ptr_map`) 40 ( 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. 110 ( 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)) . } 10 ( 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. 20 ( 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)) . } . } . } 471,712 ( 0.02%) } . 40 ( 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 { 50 ( 0.00%) match self.tcx.get_global_alloc(id) { . Some(GlobalAlloc::Function(instance)) => Some(FnVal::Instance(instance)), 10 ( 0.00%) _ => None, . } . } 40 ( 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> { 297,738 ( 0.01%) pub fn write_scalar( . &mut self, . range: AllocRange, . val: ScalarMaybeUninit, . ) -> InterpResult<'tcx> { 165,410 ( 0.01%) Ok(self . .alloc 363,902 ( 0.01%) .write_scalar(&self.tcx, self.range.subrange(range), val) . .map_err(|e| e.to_interp_error(self.alloc_id))?) 198,492 ( 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> { 15,128 ( 0.00%) pub fn read_scalar(&self, range: AllocRange) -> InterpResult<'tcx, ScalarMaybeUninit> { 946,366 ( 0.04%) Ok(self . .alloc 521,185 ( 0.02%) .read_scalar(&self.tcx, self.range.subrange(range)) . .map_err(|e| e.to_interp_error(self.alloc_id))?) 15,128 ( 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 947 ---------------------------------------- . .map_err(|e| e.to_interp_error(self.alloc_id))?) . } . } . . impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { . /// Reads the given number of bytes from memory. Returns them as a slice. . /// . /// Performs appropriate bounds checks. 8 ( 0.00%) pub fn read_bytes( . &self, . ptr: Pointer>, . size: Size, . ) -> InterpResult<'tcx, &[u8]> { 6 ( 0.00%) let alloc_ref = match self.get(ptr, size, Align::ONE)? { 12 ( 0.00%) Some(a) => a, . None => return Ok(&[]), // zero-sized access . }; . // Side-step AllocRef and directly access the underlying bytes more efficiently. . // (We are staying inside the bounds here so all is good.) 4 ( 0.00%) Ok(alloc_ref . .alloc 6 ( 0.00%) .get_bytes(&alloc_ref.tcx, alloc_ref.range) . .map_err(|e| e.to_interp_error(alloc_ref.alloc_id))?) 8 ( 0.00%) } . . /// Writes the given stream of bytes into memory. . /// . /// Performs appropriate bounds checks. . pub fn write_bytes( . &mut self, . ptr: Pointer>, . src: impl IntoIterator, -- line 978 ---------------------------------------- -- line 1016 ---------------------------------------- . &mut self, . src: Pointer>, . src_align: Align, . dest: Pointer>, . dest_align: Align, . size: Size, . nonoverlapping: bool, . ) -> InterpResult<'tcx> { 69,395 ( 0.00%) self.copy_repeatedly(src, src_align, dest, dest_align, size, 1, nonoverlapping) . } . 180,427 ( 0.01%) 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> { 27,758 ( 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. 27,758 ( 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, . }; 55,516 ( 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. 27,758 ( 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 = 166,548 ( 0.01%) src_alloc.prepare_relocation_copy(self, src_range, dest_offset, num_copies); . // Prepare a copy of the initialization mask. 55,516 ( 0.00%) let compressed = src_alloc.compress_uninit_range(src_range); . . // Destination alloc preparations and access hooks. 41,637 ( 0.00%) let (dest_alloc, extra) = self.get_raw_mut(dest_alloc_id)?; 41,637 ( 0.00%) let dest_range = alloc_range(dest_offset, size * num_copies); . M::memory_written(extra, &mut dest_alloc.extra, dest.provenance, dest_range)?; 55,516 ( 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(); . 41,637 ( 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 { 13,879 ( 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, 41,637 ( 0.00%) dest_bytes.add((size * i).bytes_usize()), // `Size` multiplication . size.bytes_usize(), . ); . } . } . } . . // now fill in all the "init" data 69,395 ( 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 124,911 ( 0.00%) dest_alloc.mark_relocation_range(relocations); . . Ok(()) 124,911 ( 0.00%) } . } . . /// Machine pointer introspection. . impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { 17 ( 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. 85 ( 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 . } . } 34 ( 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 ---------------------------------------- 1,182,584 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs -------------------------------------------------------------------------------- Ir -- line 91 ---------------------------------------- . // maximum of number bytes needed to fill an 8-byte-sized element on which . // SipHash operates. Note that for variable-sized copies which are known to be . // less than 8 bytes, this function will perform more work than necessary unless . // the compiler is able to optimize the extra work away. . #[inline] . unsafe fn copy_nonoverlapping_small(src: *const u8, dst: *mut u8, count: usize) { . debug_assert!(count <= 8); . 51,477 ( 0.00%) if count == 8 { . ptr::copy_nonoverlapping(src, dst, 8); . return; . } . . let mut i = 0; 62,330 ( 0.00%) if i + 3 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 4); . i += 4; . } . 132,545 ( 0.01%) if i + 1 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 2); 18,578 ( 0.00%) i += 2 . } . 62,330 ( 0.00%) if i < count { 30,352 ( 0.00%) *dst.add(i) = *src.add(i); . i += 1; . } . . debug_assert_eq!(i, count); . } . . // # Implementation . // -- line 124 ---------------------------------------- -- line 201 ---------------------------------------- . . hasher . } . . // A specialized write function for values with size <= 8. . #[inline] . fn short_write(&mut self, x: T) { . let size = mem::size_of::(); 916,410 ( 0.04%) let nbuf = self.nbuf; . debug_assert!(size <= 8); . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + size < BUFFER_WITH_SPILL_SIZE); . 5,972,155 ( 0.24%) if nbuf + size < BUFFER_SIZE { . unsafe { . // The memcpy call is optimized away because the size is known. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . ptr::copy_nonoverlapping(&x as *const _ as *const u8, dst, size); . } . 1,809,667 ( 0.07%) self.nbuf = nbuf + size; . . return; . } . 259,920 ( 0.01%) unsafe { self.short_write_process_buffer(x) } . } . . // A specialized write function for values with size <= 8 that should only . // be called when the write would cause the buffer to fill. . // . // SAFETY: the write of `x` into `self.buf` starting at byte offset . // `self.nbuf` must cause `self.buf` to become fully initialized (and not . // overflow) if it wasn't already. . #[inline(never)] 85,330 ( 0.00%) unsafe fn short_write_process_buffer(&mut self, x: T) { . let size = mem::size_of::(); 85,330 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(size <= 8); . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + size >= BUFFER_SIZE); . debug_assert!(nbuf + size < BUFFER_WITH_SPILL_SIZE); . . // Copy first part of input into end of buffer, possibly into spill . // element. The memcpy call is optimized away because the size is known. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . ptr::copy_nonoverlapping(&x as *const _ as *const u8, dst, size); . . // Process buffer. . for i in 0..BUFFER_CAPACITY { 853,300 ( 0.03%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 682,640 ( 0.03%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 767,970 ( 0.03%) self.state.v0 ^= elem; . } . . // Copy remaining input into start of buffer by copying size - 1 . // elements from spill (at most size - 1 bytes could have overflowed . // into the spill). The memcpy call is optimized away because the size . // is known. And the whole copy is optimized away for size == 1. . let src = self.buf.get_unchecked(BUFFER_SPILL_INDEX) as *const _ as *const u8; . ptr::copy_nonoverlapping(src, self.buf.as_mut_ptr() as *mut u8, size - 1); . . // This function should only be called when the write fills the buffer. . // Therefore, when size == 1, the new `self.nbuf` must be zero. The size . // is statically known, so the branch is optimized away. 408,262 ( 0.02%) self.nbuf = if size == 1 { 0 } else { nbuf + size - BUFFER_SIZE }; 341,320 ( 0.01%) self.processed += BUFFER_SIZE; 170,660 ( 0.01%) } . . // A write function for byte slices. . #[inline] . fn slice_write(&mut self, msg: &[u8]) { . let length = msg.len(); 31,425 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(nbuf < BUFFER_SIZE); . 300,999 ( 0.01%) if nbuf + length < BUFFER_SIZE { . unsafe { . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . 73,718 ( 0.00%) if length <= 8 { . copy_nonoverlapping_small(msg.as_ptr(), dst, length); . } else { . // This memcpy is *not* optimized away. . ptr::copy_nonoverlapping(msg.as_ptr(), dst, length); . } . } . 64,438 ( 0.00%) self.nbuf = nbuf + length; . . return; . } . 49,618 ( 0.00%) unsafe { self.slice_write_process_buffer(msg) } . } . . // A write function for byte slices that should only be called when the . // write would cause the buffer to fill. . // . // SAFETY: `self.buf` must be initialized up to the byte offset `self.nbuf`, . // and `msg` must contain enough bytes to initialize the rest of the element . // containing the byte offset `self.nbuf`. . #[inline(never)] 47,605 ( 0.00%) unsafe fn slice_write_process_buffer(&mut self, msg: &[u8]) { . let length = msg.len(); 9,521 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + length >= BUFFER_SIZE); . . // Always copy first part of input into current element of buffer. . // This function should only be called when the write fills the buffer, . // so we know that there is enough input to fill the current element. 28,563 ( 0.00%) let valid_in_elem = nbuf % ELEM_SIZE; 9,521 ( 0.00%) let needed_in_elem = ELEM_SIZE - valid_in_elem; . . let src = msg.as_ptr(); . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . copy_nonoverlapping_small(src, dst, needed_in_elem); . . // Process buffer. . . // Using `nbuf / ELEM_SIZE + 1` rather than `(nbuf + needed_in_elem) / . // ELEM_SIZE` to show the compiler that this loop's upper bound is > 0. . // We know that is true, because last step ensured we have a full . // element in the buffer. 19,042 ( 0.00%) let last = nbuf / ELEM_SIZE + 1; . . for i in 0..last { 71,767 ( 0.00%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 81,288 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 143,534 ( 0.01%) self.state.v0 ^= elem; . } . . // Process the remaining element-sized chunks of input. . let mut processed = needed_in_elem; 19,042 ( 0.00%) let input_left = length - processed; 22,602 ( 0.00%) let elems_left = input_left / ELEM_SIZE; . let extra_bytes_left = input_left % ELEM_SIZE; . . for _ in 0..elems_left { 9,464 ( 0.00%) let elem = (msg.as_ptr().add(processed) as *const u64).read_unaligned().to_le(); 9,464 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 9,464 ( 0.00%) self.state.v0 ^= elem; 18,928 ( 0.00%) processed += ELEM_SIZE; . } . . // Copy remaining input into start of buffer. . let src = msg.as_ptr().add(processed); . let dst = self.buf.as_mut_ptr() as *mut u8; . copy_nonoverlapping_small(src, dst, extra_bytes_left); . 9,521 ( 0.00%) self.nbuf = extra_bytes_left; 47,605 ( 0.00%) self.processed += nbuf + processed; 57,126 ( 0.00%) } . . #[inline] . pub fn finish128(mut self) -> (u64, u64) { . debug_assert!(self.nbuf < BUFFER_SIZE); . . // Process full elements in buffer. 4,746 ( 0.00%) let last = self.nbuf / ELEM_SIZE; . . // Since we're consuming self, avoid updating members for a potential . // performance gain. 6,328 ( 0.00%) let mut state = self.state; . . for i in 0..last { 4,199 ( 0.00%) let elem = unsafe { self.buf.get_unchecked(i).assume_init().to_le() }; 4,199 ( 0.00%) state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut state); 4,199 ( 0.00%) state.v0 ^= elem; . } . . // Get remaining partial element. 3,164 ( 0.00%) let elem = if self.nbuf % ELEM_SIZE != 0 { . unsafe { . // Ensure element is initialized by writing zero bytes. At most . // `ELEM_SIZE - 1` are required given the above check. It's safe . // to write this many because we have the spill and we maintain . // `self.nbuf` such that this write will start before the spill. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(self.nbuf); . ptr::write_bytes(dst, 0, ELEM_SIZE - 1); 1,395 ( 0.00%) self.buf.get_unchecked(last).assume_init().to_le() . } . } else { . 0 . }; . . // Finalize the hash. 4,559 ( 0.00%) let length = self.processed + self.nbuf; 3,162 ( 0.00%) let b: u64 = ((length as u64 & 0xff) << 56) | elem; . 1,581 ( 0.00%) state.v3 ^= b; . Sip24Rounds::c_rounds(&mut state); 1,581 ( 0.00%) state.v0 ^= b; . 1,581 ( 0.00%) state.v2 ^= 0xee; . Sip24Rounds::d_rounds(&mut state); 4,486 ( 0.00%) let _0 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; . 1,322 ( 0.00%) state.v1 ^= 0xdd; . Sip24Rounds::d_rounds(&mut state); 1,322 ( 0.00%) let _1 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; . . (_0, _1) . } . } . . impl Hasher for SipHasher128 { . #[inline] . fn write_u8(&mut self, i: u8) { -- line 414 ---------------------------------------- -- line 471 ---------------------------------------- . } . . #[derive(Debug, Clone, Default)] . struct Sip24Rounds; . . impl Sip24Rounds { . #[inline] . fn c_rounds(state: &mut State) { 3,192,497 ( 0.13%) compress!(state); 3,549,895 ( 0.14%) compress!(state); . } . . #[inline] . fn d_rounds(state: &mut State) { 8,968 ( 0.00%) compress!(state); 8,968 ( 0.00%) compress!(state); 8,968 ( 0.00%) compress!(state); 7,388 ( 0.00%) compress!(state); . } . } 658,248 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/writeback.rs -------------------------------------------------------------------------------- Ir -- line 30 ---------------------------------------- . // the final TypeckResults since all of the types should have been . // inferred once typeck is done. . // When type inference is running however, having to update the typeck . // typeck results every time a new type is inferred would be unreasonably slow, . // so instead all of the replacement happens at the end in . // resolve_type_vars_in_body, which creates a new TypeTables which . // doesn't contain any inference types. . impl<'a, 'tcx> FnCtxt<'a, 'tcx> { 495 ( 0.00%) pub fn resolve_type_vars_in_body( . &self, . body: &'tcx hir::Body<'tcx>, . ) -> &'tcx ty::TypeckResults<'tcx> { 550 ( 0.00%) let item_id = self.tcx.hir().body_owner(body.id()); 330 ( 0.00%) let item_def_id = self.tcx.hir().local_def_id(item_id); . . // This attribute causes us to dump some writeback information . // in the form of errors, which is used for unit tests. . let rustc_dump_user_substs = 330 ( 0.00%) self.tcx.has_attr(item_def_id.to_def_id(), sym::rustc_dump_user_substs); . . let mut wbcx = WritebackCx::new(self, body, rustc_dump_user_substs); 220 ( 0.00%) for param in body.params { 567 ( 0.00%) wbcx.visit_node_id(param.pat.span, param.hir_id); . } . // Type only exists for constants and statics, not functions. 605 ( 0.00%) match self.tcx.hir().body_owner_kind(item_id) { . hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => { 65 ( 0.00%) wbcx.visit_node_id(body.value.span, item_id); . } . hir::BodyOwnerKind::Closure | hir::BodyOwnerKind::Fn => (), . } . wbcx.visit_body(body); 55 ( 0.00%) wbcx.visit_min_capture_map(); 55 ( 0.00%) wbcx.eval_closure_size(); 55 ( 0.00%) wbcx.visit_fake_reads_map(); 55 ( 0.00%) wbcx.visit_closures(); 55 ( 0.00%) wbcx.visit_liberated_fn_sigs(); 55 ( 0.00%) wbcx.visit_fru_field_types(); 165 ( 0.00%) wbcx.visit_opaque_types(body.value.span); 55 ( 0.00%) wbcx.visit_coercion_casts(); 55 ( 0.00%) wbcx.visit_user_provided_tys(); 55 ( 0.00%) wbcx.visit_user_provided_sigs(); 55 ( 0.00%) wbcx.visit_generator_interior_types(); . . let used_trait_imports = 110 ( 0.00%) mem::take(&mut self.typeck_results.borrow_mut().used_trait_imports); . debug!("used_trait_imports({:?}) = {:?}", item_def_id, used_trait_imports); 110 ( 0.00%) wbcx.typeck_results.used_trait_imports = used_trait_imports; . 275 ( 0.00%) wbcx.typeck_results.treat_byte_string_as_slice = 55 ( 0.00%) mem::take(&mut self.typeck_results.borrow_mut().treat_byte_string_as_slice); . 165 ( 0.00%) if self.is_tainted_by_errors() { . // FIXME(eddyb) keep track of `ErrorReported` from where the error was emitted. . wbcx.typeck_results.tainted_by_errors = Some(ErrorReported); . } . . debug!("writeback: typeck results for {:?} are {:#?}", item_def_id, wbcx.typeck_results); . 110 ( 0.00%) self.tcx.arena.alloc(wbcx.typeck_results) 495 ( 0.00%) } . } . . /////////////////////////////////////////////////////////////////////////// . // The Writeback context. This visitor walks the HIR, checking the . // fn-specific typeck results to find references to types or regions. It . // resolves those regions to remove inference variables and writes the . // final result back into the master typeck results in the tcx. Here and . // there, it applies a few ad-hoc checks that were not convenient to -- line 98 ---------------------------------------- -- line 109 ---------------------------------------- . } . . impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { . fn new( . fcx: &'cx FnCtxt<'cx, 'tcx>, . body: &'tcx hir::Body<'tcx>, . rustc_dump_user_substs: bool, . ) -> WritebackCx<'cx, 'tcx> { 110 ( 0.00%) let owner = body.id().hir_id.owner; . 495 ( 0.00%) WritebackCx { . fcx, 220 ( 0.00%) typeck_results: ty::TypeckResults::new(owner), . body, . rustc_dump_user_substs, . } . } . . fn tcx(&self) -> TyCtxt<'tcx> { 238 ( 0.00%) self.fcx.tcx . } . . fn write_ty_to_typeck_results(&mut self, hir_id: hir::HirId, ty: Ty<'tcx>) { . debug!("write_ty_to_typeck_results({:?}, {:?})", hir_id, ty); 137,169 ( 0.01%) assert!(!ty.needs_infer() && !ty.has_placeholders() && !ty.has_free_regions()); 182,882 ( 0.01%) self.typeck_results.node_types_mut().insert(hir_id, ty); . } . . // Hacky hack: During type-checking, we treat *all* operators . // as potentially overloaded. But then, during writeback, if . // we observe that something like `a+b` is (known to be) . // operating on scalars, we clear the overload. . fn fix_scalar_builtin_expr(&mut self, e: &hir::Expr<'_>) { 313,953 ( 0.01%) match e.kind { 18 ( 0.00%) hir::ExprKind::Unary(hir::UnOp::Neg | hir::UnOp::Not, inner) => { 72 ( 0.00%) let inner_ty = self.fcx.node_ty(inner.hir_id); . let inner_ty = self.fcx.resolve_vars_if_possible(inner_ty); . . if inner_ty.is_scalar() { 18 ( 0.00%) let mut typeck_results = self.fcx.typeck_results.borrow_mut(); 108 ( 0.00%) typeck_results.type_dependent_defs_mut().remove(e.hir_id); 36 ( 0.00%) typeck_results.node_substs_mut().remove(e.hir_id); . } . } . hir::ExprKind::Binary(ref op, lhs, rhs) | hir::ExprKind::AssignOp(ref op, lhs, rhs) => { 750 ( 0.00%) let lhs_ty = self.fcx.node_ty(lhs.hir_id); . let lhs_ty = self.fcx.resolve_vars_if_possible(lhs_ty); . 600 ( 0.00%) let rhs_ty = self.fcx.node_ty(rhs.hir_id); . let rhs_ty = self.fcx.resolve_vars_if_possible(rhs_ty); . . if lhs_ty.is_scalar() && rhs_ty.is_scalar() { 143 ( 0.00%) let mut typeck_results = self.fcx.typeck_results.borrow_mut(); 715 ( 0.00%) typeck_results.type_dependent_defs_mut().remove(e.hir_id); 143 ( 0.00%) typeck_results.node_substs_mut().remove(e.hir_id); . 338 ( 0.00%) match e.kind { . hir::ExprKind::Binary(..) => { 468 ( 0.00%) if !op.node.is_by_value() { 33 ( 0.00%) let mut adjustments = typeck_results.adjustments_mut(); 198 ( 0.00%) if let Some(a) = adjustments.get_mut(lhs.hir_id) { . a.pop(); . } 132 ( 0.00%) if let Some(a) = adjustments.get_mut(rhs.hir_id) { . a.pop(); . } . } . } . hir::ExprKind::AssignOp(..) 130 ( 0.00%) if let Some(a) = typeck_results.adjustments_mut().get_mut(lhs.hir_id) => . { . a.pop(); . } . _ => {} . } . } . } . _ => {} -- line 186 ---------------------------------------- -- line 187 ---------------------------------------- . } . } . . // Similar to operators, indexing is always assumed to be overloaded . // Here, correct cases where an indexing expression can be simplified . // to use builtin indexing because the index type is known to be . // usize-ish . fn fix_index_builtin_expr(&mut self, e: &hir::Expr<'_>) { 89,975 ( 0.00%) if let hir::ExprKind::Index(ref base, ref index) = e.kind { 22 ( 0.00%) let mut typeck_results = self.fcx.typeck_results.borrow_mut(); . . // All valid indexing looks like this; might encounter non-valid indexes at this point. 22 ( 0.00%) let base_ty = typeck_results 11 ( 0.00%) .expr_ty_adjusted_opt(base) . .map(|t| self.fcx.resolve_vars_if_possible(t).kind()); . if base_ty.is_none() { . // When encountering `return [0][0]` outside of a `fn` body we can encounter a base . // that isn't in the type table. We assume more relevant errors have already been . // emitted, so we delay an ICE if none have. (#64638) . self.tcx().sess.delay_span_bug(e.span, &format!("bad base: `{:?}`", base)); . } 22 ( 0.00%) if let Some(ty::Ref(_, base_ty, _)) = base_ty { 44 ( 0.00%) let index_ty = typeck_results.expr_ty_adjusted_opt(index).unwrap_or_else(|| { . // When encountering `return [0][0]` outside of a `fn` body we would attempt . // to access an unexistend index. We assume that more relevant errors will . // already have been emitted, so we only gate on this with an ICE if no . // error has been emitted. (#64638) . self.fcx.tcx.ty_error_with_message( . e.span, . &format!("bad index {:?} for base: `{:?}`", index, base), . ) . }); . let index_ty = self.fcx.resolve_vars_if_possible(index_ty); . 41 ( 0.00%) if base_ty.builtin_index().is_some() && index_ty == self.fcx.tcx.types.usize { . // Remove the method call record 24 ( 0.00%) typeck_results.type_dependent_defs_mut().remove(e.hir_id); 24 ( 0.00%) typeck_results.node_substs_mut().remove(e.hir_id); . 40 ( 0.00%) if let Some(a) = typeck_results.adjustments_mut().get_mut(base.hir_id) { . // Discard the need for a mutable borrow . . // Extra adjustment made when indexing causes a drop . // of size information - we need to get rid of it . // Since this is "after" the other adjustment to be . // discarded, we do an extra `pop()` 8 ( 0.00%) if let Some(Adjustment { . kind: Adjust::Pointer(PointerCast::Unsize), .. . }) = a.pop() . { . // So the borrow discard actually happens here . a.pop(); . } . } . } -- line 241 ---------------------------------------- -- line 248 ---------------------------------------- . // Impl of Visitor for Resolver . // . // This is the master code which walks the AST. It delegates most of . // the heavy lifting to the generic visit and resolve functions . // below. In general, a function is made into a `visitor` if it must . // traffic in node-ids or update typeck results in the type context etc. . . impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> { 403,839 ( 0.02%) fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) { 44,871 ( 0.00%) self.fix_scalar_builtin_expr(e); . self.fix_index_builtin_expr(e); . 224,355 ( 0.01%) self.visit_node_id(e.span, e.hir_id); . 179,484 ( 0.01%) match e.kind { 22 ( 0.00%) hir::ExprKind::Closure(_, _, body, _, _) => { 66 ( 0.00%) let body = self.fcx.tcx.hir().body(body); 22 ( 0.00%) for param in body.params { 55 ( 0.00%) self.visit_node_id(e.span, param.hir_id); . } . . self.visit_body(body); . } 5,842 ( 0.00%) hir::ExprKind::Struct(_, fields, _) => { . for field in fields { 70,100 ( 0.00%) self.visit_field_id(field.hir_id); . } . } . hir::ExprKind::Field(..) => { 350 ( 0.00%) self.visit_field_id(e.hir_id); . } . hir::ExprKind::ConstBlock(anon_const) => { . self.visit_node_id(e.span, anon_const.hir_id); . . let body = self.tcx().hir().body(anon_const.body); . self.visit_body(body); . } . _ => {} . } . 134,613 ( 0.01%) intravisit::walk_expr(self, e); 358,968 ( 0.01%) } . 1,719 ( 0.00%) fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) { 764 ( 0.00%) self.visit_node_id(b.span, b.hir_id); . intravisit::walk_block(self, b); 688 ( 0.00%) } . 3,753 ( 0.00%) fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) { 1,617 ( 0.00%) match p.kind { . hir::PatKind::Binding(..) => { 468 ( 0.00%) let typeck_results = self.fcx.typeck_results.borrow(); 702 ( 0.00%) if let Some(bm) = 1,872 ( 0.00%) typeck_results.extract_binding_mode(self.tcx().sess, p.hir_id, p.span) . { 702 ( 0.00%) self.typeck_results.pat_binding_modes_mut().insert(p.hir_id, bm); . } . } 33 ( 0.00%) hir::PatKind::Struct(_, fields, _) => { . for field in fields { 188 ( 0.00%) self.visit_field_id(field.hir_id); . } . } . _ => {} . }; . 1,668 ( 0.00%) self.visit_pat_adjustments(p.span, p.hir_id); . 2,085 ( 0.00%) self.visit_node_id(p.span, p.hir_id); 1,251 ( 0.00%) intravisit::walk_pat(self, p); 3,336 ( 0.00%) } . 680 ( 0.00%) fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) { . intravisit::walk_local(self, l); 510 ( 0.00%) let var_ty = self.fcx.local_ty(l.span, l.hir_id).decl_ty; . let var_ty = self.resolve(var_ty, &l.span); . self.write_ty_to_typeck_results(l.hir_id, var_ty); . } . 469 ( 0.00%) fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) { 77 ( 0.00%) intravisit::walk_ty(self, hir_ty); 288 ( 0.00%) let ty = self.fcx.node_ty(hir_ty.hir_id); 67 ( 0.00%) let ty = self.resolve(ty, &hir_ty.span); . self.write_ty_to_typeck_results(hir_ty.hir_id, ty); . } . . fn visit_infer(&mut self, inf: &'tcx hir::InferArg) { . intravisit::walk_inf(self, inf); . // Ignore cases where the inference is a const. . if let Some(ty) = self.fcx.node_ty_opt(inf.hir_id) { . let ty = self.resolve(ty, &inf.span); . self.write_ty_to_typeck_results(inf.hir_id, ty); . } . } . } . . impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { 385 ( 0.00%) fn eval_closure_size(&mut self) { . let mut res: FxHashMap> = Default::default(); 165 ( 0.00%) for (closure_def_id, data) in self.fcx.typeck_results.borrow().closure_size_eval.iter() { . let closure_hir_id = . self.tcx().hir().local_def_id_to_hir_id(closure_def_id.expect_local()); . . let data = self.resolve(*data, &closure_hir_id); . . res.insert(*closure_def_id, data); . } . 550 ( 0.00%) self.typeck_results.closure_size_eval = res; 440 ( 0.00%) } 385 ( 0.00%) fn visit_min_capture_map(&mut self) { . let mut min_captures_wb = ty::MinCaptureInformationMap::with_capacity_and_hasher( 110 ( 0.00%) self.fcx.typeck_results.borrow().closure_min_captures.len(), . Default::default(), . ); . for (closure_def_id, root_min_captures) in 110 ( 0.00%) self.fcx.typeck_results.borrow().closure_min_captures.iter() . { . let mut root_var_map_wb = ty::RootVariableMinCaptureList::with_capacity_and_hasher( . root_min_captures.len(), . Default::default(), . ); . for (var_hir_id, min_list) in root_min_captures.iter() { . let min_list_wb = min_list . .iter() . .map(|captured_place| { 15 ( 0.00%) let locatable = captured_place.info.path_expr_id.unwrap_or_else(|| { . self.tcx().hir().local_def_id_to_hir_id(closure_def_id.expect_local()) . }); . . self.resolve(captured_place.clone(), &locatable) . }) . .collect(); 10 ( 0.00%) root_var_map_wb.insert(*var_hir_id, min_list_wb); . } 10 ( 0.00%) min_captures_wb.insert(*closure_def_id, root_var_map_wb); . } . 495 ( 0.00%) self.typeck_results.closure_min_captures = min_captures_wb; 440 ( 0.00%) } . 385 ( 0.00%) fn visit_fake_reads_map(&mut self) { . let mut resolved_closure_fake_reads: FxHashMap< . DefId, . Vec<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>, . > = Default::default(); . for (closure_def_id, fake_reads) in 110 ( 0.00%) self.fcx.typeck_results.borrow().closure_fake_reads.iter() . { . let mut resolved_fake_reads = Vec::<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>::new(); . for (place, cause, hir_id) in fake_reads.iter() { . let locatable = . self.tcx().hir().local_def_id_to_hir_id(closure_def_id.expect_local()); . . let resolved_fake_read = self.resolve(place.clone(), &locatable); . resolved_fake_reads.push((resolved_fake_read, *cause, *hir_id)); . } 22 ( 0.00%) resolved_closure_fake_reads.insert(*closure_def_id, resolved_fake_reads); . } 495 ( 0.00%) self.typeck_results.closure_fake_reads = resolved_closure_fake_reads; 440 ( 0.00%) } . 385 ( 0.00%) fn visit_closures(&mut self) { 110 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 165 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . let common_hir_owner = fcx_typeck_results.hir_owner; . 55 ( 0.00%) for (id, origin) in fcx_typeck_results.closure_kind_origins().iter() { . let hir_id = hir::HirId { owner: common_hir_owner, local_id: *id }; . let place_span = origin.0; . let place = self.resolve(origin.1.clone(), &place_span); . self.typeck_results.closure_kind_origins_mut().insert(hir_id, (place_span, place)); . } 440 ( 0.00%) } . 385 ( 0.00%) fn visit_coercion_casts(&mut self) { 110 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 55 ( 0.00%) let fcx_coercion_casts = fcx_typeck_results.coercion_casts(); 110 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . . for local_id in fcx_coercion_casts { . self.typeck_results.set_coercion_cast(*local_id); . } 440 ( 0.00%) } . 440 ( 0.00%) fn visit_user_provided_tys(&mut self) { 110 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 220 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . let common_hir_owner = fcx_typeck_results.hir_owner; . . let mut errors_buffer = Vec::new(); 103 ( 0.00%) for (&local_id, c_ty) in fcx_typeck_results.user_provided_types().iter() { . let hir_id = hir::HirId { owner: common_hir_owner, local_id }; . . if cfg!(debug_assertions) && c_ty.needs_infer() { . span_bug!( . hir_id.to_span(self.fcx.tcx), . "writeback: `{:?}` has inference variables", . c_ty . ); . }; . 216 ( 0.00%) self.typeck_results.user_provided_types_mut().insert(hir_id, *c_ty); . 143 ( 0.00%) if let ty::UserType::TypeOf(_, user_substs) = c_ty.value { 38 ( 0.00%) if self.rustc_dump_user_substs { . // This is a unit-testing mechanism. . let span = self.tcx().hir().span(hir_id); . // We need to buffer the errors in order to guarantee a consistent . // order when emitting them. . let err = self . .tcx() . .sess . .struct_span_err(span, &format!("user substs: {:?}", user_substs)); . err.buffer(&mut errors_buffer); . } . } . } . 55 ( 0.00%) if !errors_buffer.is_empty() { . errors_buffer.sort_by_key(|diag| diag.span.primary_span()); . for diag in errors_buffer.drain(..) { . self.tcx().sess.diagnostic().emit_diagnostic(&diag); . } . } 440 ( 0.00%) } . 385 ( 0.00%) fn visit_user_provided_sigs(&mut self) { 110 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 110 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . 22 ( 0.00%) for (&def_id, c_sig) in fcx_typeck_results.user_provided_sigs.iter() { . if cfg!(debug_assertions) && c_sig.needs_infer() { . span_bug!( . self.fcx.tcx.hir().span_if_local(def_id).unwrap(), . "writeback: `{:?}` has inference variables", . c_sig . ); . }; . 66 ( 0.00%) self.typeck_results.user_provided_sigs.insert(def_id, *c_sig); . } 440 ( 0.00%) } . 275 ( 0.00%) fn visit_generator_interior_types(&mut self) { 110 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 110 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); 330 ( 0.00%) self.typeck_results.generator_interior_types = 110 ( 0.00%) fcx_typeck_results.generator_interior_types.clone(); 330 ( 0.00%) } . 880 ( 0.00%) #[instrument(skip(self, span), level = "debug")] . fn visit_opaque_types(&mut self, span: Span) { 55 ( 0.00%) let opaque_types = self.fcx.infcx.inner.borrow().opaque_types.clone(); 220 ( 0.00%) for (opaque_type_key, opaque_defn) in opaque_types { . let hir_id = . self.tcx().hir().local_def_id_to_hir_id(opaque_type_key.def_id.expect_local()); . let instantiated_ty = self.resolve(opaque_defn.concrete_ty, &hir_id); . . debug_assert!(!instantiated_ty.has_escaping_bound_vars()); . . let opaque_type_key = self.fcx.fully_resolve(opaque_type_key).unwrap(); . -- line 510 ---------------------------------------- -- line 552 ---------------------------------------- . // in some other location, or we'll end up emitting an error due . // to the lack of defining usage . if !skip_add { . self.typeck_results.concrete_opaque_types.insert(opaque_type_key.def_id); . } . } . } . 105,852 ( 0.00%) fn visit_field_id(&mut self, hir_id: hir::HirId) { 88,210 ( 0.00%) if let Some(index) = self.fcx.typeck_results.borrow_mut().field_indices_mut().remove(hir_id) . { 52,926 ( 0.00%) self.typeck_results.field_indices_mut().insert(hir_id, index); . } 123,494 ( 0.00%) } . 820,188 ( 0.03%) #[instrument(skip(self, span), level = "debug")] . fn visit_node_id(&mut self, span: Span, hir_id: hir::HirId) { . // Export associated path extensions and method resolutions. 182,264 ( 0.01%) if let Some(def) = 136,698 ( 0.01%) self.fcx.typeck_results.borrow_mut().type_dependent_defs_mut().remove(hir_id) . { 476 ( 0.00%) self.typeck_results.type_dependent_defs_mut().insert(hir_id, def); . } . . // Resolve any borrowings for the node with id `node_id` . self.visit_adjustments(span, hir_id); . . // Resolve the type of the node with id `node_id` 182,264 ( 0.01%) let n_ty = self.fcx.node_ty(hir_id); . let n_ty = self.resolve(n_ty, &span); . self.write_ty_to_typeck_results(hir_id, n_ty); . debug!(?n_ty); . . // Resolve any substitutions 273,396 ( 0.01%) if let Some(substs) = self.fcx.typeck_results.borrow().node_substs_opt(hir_id) { . let substs = self.resolve(substs, &span); . debug!("write_substs_to_tcx({:?}, {:?})", hir_id, substs); . assert!(!substs.needs_infer() && !substs.has_placeholders()); 358 ( 0.00%) self.typeck_results.node_substs_mut().insert(hir_id, substs); . } . } . . #[instrument(skip(self, span), level = "debug")] . fn visit_adjustments(&mut self, span: Span, hir_id: hir::HirId) { 136,698 ( 0.01%) let adjustment = self.fcx.typeck_results.borrow_mut().adjustments_mut().remove(hir_id); 227,830 ( 0.01%) match adjustment { . None => { . debug!("no adjustments for node"); . } . . Some(adjustment) => { 882 ( 0.00%) let resolved_adjustment = self.resolve(adjustment, &span); . debug!(?resolved_adjustment); 2,646 ( 0.00%) self.typeck_results.adjustments_mut().insert(hir_id, resolved_adjustment); . } . } . } . . #[instrument(skip(self, span), level = "debug")] . fn visit_pat_adjustments(&mut self, span: Span, hir_id: hir::HirId) { 1,251 ( 0.00%) let adjustment = self.fcx.typeck_results.borrow_mut().pat_adjustments_mut().remove(hir_id); 834 ( 0.00%) match adjustment { . None => { . debug!("no pat_adjustments for node"); . } . . Some(adjustment) => { 50 ( 0.00%) let resolved_adjustment = self.resolve(adjustment, &span); . debug!(?resolved_adjustment); 30 ( 0.00%) self.typeck_results.pat_adjustments_mut().insert(hir_id, resolved_adjustment); . } . } . } . 440 ( 0.00%) fn visit_liberated_fn_sigs(&mut self) { 110 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 220 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . let common_hir_owner = fcx_typeck_results.hir_owner; . 267 ( 0.00%) for (&local_id, &fn_sig) in fcx_typeck_results.liberated_fn_sigs().iter() { 159 ( 0.00%) let hir_id = hir::HirId { owner: common_hir_owner, local_id }; . let fn_sig = self.resolve(fn_sig, &hir_id); 159 ( 0.00%) self.typeck_results.liberated_fn_sigs_mut().insert(hir_id, fn_sig); . } 440 ( 0.00%) } . 440 ( 0.00%) fn visit_fru_field_types(&mut self) { 110 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 220 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . let common_hir_owner = fcx_typeck_results.hir_owner; . 55 ( 0.00%) for (&local_id, ftys) in fcx_typeck_results.fru_field_types().iter() { . let hir_id = hir::HirId { owner: common_hir_owner, local_id }; . let ftys = self.resolve(ftys.clone(), &hir_id); . self.typeck_results.fru_field_types_mut().insert(hir_id, ftys); . } 440 ( 0.00%) } . 35 ( 0.00%) fn resolve(&mut self, x: T, span: &dyn Locatable) -> T . where . T: TypeFoldable<'tcx>, . { 92,371 ( 0.00%) let mut resolver = Resolver::new(self.fcx, span, self.body); 468 ( 0.00%) let x = x.fold_with(&mut resolver); . if cfg!(debug_assertions) && x.needs_infer() { . span_bug!(span.to_span(self.fcx.tcx), "writeback: `{:?}` has inference variables", x); . } . . // We may have introduced e.g. `ty::Error`, if inference failed, make sure . // to mark the `TypeckResults` as tainted in that case, so that downstream . // users of the typeck results don't produce extra errors, or worse, ICEs. 94,900 ( 0.00%) if resolver.replaced_with_error { . // FIXME(eddyb) keep track of `ErrorReported` from where the error was emitted. . self.typeck_results.tainted_by_errors = Some(ErrorReported); . } . . x 40 ( 0.00%) } . } . . crate trait Locatable { . fn to_span(&self, tcx: TyCtxt<'_>) -> Span; . } . . impl Locatable for Span { . fn to_span(&self, _: TyCtxt<'_>) -> Span { -- line 677 ---------------------------------------- -- line 698 ---------------------------------------- . } . . impl<'cx, 'tcx> Resolver<'cx, 'tcx> { . fn new( . fcx: &'cx FnCtxt<'cx, 'tcx>, . span: &'cx dyn Locatable, . body: &'tcx hir::Body<'tcx>, . ) -> Resolver<'cx, 'tcx> { 463,031 ( 0.02%) Resolver { tcx: fcx.tcx, infcx: fcx, span, body, replaced_with_error: false } . } . . fn report_type_error(&self, t: Ty<'tcx>) { . if !self.tcx.sess.has_errors() { . self.infcx . .emit_inference_failure_err( . Some(self.body.id()), . self.span.to_span(self.tcx), -- line 714 ---------------------------------------- -- line 736 ---------------------------------------- . } . . struct EraseEarlyRegions<'tcx> { . tcx: TyCtxt<'tcx>, . } . . impl<'tcx> TypeFolder<'tcx> for EraseEarlyRegions<'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { 664 ( 0.00%) self.tcx . } . fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { 46,989 ( 0.00%) if ty.has_type_flags(ty::TypeFlags::HAS_FREE_REGIONS) { 1,112 ( 0.00%) ty.super_fold_with(self) . } else { . ty . } . } . fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { 1,968 ( 0.00%) if let ty::ReLateBound(..) = r { r } else { self.tcx.lifetimes.re_erased } . } . } . . impl<'cx, 'tcx> TypeFolder<'tcx> for Resolver<'cx, 'tcx> { . fn tcx<'a>(&'a self) -> TyCtxt<'tcx> { 208 ( 0.00%) self.tcx . } . 419,625 ( 0.02%) fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 139,875 ( 0.01%) match self.infcx.fully_resolve(t) { . Ok(t) => { . // Do not anonymize late-bound regions . // (e.g. keep `for<'a>` named `for<'a>`). . // This allows NLL to generate error messages that . // refer to the higher-ranked lifetime names written by the user. 93,250 ( 0.00%) EraseEarlyRegions { tcx: self.infcx.tcx }.fold_ty(t) . } . Err(_) => { . debug!("Resolver::fold_ty: input type `{:?}` not fully resolvable", t); . self.report_type_error(t); . self.replaced_with_error = true; . self.tcx().ty_error() . } . } 373,000 ( 0.01%) } . . fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { . debug_assert!(!r.is_late_bound(), "Should not be resolving bound region."); 1,026 ( 0.00%) self.tcx.lifetimes.re_erased . } . . fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { . match self.infcx.fully_resolve(ct) { . Ok(ct) => self.infcx.tcx.erase_regions(ct), . Err(_) => { . debug!("Resolver::fold_const: input const `{:?}` not fully resolvable", ct); . self.report_const_error(ct); -- line 791 ---------------------------------------- 686,619 ( 0.03%) -------------------------------------------------------------------------------- The following files chosen for auto-annotation could not be found: -------------------------------------------------------------------------------- ./elf/../sysdeps/x86_64/dl-machine.h ./elf/dl-lookup.c ./malloc/malloc.c ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 1,182,592,701 (46.78%) events annotated