-------------------------------------------------------------------------------- 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 js_sys --edition=2018 src/lib.rs --error-format=json --json=diagnostic-rendered-ansi,artifacts,future-incompat --crate-type lib --emit=dep-info,metadata,link -C opt-level=3 -C embed-bitcode=no -C metadata=fb423152589d441d -C extra-filename=-fb423152589d441d --out-dir /usr/home/liquid/tmp/.tmpWuEDWa/target/release/deps -L dependency=/usr/home/liquid/tmp/.tmpWuEDWa/target/release/deps --extern wasm_bindgen=/usr/home/liquid/tmp/.tmpWuEDWa/target/release/deps/libwasm_bindgen-fb6f1d415f697407.rmeta -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-js-sys-0.3.56-Opt-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 16,738,274,616 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 650,202,800 ( 3.88%) ./malloc/malloc.c:_int_free 518,670,709 ( 3.10%) ./malloc/malloc.c:_int_malloc 391,356,077 ( 2.34%) ./malloc/malloc.c:malloc 324,202,542 ( 1.94%) ???:llvm::FPPassManager::runOnFunction(llvm::Function&) 300,726,648 ( 1.80%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 206,112,324 ( 1.23%) ./malloc/malloc.c:free 189,490,853 ( 1.13%) ???:llvm::AnalysisManager::getResultImpl(llvm::AnalysisKey*, llvm::Function&) 159,903,380 ( 0.96%) ???:llvm::AnalysisManager::invalidate(llvm::Function&, llvm::PreservedAnalyses const&) 145,655,039 ( 0.87%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/server.rs:> as proc_macro::bridge::server::DispatcherTrait>::dispatch 132,077,880 ( 0.79%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/hash/sip.rs:::write 103,541,016 ( 0.62%) ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S:__memcmp_avx2_movbe 95,615,302 ( 0.57%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/client.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 81,474,017 ( 0.49%) ./malloc/malloc.c:malloc_consolidate 75,628,232 ( 0.45%) ???:llvm::TargetLibraryInfoImpl::getLibFunc(llvm::Function const&, llvm::LibFunc&) const 71,255,103 ( 0.43%) ???:llvm::AttributeList::addAttributes(llvm::LLVMContext&, unsigned int, llvm::AttrBuilder const&) const 65,119,748 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/search.rs:, proc_macro::bridge::client::SourceFile>, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 62,816,684 ( 0.38%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs:>::decode 58,138,204 ( 0.35%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::drop_in_place::replace::PutBackOnDrop> 55,534,819 ( 0.33%) ???:llvm::DomTreeBuilder::SemiNCAInfo >::CalculateFromScratch(llvm::DominatorTreeBase&, llvm::DomTreeBuilder::SemiNCAInfo >::BatchUpdateInfo*) 55,374,608 ( 0.33%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/search.rs:>>::insert 54,561,682 ( 0.33%) ???:llvm::coro::declaresIntrinsics(llvm::Module const&, std::initializer_list) 53,528,539 ( 0.32%) ???:llvm::InstCombinerImpl::run() 52,236,100 ( 0.31%) ./malloc/malloc.c:unlink_chunk.constprop.0 51,225,542 ( 0.31%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 50,825,658 ( 0.30%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/scoped_cell.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 50,687,704 ( 0.30%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:, proc_macro::bridge::client::SourceFile>, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 50,243,105 ( 0.30%) ./string/../sysdeps/x86_64/multiarch/strcmp-avx2.S:__strncmp_avx2 49,340,382 ( 0.29%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 48,351,259 ( 0.29%) ./elf/../sysdeps/x86_64/tls_get_addr.S:__tls_get_addr 48,189,766 ( 0.29%) ???:core::ptr::read 48,027,193 ( 0.29%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs:>::encode 46,983,806 ( 0.28%) ???:runCVP(llvm::Module&) [clone .llvm.11785992503873176614] 46,722,137 ( 0.28%) ./malloc/malloc.c:realloc 46,468,668 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:>>::insert 46,344,528 ( 0.28%) ???:combineInstructionsOverFunction(llvm::Function&, llvm::InstCombineWorklist&, llvm::AAResults*, llvm::AssumptionCache&, llvm::TargetLibraryInfo&, llvm::TargetTransformInfo&, llvm::DominatorTree&, llvm::OptimizationRemarkEmitter&, llvm::BlockFrequencyInfo*, llvm::ProfileSummaryInfo*, unsigned int, llvm::LoopInfo*) 45,499,446 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 45,301,939 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/search.rs:, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 44,605,625 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/buffer.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 43,977,973 ( 0.26%) ???:llvm::detail::PassModel>, llvm::PreservedAnalyses, llvm::AnalysisManager>::run(llvm::Function&, llvm::AnalysisManager&) 43,294,566 ( 0.26%) ???:llvm::InlineFunction(llvm::CallBase&, llvm::InlineFunctionInfo&, llvm::AAResults*, bool, llvm::Function*) 43,231,665 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs: as proc_macro::bridge::rpc::DecodeMut>::decode 40,537,655 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/node.rs:, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::Edge>>::insert_recursing 40,443,952 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/closure.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 40,132,367 ( 0.24%) ???:llvm::PMDataManager::verifyPreservedAnalysis(llvm::Pass*) 38,079,131 ( 0.23%) ???:llvm::SelectionDAG::Combine(llvm::CombineLevel, llvm::AAResults*, llvm::CodeGenOpt::Level) 37,983,387 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 37,679,360 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/buffer.rs:>::encode 37,592,461 ( 0.22%) ???:llvm::LazyCallGraph::removeDeadFunction(llvm::Function&) 35,388,472 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs:core::ptr::drop_in_place::replace::PutBackOnDrop> 34,609,419 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/buffer.rs:>::encode 33,294,179 ( 0.20%) ???: as core::iter::traits::iterator::Iterator>::next 33,176,334 ( 0.20%) ???:core::mem::replace 33,097,896 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::short_write_process_buffer:: 32,587,039 ( 0.19%) ???:??? 32,220,000 ( 0.19%) ./malloc/malloc.c:_int_realloc 31,970,700 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 31,441,869 ( 0.19%) ???:llvm::BitstreamCursor::readRecord(unsigned int, llvm::SmallVectorImpl&, llvm::StringRef*) 31,381,277 ( 0.19%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 30,966,954 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/hash/sip.rs:::write 30,350,737 ( 0.18%) ./malloc/malloc.c:calloc 30,246,880 ( 0.18%) ???:llvm::InstCombinerImpl::visitCallInst(llvm::CallInst&) 30,246,249 ( 0.18%) /tmp/gcc-build/x86_64-unknown-linux-gnu/libstdc++-v3/libsupc++/../../../../gcc-5.5.0/libstdc++-v3/libsupc++/new_op.cc:operator new(unsigned long) 29,886,471 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 28,493,069 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::check 27,782,046 ( 0.17%) ???:llvm::removeUnreachableBlocks(llvm::Function&, llvm::DomTreeUpdater*, llvm::MemorySSAUpdater*) 27,646,596 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:, proc_macro::bridge::client::SourceFile>, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 27,431,305 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 26,796,710 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:>>::insert 25,873,071 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/remove.rs:, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::KV>>::remove_leaf_kv::<>>::remove_kv::{closure#0}> 25,584,384 ( 0.15%) ???:llvm::ValueHandleBase::AddToUseList() 25,300,080 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/map/entry.rs:>>::remove_entry 25,099,587 ( 0.15%) ???:core::ptr::mut_ptr::::is_null 24,714,559 ( 0.15%) ???:llvm::DomTreeBuilder::SemiNCAInfo >::CalculateFromScratch(llvm::DominatorTreeBase&, llvm::DomTreeBuilder::SemiNCAInfo >::BatchUpdateInfo*) 24,532,056 ( 0.15%) ???:core::ptr::mut_ptr::::guaranteed_eq 23,960,367 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs:>::encode 23,951,700 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next_with_spacing 23,783,044 ( 0.14%) ???:llvm::LiveVariables::runOnBlock(llvm::MachineBasicBlock*, unsigned int) 23,778,264 ( 0.14%) ???:alloc::vec::Vec::push 23,467,680 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs:::span_data_to_lines_and_cols 22,749,723 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/server.rs: as core::convert::From<&mut _>>::from::call::, proc_macro::bridge::buffer::Buffer, ::run_bridge_and_client proc_macro::TokenStream, proc_macro::bridge::server::Dispatcher>>::{closure#0}> 22,547,459 ( 0.13%) ???:>::extend 22,323,600 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/node.rs:, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::Edge>>::insert_fit 22,265,051 ( 0.13%) ???:core::iter::traits::iterator::Iterator::fold 22,263,653 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:> as core::ops::drop::Drop>::drop 21,790,752 ( 0.13%) ./elf/dl-lookup.c:_dl_lookup_symbol_x 21,430,084 ( 0.13%) ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S:__memset_avx2_unaligned_erms 20,833,630 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::is_keyword 20,520,298 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 20,507,612 ( 0.12%) ???:llvm::X86TargetMachine::getSubtargetImpl(llvm::Function const&) const 20,125,742 ( 0.12%) ???:core::str::traits::::eq 20,124,320 ( 0.12%) ???:llvm::LiveVariables::HandleRegMask(llvm::MachineOperand const&) 20,055,210 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/node.rs:, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::KV>>::remove_leaf_kv::<>>::remove_kv::{closure#0}> 19,780,305 ( 0.12%) ???:(anonymous namespace)::MachineCopyPropagation::runOnMachineFunction(llvm::MachineFunction&) 19,656,254 ( 0.12%) ???: as core::ops::try_trait::Try>::branch 19,540,143 ( 0.12%) ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S:__memset_avx2_erms 19,420,858 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/map/entry.rs:>>::insert 19,385,534 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 19,296,926 ( 0.12%) ???:llvm::AttributeSetNode::get(llvm::LLVMContext&, llvm::AttrBuilder const&) 18,900,601 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::hash_stable 18,813,884 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::from_lit_token 18,603,000 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/map.rs:>>::insert 18,030,278 ( 0.11%) ???:llvm::DomTreeBuilder::SemiNCAInfo >::FindRoots(llvm::DominatorTreeBase const&, llvm::DomTreeBuilder::SemiNCAInfo >::BatchUpdateInfo*) 17,887,806 ( 0.11%) ???:(anonymous namespace)::CVPLatticeFunc::ComputeInstructionState(llvm::Instruction&, llvm::DenseMap, llvm::PointerIntPairInfo > >, (anonymous namespace)::CVPLatticeVal, llvm::DenseMapInfo, llvm::PointerIntPairInfo > > >, llvm::detail::DenseMapPair, llvm::PointerIntPairInfo > >, (anonymous namespace)::CVPLatticeVal> >&, llvm::SparseSolver, llvm::PointerIntPairInfo > >, (anonymous namespace)::CVPLatticeVal, llvm::LatticeKeyInfo, llvm::PointerIntPairInfo > > > >&) 17,805,979 ( 0.11%) ???:llvm::PMDataManager::removeNotPreservedAnalysis(llvm::Pass*) 17,731,812 ( 0.11%) ???:llvm::MD5::final(llvm::MD5::MD5Result&) 17,694,229 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/closure.rs: as core::convert::From<&mut _>>::from::call::, proc_macro::bridge::buffer::Buffer, ::run_bridge_and_client proc_macro::TokenStream, proc_macro::bridge::server::Dispatcher>>::{closure#0}> 17,326,501 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/decoder.rs:>::decode 17,206,251 ( 0.10%) ???:llvm::PassManager, llvm::LazyCallGraph&, llvm::CGSCCUpdateResult&>::run(llvm::LazyCallGraph::SCC&, llvm::AnalysisManager&, llvm::LazyCallGraph&, llvm::CGSCCUpdateResult&) 17,111,770 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs:, proc_macro::bridge::rpc::PanicMessage> as proc_macro::bridge::rpc::Encode>>>::encode 17,022,461 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::eq 17,019,784 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: -------------------------------------------------------------------------------- -- 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. 889,417 ( 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,558,409 ( 0.01%) self.ptr = unsafe { NonNull::new_unchecked(self.ptr.as_ptr().offset(offset)) }; . old . } . } . . // Helper function for moving the end of the iterator backwards by `offset` elements, . // returning the new end. . // Unsafe because the offset must not exceed `self.len()`. . #[inline(always)] -- line 101 ---------------------------------------- -- line 102 ---------------------------------------- . unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T { . if mem::size_of::() == 0 { . zst_shrink!(self, offset); . self.ptr.as_ptr() . } else { . // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`, . // which is guaranteed to not overflow an `isize`. Also, the resulting pointer . // is in bounds of `slice`, which fulfills the other requirements for `offset`. 2,565 ( 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 { 4,423,521 ( 0.03%) 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 { 1,068,117 ( 0.01%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 426,703 ( 0.00%) assume(!self.end.is_null()); . } 196,669,021 ( 1.17%) if is_empty!(self) { . None . } else { 1 ( 0.00%) Some(next_unchecked!(self)) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 4,091,443 ( 0.02%) let exact = len!(self); . (exact, Some(exact)) . } . . #[inline] . fn count(self) -> usize { . len!(self) . } . . #[inline] . fn nth(&mut self, n: usize) -> Option<$elem> { 132,101 ( 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() { 12,985 ( 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, . { 14,490 ( 0.00%) while let Some(x) = self.next() { 25,221 ( 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] 1,992 ( 0.00%) fn any(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 1,700,427 ( 0.01%) while let Some(x) = self.next() { 10,986,227 ( 0.07%) if f(x) { . return true; . } . } . false 1,992 ( 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, . { 90,568 ( 0.00%) while let Some(x) = self.next() { 328,154 ( 0.00%) if predicate(&x) { . return Some(x); . } . } . None 2,832 ( 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, . { 86,194 ( 0.00%) while let Some(x) = self.next() { 582,538 ( 0.00%) if let Some(y) = f(x) { 38,774 ( 0.00%) return Some(y); . } . } . None 33,152 ( 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() { 342,085 ( 0.00%) if predicate(x) { . // SAFETY: we are guaranteed to be in bounds by the loop invariant: . // when `i >= n`, `self.next()` returns `None` and the loop breaks. . unsafe { assume(i < n) }; . return Some(i); . } . i += 1; . } . None -- line 303 ---------------------------------------- -- line 308 ---------------------------------------- . // faster to compile. Also, the `assume` avoids a bounds check. . #[inline] . fn rposition

(&mut self, mut predicate: P) -> Option where . P: FnMut(Self::Item) -> bool, . Self: Sized + ExactSizeIterator + DoubleEndedIterator . { . let n = len!(self); . let mut i = n; 271,931 ( 0.00%) while let Some(x) = self.next_back() { 3,604,483 ( 0.02%) i -= 1; 2,995,215 ( 0.02%) 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` 184,738 ( 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 { 3,032 ( 0.00%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 3,054 ( 0.00%) assume(!self.end.is_null()); . } 4,139,358 ( 0.02%) if is_empty!(self) { . None . } else { . Some(next_back_unchecked!(self)) . } . } . } . . #[inline] -- line 369 ---------------------------------------- 27,815,800 ( 0.17%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/node.rs -------------------------------------------------------------------------------- Ir -- line 221 ---------------------------------------- . NodeRef { height: 0, node: NonNull::from(Box::leak(leaf)), _marker: PhantomData } . } . } . . impl NodeRef { . fn new_internal(child: Root) -> Self { . let mut new_node = unsafe { InternalNode::new() }; . new_node.edges[0].write(child.node); 17,246 ( 0.00%) unsafe { NodeRef::from_new_internal(new_node, child.height + 1) } . } . . /// # Safety . /// `height` must not be zero. . unsafe fn from_new_internal(internal: Box>, height: usize) -> Self { . debug_assert!(height > 0); . let node = NonNull::from(Box::leak(internal)).cast(); . let mut this = NodeRef { height, node, _marker: PhantomData }; -- line 237 ---------------------------------------- -- line 269 ---------------------------------------- . impl NodeRef { . /// Finds the length of the node. This is the number of keys or values. . /// The number of edges is `len() + 1`. . /// Note that, despite being safe, calling this function can have the side effect . /// of invalidating mutable references that unsafe code has created. . pub fn len(&self) -> usize { . // Crucially, we only access the `len` field here. If BorrowType is marker::ValMut, . // there might be outstanding mutable references to values that we must not invalidate. 1,354,898 ( 0.01%) unsafe { usize::from((*Self::as_leaf_ptr(self)).len) } . } . . /// Returns the number of levels that the node and leaves are apart. Zero . /// height means the node is a leaf itself. If you picture trees with the . /// root on top, the number says at which elevation the node appears. . /// If you picture trees with leaves on top, the number says how high . /// the tree extends above the node. . pub fn height(&self) -> usize { . self.height . } . . /// Temporarily takes out another, immutable reference to the same node. . pub fn reborrow(&self) -> NodeRef, K, V, Type> { 3,067,662 ( 0.02%) NodeRef { height: self.height, node: self.node, _marker: PhantomData } . } . . /// Exposes the leaf portion of any leaf or internal node. . /// . /// Returns a raw ptr to avoid invalidating other references to this node. . fn as_leaf_ptr(this: &Self) -> *mut LeafNode { . // The node must be valid for at least the LeafNode portion. . // This is not a reference in the NodeRef type because we don't know if -- line 299 ---------------------------------------- -- line 314 ---------------------------------------- . /// both, upon success, do nothing. . pub fn ascend( . self, . ) -> Result, marker::Edge>, Self> { . assert!(BorrowType::PERMITS_TRAVERSAL); . // We need to use raw pointers to nodes because, if BorrowType is marker::ValMut, . // there might be outstanding mutable references to values that we must not invalidate. . let leaf_ptr: *const _ = Self::as_leaf_ptr(&self); 1,018,227 ( 0.01%) unsafe { (*leaf_ptr).parent } . .as_ref() . .map(|parent| Handle { 1,444,648 ( 0.01%) node: NodeRef::from_internal(*parent, self.height + 1), 443,792 ( 0.00%) idx: unsafe { usize::from((*leaf_ptr).parent_idx.assume_init()) }, . _marker: PhantomData, . }) . .ok_or(self) . } . . pub fn first_edge(self) -> Handle { . unsafe { Handle::new_edge(self, 0) } . } -- line 334 ---------------------------------------- -- line 373 ---------------------------------------- . // SAFETY: there can be no mutable references into this tree borrowed as `Immut`. . unsafe { &*ptr } . } . . /// Borrows a view into the keys stored in the node. . pub fn keys(&self) -> &[K] { . let leaf = self.into_leaf(); . unsafe { 8,667,212 ( 0.05%) MaybeUninit::slice_assume_init_ref(leaf.keys.get_unchecked(..usize::from(leaf.len))) . } . } . } . . impl NodeRef { . /// Similar to `ascend`, gets a reference to a node's parent node, but also . /// deallocates the current node in the process. This is unsafe because the . /// current node will still be accessible despite being deallocated. -- line 389 ---------------------------------------- -- line 391 ---------------------------------------- . self, . ) -> Option, marker::Edge>> { . let height = self.height; . let node = self.node; . let ret = self.ascend().ok(); . unsafe { . Global.deallocate( . node.cast(), 130,884 ( 0.00%) if height > 0 { . Layout::new::>() . } else { . Layout::new::>() . }, . ); . } . ret . } -- line 407 ---------------------------------------- -- line 435 ---------------------------------------- . // SAFETY: we have exclusive access to the entire node. . unsafe { &mut *ptr } . } . } . . impl NodeRef { . /// Borrows exclusive access to the leaf portion of a dying leaf or internal node. . fn as_leaf_dying(&mut self) -> &mut LeafNode { 1 ( 0.00%) let ptr = Self::as_leaf_ptr(self); . // SAFETY: we have exclusive access to the entire node. . unsafe { &mut *ptr } . } . } . . impl<'a, K: 'a, V: 'a, Type> NodeRef, K, V, Type> { . /// Borrows exclusive access to an element of the key storage area. . /// -- line 451 ---------------------------------------- -- line 467 ---------------------------------------- . /// `index` is in bounds of 0..CAPACITY . unsafe fn val_area_mut(&mut self, index: I) -> &mut Output . where . I: SliceIndex<[MaybeUninit], Output = Output>, . { . // SAFETY: the caller will not be able to call further methods on self . // until the value slice reference is dropped, as we have unique access . // for the lifetime of the borrow. 1,231,488 ( 0.01%) unsafe { self.as_leaf_mut().vals.as_mut_slice().get_unchecked_mut(index) } . } . } . . impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::Internal> { . /// Borrows exclusive access to an element or slice of the node's storage area for edge contents. . /// . /// # Safety . /// `index` is in bounds of 0..CAPACITY + 1 -- line 483 ---------------------------------------- -- line 534 ---------------------------------------- . } . } . . impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::LeafOrInternal> { . /// Sets the node's link to its parent edge, . /// without invalidating other references to the node. . fn set_parent_link(&mut self, parent: NonNull>, parent_idx: usize) { . let leaf = Self::as_leaf_ptr(self); 272,985 ( 0.00%) unsafe { (*leaf).parent = Some(parent) }; . unsafe { (*leaf).parent_idx.write(parent_idx as u16) }; . } . } . . impl NodeRef { . /// Clears the root's link to its parent edge. . fn clear_parent_link(&mut self) { . let mut root_node = self.borrow_mut(); . let leaf = root_node.as_leaf_mut(); 7,463 ( 0.00%) leaf.parent = None; . } . } . . impl NodeRef { . /// Returns a new owned tree, with its own root node that is initially empty. . pub fn new() -> Self { . NodeRef::new_leaf().forget_type() . } . . /// Adds a new internal node with a single edge pointing to the previous root node, . /// make that new node the root node, and return it. This increases the height by 1 . /// and is the opposite of `pop_internal_level`. 51,738 ( 0.00%) pub fn push_internal_level(&mut self) -> NodeRef, K, V, marker::Internal> { . super::mem::take_mut(self, |old_root| NodeRef::new_internal(old_root).forget_type()); . . // `self.borrow_mut()`, except that we just forgot we're internal now: . NodeRef { height: self.height, node: self.node, _marker: PhantomData } 68,984 ( 0.00%) } . . /// Removes the internal root node, using its first child as the new root node. . /// As it is intended only to be called when the root node has only one child, . /// no cleanup is done on any of the keys, values and other children. . /// This decreases the height by 1 and is the opposite of `push_internal_level`. . /// . /// Requires exclusive access to the `NodeRef` object but not to the root node; . /// it will not invalidate other handles or references to the root node. . /// . /// Panics if there is no internal level, i.e., if the root node is a leaf. . pub fn pop_internal_level(&mut self) { 22,231 ( 0.00%) assert!(self.height > 0); . . let top = self.node; . . // SAFETY: we asserted to be internal. . let internal_self = unsafe { self.borrow_mut().cast_to_internal_unchecked() }; . // SAFETY: we borrowed `self` exclusively and its borrow type is exclusive. . let internal_node = unsafe { &mut *NodeRef::as_internal_ptr(&internal_self) }; . // SAFETY: the first edge is always initialized. 7,463 ( 0.00%) self.node = unsafe { internal_node.edges[0].assume_init_read() }; 14,926 ( 0.00%) self.height -= 1; . self.clear_parent_link(); . . unsafe { . Global.deallocate(top.cast(), Layout::new::>()); . } . } . } . . impl NodeRef { . /// Mutably borrows the owned root node. Unlike `reborrow_mut`, this is safe . /// because the return value cannot be used to destroy the root, and there . /// cannot be other references to the tree. . pub fn borrow_mut(&mut self) -> NodeRef, K, V, Type> { 7,026,719 ( 0.04%) NodeRef { height: self.height, node: self.node, _marker: PhantomData } . } . . /// Slightly mutably borrows the owned root node. . pub fn borrow_valmut(&mut self) -> NodeRef, K, V, Type> { . NodeRef { height: self.height, node: self.node, _marker: PhantomData } . } . . /// Irreversibly transitions to a reference that permits traversal and offers -- line 614 ---------------------------------------- -- line 617 ---------------------------------------- . NodeRef { height: self.height, node: self.node, _marker: PhantomData } . } . } . . impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::Leaf> { . /// Adds a key-value pair to the end of the node. . pub fn push(&mut self, key: K, val: V) { . let len = self.len_mut(); 22 ( 0.00%) let idx = usize::from(*len); 11 ( 0.00%) assert!(idx < CAPACITY); 24 ( 0.00%) *len += 1; . unsafe { . self.key_area_mut(idx).write(key); . self.val_area_mut(idx).write(val); . } . } . } . . impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::Internal> { . /// Adds a key-value pair, and an edge to go to the right of that pair, . /// to the end of the node. . pub fn push(&mut self, key: K, val: V, edge: Root) { 34,492 ( 0.00%) assert!(edge.height == self.height - 1); . . let len = self.len_mut(); 17,246 ( 0.00%) let idx = usize::from(*len); 8,623 ( 0.00%) assert!(idx < CAPACITY); 17,246 ( 0.00%) *len += 1; . unsafe { . self.key_area_mut(idx).write(key); . self.val_area_mut(idx).write(val); 8,623 ( 0.00%) self.edge_area_mut(idx + 1).write(edge.node); . Handle::new_edge(self.reborrow_mut(), idx + 1).correct_parent_link(); . } . } . } . . impl NodeRef { . /// Removes any static information asserting that this node is a `Leaf` node. . pub fn forget_type(self) -> NodeRef { -- line 656 ---------------------------------------- -- line 668 ---------------------------------------- . impl NodeRef { . /// Checks whether a node is an `Internal` node or a `Leaf` node. . pub fn force( . self, . ) -> ForceResult< . NodeRef, . NodeRef, . > { 8,491,988 ( 0.05%) if self.height == 0 { . ForceResult::Leaf(NodeRef { . height: self.height, . node: self.node, . _marker: PhantomData, . }) . } else { . ForceResult::Internal(NodeRef { . height: self.height, -- line 684 ---------------------------------------- -- line 747 ---------------------------------------- . Handle { node, idx, _marker: PhantomData } . } . . pub fn left_edge(self) -> Handle, marker::Edge> { . unsafe { Handle::new_edge(self.node, self.idx) } . } . . pub fn right_edge(self) -> Handle, marker::Edge> { 332,580 ( 0.00%) unsafe { Handle::new_edge(self.node, self.idx + 1) } . } . } . . impl PartialEq . for Handle, HandleType> . { . fn eq(&self, other: &Self) -> bool { . let Self { node, idx, _marker } = self; -- line 763 ---------------------------------------- -- line 790 ---------------------------------------- . } . . impl Handle, marker::Edge> { . /// Creates a new handle to an edge in `node`. . /// Unsafe because the caller must ensure that `idx <= node.len()`. . pub unsafe fn new_edge(node: NodeRef, idx: usize) -> Self { . debug_assert!(idx <= node.len()); . 1,652,877 ( 0.01%) Handle { node, idx, _marker: PhantomData } . } . . pub fn left_kv(self) -> Result, marker::KV>, Self> { 136,354 ( 0.00%) if self.idx > 0 { 130,548 ( 0.00%) Ok(unsafe { Handle::new_kv(self.node, self.idx - 1) }) . } else { . Err(self) . } . } . . pub fn right_kv(self) -> Result, marker::KV>, Self> { 539,941 ( 0.00%) if self.idx < self.node.len() { . Ok(unsafe { Handle::new_kv(self.node, self.idx) }) . } else { . Err(self) . } . } . } . . pub enum LeftOrRight { -- line 818 ---------------------------------------- -- line 820 ---------------------------------------- . Right(T), . } . . /// Given an edge index where we want to insert into a node filled to capacity, . /// computes a sensible KV index of a split point and where to perform the insertion. . /// The goal of the split point is for its key and value to end up in a parent node; . /// the keys, values and edges to the left of the split point become the left child; . /// the keys, values and edges to the right of the split point become the right child. 143,521 ( 0.00%) fn splitpoint(edge_idx: usize) -> (usize, LeftOrRight) { . debug_assert!(edge_idx <= CAPACITY); . // Rust issue #74834 tries to explain these symmetric rules. 573,806 ( 0.00%) match edge_idx { 287,042 ( 0.00%) 0..EDGE_IDX_LEFT_OF_CENTER => (KV_IDX_CENTER - 1, LeftOrRight::Left(edge_idx)), . EDGE_IDX_LEFT_OF_CENTER => (KV_IDX_CENTER, LeftOrRight::Left(edge_idx)), . EDGE_IDX_RIGHT_OF_CENTER => (KV_IDX_CENTER, LeftOrRight::Right(0)), 429,672 ( 0.00%) _ => (KV_IDX_CENTER + 1, LeftOrRight::Right(edge_idx - (KV_IDX_CENTER + 1 + 1))), . } 143,521 ( 0.00%) } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { . /// Inserts a new key-value pair between the key-value pairs to the right and left of . /// this edge. This method assumes that there is enough space in the node for the new . /// pair to fit. . /// . /// The returned pointer points to the inserted value. 9,216,231 ( 0.06%) fn insert_fit(&mut self, key: K, val: V) -> *mut V { . debug_assert!(self.node.len() < CAPACITY); . let new_len = self.node.len() + 1; . . unsafe { 1,164,100 ( 0.01%) slice_insert(self.node.key_area_mut(..new_len), self.idx, key); 1,310,674 ( 0.01%) slice_insert(self.node.val_area_mut(..new_len), self.idx, val); 1,164,097 ( 0.01%) *self.node.len_mut() = new_len as u16; . . self.node.val_area_mut(self.idx).assume_init_mut() . } 9,313,018 ( 0.06%) } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { . /// Inserts a new key-value pair between the key-value pairs to the right and left of . /// this edge. This method splits the node if there isn't enough room. . /// . /// The returned pointer points to the inserted value. . fn insert(mut self, key: K, val: V) -> (InsertResult<'a, K, V, marker::Leaf>, *mut V) { 3,492,291 ( 0.02%) if self.node.len() < CAPACITY { 5,429,507 ( 0.03%) let val_ptr = self.insert_fit(key, val); 2,063,996 ( 0.01%) let kv = unsafe { Handle::new_kv(self.node, self.idx) }; . (InsertResult::Fit(kv), val_ptr) . } else { 1,056,792 ( 0.01%) let (middle_kv_idx, insertion) = splitpoint(self.idx); 261,307 ( 0.00%) let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) }; . let mut result = middle.split(); 658,300 ( 0.00%) let mut insertion_edge = match insertion { . LeftOrRight::Left(insert_idx) => unsafe { . Handle::new_edge(result.left.reborrow_mut(), insert_idx) . }, . LeftOrRight::Right(insert_idx) => unsafe { . Handle::new_edge(result.right.borrow_mut(), insert_idx) . }, . }; 312,015 ( 0.00%) let val_ptr = insertion_edge.insert_fit(key, val); 266,596 ( 0.00%) (InsertResult::Split(result), val_ptr) . } . } . } . . impl<'a, K, V> Handle, K, V, marker::Internal>, marker::Edge> { . /// Fixes the parent pointer and index in the child node that this edge . /// links to. This is useful when the ordering of edges has been changed, . fn correct_parent_link(self) { -- line 890 ---------------------------------------- -- line 895 ---------------------------------------- . child.set_parent_link(ptr, idx); . } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::Edge> { . /// Inserts a new key-value pair and an edge that will go to the right of that new pair . /// between this edge and the key-value pair to the right of this edge. This method assumes . /// that there is enough space in the node for the new pair to fit. 1,075,084 ( 0.01%) fn insert_fit(&mut self, key: K, val: V, edge: Root) { . debug_assert!(self.node.len() < CAPACITY); . debug_assert!(edge.height == self.node.height - 1); . let new_len = self.node.len() + 1; . . unsafe { 134,898 ( 0.00%) slice_insert(self.node.key_area_mut(..new_len), self.idx, key); 12,916 ( 0.00%) slice_insert(self.node.val_area_mut(..new_len), self.idx, val); . slice_insert(self.node.edge_area_mut(..new_len + 1), self.idx + 1, edge.node); 134,898 ( 0.00%) *self.node.len_mut() = new_len as u16; . . self.node.correct_childrens_parent_links(self.idx + 1..new_len + 1); . } 1,079,184 ( 0.01%) } . . /// Inserts a new key-value pair and an edge that will go to the right of that new pair . /// between this edge and the key-value pair to the right of this edge. This method splits . /// the node if there isn't enough room. . fn insert( . mut self, . key: K, . val: V, . edge: Root, . ) -> InsertResult<'a, K, V, marker::Internal> { 404,694 ( 0.00%) assert!(edge.height == self.node.height - 1); . 269,796 ( 0.00%) if self.node.len() < CAPACITY { 401,642 ( 0.00%) self.insert_fit(key, val, edge); . let kv = unsafe { Handle::new_kv(self.node, self.idx) }; . InsertResult::Fit(kv) . } else { 81,274 ( 0.00%) let (middle_kv_idx, insertion) = splitpoint(self.idx); . let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) }; . let mut result = middle.split(); 12,682 ( 0.00%) let mut insertion_edge = match insertion { . LeftOrRight::Left(insert_idx) => unsafe { . Handle::new_edge(result.left.reborrow_mut(), insert_idx) . }, . LeftOrRight::Right(insert_idx) => unsafe { . Handle::new_edge(result.right.borrow_mut(), insert_idx) . }, . }; 89,237 ( 0.00%) insertion_edge.insert_fit(key, val, edge); 20,579 ( 0.00%) InsertResult::Split(result) . } . } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { . /// Inserts a new key-value pair between the key-value pairs to the right and left of . /// this edge. This method splits the node if there isn't enough room, and tries to . /// insert the split off portion into the parent node recursively, until the root is reached. . /// . /// If the returned result is a `Fit`, its handle's node can be this edge's node or an ancestor. . /// If the returned result is a `Split`, the `left` field will be the root node. . /// The returned pointer points to the inserted value. 11,520,421 ( 0.07%) pub fn insert_recursing( . self, . key: K, . value: V, . ) -> (InsertResult<'a, K, V, marker::LeafOrInternal>, *mut V) { 6,739,031 ( 0.04%) let (mut split, val_ptr) = match self.insert(key, value) { . (InsertResult::Fit(handle), ptr) => { 5,159,990 ( 0.03%) return (InsertResult::Fit(handle.forget_node_type()), ptr); . } . (InsertResult::Split(split), val_ptr) => (split.forget_node_type(), val_ptr), . }; . . loop { 1,036,181 ( 0.01%) split = match split.left.ascend() { 539,721 ( 0.00%) Ok(parent) => match parent.insert(split.kv.0, split.kv.1, split.right) { . InsertResult::Fit(handle) => { 626,336 ( 0.00%) return (InsertResult::Fit(handle.forget_node_type()), val_ptr); . } 604 ( 0.00%) InsertResult::Split(split) => split.forget_node_type(), . }, . Err(root) => { 85,793 ( 0.00%) return (InsertResult::Split(SplitResult { left: root, ..split }), val_ptr); . } . }; . } 10,476,873 ( 0.06%) } . } . . impl . Handle, marker::Edge> . { . /// Finds the node pointed to by this edge. . /// . /// The method name assumes you picture trees with the root node on top. -- line 992 ---------------------------------------- -- line 999 ---------------------------------------- . // marker::ValMut, there might be outstanding mutable references to . // values that we must not invalidate. There's no worry accessing the . // height field because that value is copied. Beware that, once the . // node pointer is dereferenced, we access the edges array with a . // reference (Rust issue #73987) and invalidate any other references . // to or inside the array, should any be around. . let parent_ptr = NodeRef::as_internal_ptr(&self.node); . let node = unsafe { (*parent_ptr).edges.get_unchecked(self.idx).assume_init_read() }; 416,941 ( 0.00%) NodeRef { node, height: self.node.height - 1, _marker: PhantomData } . } . } . . impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { . pub fn into_kv(self) -> (&'a K, &'a V) { . debug_assert!(self.idx < self.node.len()); . let leaf = self.node.into_leaf(); . let k = unsafe { leaf.keys.get_unchecked(self.idx).assume_init_ref() }; . let v = unsafe { leaf.vals.get_unchecked(self.idx).assume_init_ref() }; 661,394 ( 0.00%) (k, v) . } . } . . impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { . pub fn key_mut(&mut self) -> &mut K { . unsafe { self.node.key_area_mut(self.idx).assume_init_mut() } . } . -- line 1025 ---------------------------------------- -- line 1037 ---------------------------------------- . } . . impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { . pub fn kv_mut(&mut self) -> (&mut K, &mut V) { . debug_assert!(self.idx < self.node.len()); . // We cannot call separate key and value methods, because calling the second one . // invalidates the reference returned by the first. . unsafe { 2,833 ( 0.00%) let leaf = self.node.as_leaf_mut(); 2,833 ( 0.00%) let key = leaf.keys.get_unchecked_mut(self.idx).assume_init_mut(); . let val = leaf.vals.get_unchecked_mut(self.idx).assume_init_mut(); 4,468 ( 0.00%) (key, val) . } . } . . /// Replaces the key and value that the KV handle refers to. . pub fn replace_kv(&mut self, k: K, v: V) -> (K, V) { . let (key, val) = self.kv_mut(); . (mem::replace(key, k), mem::replace(val, v)) . } -- line 1056 ---------------------------------------- -- line 1069 ---------------------------------------- . (key, val) . } . } . . /// Drops the key and value that the KV handle refers to. . /// # Safety . /// The node that the handle refers to must not yet have been deallocated. . #[inline] 6 ( 0.00%) pub unsafe fn drop_key_val(mut self) { . debug_assert!(self.idx < self.node.len()); . let leaf = self.node.as_leaf_dying(); . unsafe { 1 ( 0.00%) leaf.keys.get_unchecked_mut(self.idx).assume_init_drop(); 33,731 ( 0.00%) leaf.vals.get_unchecked_mut(self.idx).assume_init_drop(); . } 7 ( 0.00%) } . } . . impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { . /// Helps implementations of `split` for a particular `NodeType`, . /// by taking care of leaf data. . fn split_leaf_data(&mut self, new_node: &mut LeafNode) -> (K, V) { . debug_assert!(self.idx < self.node.len()); . let old_len = self.node.len(); 727,479 ( 0.00%) let new_len = old_len - self.idx - 1; 144,454 ( 0.00%) new_node.len = new_len as u16; . unsafe { 152,562 ( 0.00%) let k = self.node.key_area_mut(self.idx).assume_init_read(); 126,290 ( 0.00%) let v = self.node.val_area_mut(self.idx).assume_init_read(); . . move_to_slice( 430,563 ( 0.00%) self.node.key_area_mut(self.idx + 1..old_len), 143,521 ( 0.00%) &mut new_node.keys[..new_len], . ); . move_to_slice( . self.node.val_area_mut(self.idx + 1..old_len), 153,620 ( 0.00%) &mut new_node.vals[..new_len], . ); . 269,816 ( 0.00%) *self.node.len_mut() = self.idx as u16; 37,920 ( 0.00%) (k, v) . } . } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::KV> { . /// Splits the underlying node into three parts: . /// . /// - The node is truncated to only contain the key-value pairs to the left of -- line 1117 ---------------------------------------- -- line 1120 ---------------------------------------- . /// - All the key-value pairs to the right of this handle are put into a newly . /// allocated node. . pub fn split(mut self) -> SplitResult<'a, K, V, marker::Leaf> { . let mut new_node = LeafNode::new(); . . let kv = self.split_leaf_data(&mut new_node); . . let right = NodeRef::from_new_leaf(new_node); 1,132,182 ( 0.01%) SplitResult { left: self.node, kv, right } . } . . /// Removes the key-value pair pointed to by this handle and returns it, along with the edge . /// that the key-value pair collapsed into. . pub fn remove( . mut self, . ) -> ((K, V), Handle, K, V, marker::Leaf>, marker::Edge>) { . let old_len = self.node.len(); . unsafe { . let k = slice_remove(self.node.key_area_mut(..old_len), self.idx); 744,120 ( 0.00%) let v = slice_remove(self.node.val_area_mut(..old_len), self.idx); 3,863,256 ( 0.02%) *self.node.len_mut() = (old_len - 1) as u16; 3,710,090 ( 0.02%) ((k, v), self.left_edge()) . } . } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::KV> { . /// Splits the underlying node into three parts: . /// . /// - The node is truncated to only contain the edges and key-value pairs to the -- line 1149 ---------------------------------------- -- line 1150 ---------------------------------------- . /// left of this handle. . /// - The key and value pointed to by this handle are extracted. . /// - All the edges and key-value pairs to the right of this handle are put into . /// a newly allocated node. . pub fn split(mut self) -> SplitResult<'a, K, V, marker::Internal> { . let old_len = self.node.len(); . unsafe { . let mut new_node = InternalNode::new(); 30,297 ( 0.00%) let kv = self.split_leaf_data(&mut new_node.data); . let new_len = usize::from(new_node.data.len); . move_to_slice( 11,422 ( 0.00%) self.node.edge_area_mut(self.idx + 1..old_len + 1), 22,844 ( 0.00%) &mut new_node.edges[..new_len + 1], . ); . . let height = self.node.height; . let right = NodeRef::from_new_internal(new_node, height); . 72,059 ( 0.00%) SplitResult { left: self.node, kv, right } . } . } . } . . /// Represents a session for evaluating and performing a balancing operation . /// around an internal key-value pair. . pub struct BalancingContext<'a, K, V> { . parent: Handle, K, V, marker::Internal>, marker::KV>, -- line 1176 ---------------------------------------- -- line 1242 ---------------------------------------- . . pub fn into_right_child(self) -> NodeRef, K, V, marker::LeafOrInternal> { . self.right_child . } . . /// Returns whether merging is possible, i.e., whether there is enough room . /// in a node to combine the central KV with both adjacent child nodes. . pub fn can_merge(&self) -> bool { 403,807 ( 0.00%) self.left_child.len() + 1 + self.right_child.len() <= CAPACITY . } . } . . impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { . /// Performs a merge and lets a closure decide what to return. . fn do_merge< . F: FnOnce( . NodeRef, K, V, marker::Internal>, -- line 1258 ---------------------------------------- -- line 1264 ---------------------------------------- . result: F, . ) -> R { . let Handle { node: mut parent_node, idx: parent_idx, _marker } = self.parent; . let old_parent_len = parent_node.len(); . let mut left_node = self.left_child; . let old_left_len = left_node.len(); . let mut right_node = self.right_child; . let right_len = right_node.len(); 263,538 ( 0.00%) let new_left_len = old_left_len + 1 + right_len; . 263,538 ( 0.00%) assert!(new_left_len <= CAPACITY); . . unsafe { 131,769 ( 0.00%) *left_node.len_mut() = new_left_len as u16; . . let parent_key = slice_remove(parent_node.key_area_mut(..old_parent_len), parent_idx); . left_node.key_area_mut(old_left_len).write(parent_key); . move_to_slice( . right_node.key_area_mut(..right_len), . left_node.key_area_mut(old_left_len + 1..new_left_len), . ); . . let parent_val = slice_remove(parent_node.val_area_mut(..old_parent_len), parent_idx); . left_node.val_area_mut(old_left_len).write(parent_val); . move_to_slice( . right_node.val_area_mut(..right_len), . left_node.val_area_mut(old_left_len + 1..new_left_len), . ); . 131,769 ( 0.00%) slice_remove(&mut parent_node.edge_area_mut(..old_parent_len + 1), parent_idx + 1); . parent_node.correct_childrens_parent_links(parent_idx + 1..old_parent_len); 790,614 ( 0.00%) *parent_node.len_mut() -= 1; . 263,538 ( 0.00%) if parent_node.height > 1 { . // SAFETY: the height of the nodes being merged is one below the height . // of the node of this edge, thus above zero, so they are internal. . let mut left_node = left_node.reborrow_mut().cast_to_internal_unchecked(); . let mut right_node = right_node.cast_to_internal_unchecked(); . move_to_slice( . right_node.edge_area_mut(..right_len + 1), 10,310 ( 0.00%) left_node.edge_area_mut(old_left_len + 1..new_left_len + 1), . ); . . left_node.correct_childrens_parent_links(old_left_len + 1..new_left_len + 1); . . Global.deallocate(right_node.node.cast(), Layout::new::>()); . } else { . Global.deallocate(right_node.node.cast(), Layout::new::>()); . } -- line 1312 ---------------------------------------- -- line 1313 ---------------------------------------- . } . result(parent_node, left_node) . } . . /// Merges the parent's key-value pair and both adjacent child nodes into . /// the left child node and returns the shrunk parent node. . /// . /// Panics unless we `.can_merge()`. 72,170 ( 0.00%) pub fn merge_tracking_parent(self) -> NodeRef, K, V, marker::Internal> { 20,620 ( 0.00%) self.do_merge(|parent, _child| parent) 103,040 ( 0.00%) } . . /// Merges the parent's key-value pair and both adjacent child nodes into . /// the left child node and returns that child node. . /// . /// Panics unless we `.can_merge()`. . pub fn merge_tracking_child(self) -> NodeRef, K, V, marker::LeafOrInternal> { . self.do_merge(|_parent, child| child) . } . . /// Merges the parent's key-value pair and both adjacent child nodes into . /// the left child node and returns the edge handle in that child node . /// where the tracked child edge ended up, . /// . /// Panics unless we `.can_merge()`. 850,213 ( 0.01%) pub fn merge_tracking_child_edge( . self, . track_edge_idx: LeftOrRight, . ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { 121,459 ( 0.00%) let old_left_len = self.left_child.len(); 121,459 ( 0.00%) let right_len = self.right_child.len(); 364,377 ( 0.00%) assert!(match track_edge_idx { . LeftOrRight::Left(idx) => idx <= old_left_len, . LeftOrRight::Right(idx) => idx <= right_len, . }); . let child = self.merge_tracking_child(); 121,459 ( 0.00%) let new_idx = match track_edge_idx { . LeftOrRight::Left(idx) => idx, 356,172 ( 0.00%) LeftOrRight::Right(idx) => old_left_len + 1 + idx, . }; . unsafe { Handle::new_edge(child, new_idx) } 971,672 ( 0.01%) } . . /// Removes a key-value pair from the left child and places it in the key-value storage . /// of the parent, while pushing the old parent key-value pair into the right child. . /// Returns a handle to the edge in the right child corresponding to where the original . /// edge specified by `track_right_edge_idx` ended up. . pub fn steal_left( . mut self, . track_right_edge_idx: usize, . ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { 3,250 ( 0.00%) self.bulk_steal_left(1); . unsafe { Handle::new_edge(self.right_child, 1 + track_right_edge_idx) } . } . . /// Removes a key-value pair from the right child and places it in the key-value storage . /// of the parent, while pushing the old parent key-value pair onto the left child. . /// Returns a handle to the edge in the left child specified by `track_left_edge_idx`, . /// which didn't move. . pub fn steal_right( . mut self, . track_left_edge_idx: usize, . ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { 2,162 ( 0.00%) self.bulk_steal_right(1); . unsafe { Handle::new_edge(self.left_child, track_left_edge_idx) } . } . . /// This does stealing similar to `steal_left` but steals multiple elements at once. 11,375 ( 0.00%) pub fn bulk_steal_left(&mut self, count: usize) { 3,250 ( 0.00%) assert!(count > 0); . unsafe { . let left_node = &mut self.left_child; . let old_left_len = left_node.len(); . let right_node = &mut self.right_child; 1,625 ( 0.00%) let old_right_len = right_node.len(); . . // Make sure that we may steal safely. 8,125 ( 0.00%) assert!(old_right_len + count <= CAPACITY); 4,873 ( 0.00%) assert!(old_left_len >= count); . . let new_left_len = old_left_len - count; . let new_right_len = old_right_len + count; 1,625 ( 0.00%) *left_node.len_mut() = new_left_len as u16; 2,372 ( 0.00%) *right_node.len_mut() = new_right_len as u16; . . // Move leaf data. . { . // Make room for stolen elements in the right child. . slice_shr(right_node.key_area_mut(..new_right_len), count); . slice_shr(right_node.val_area_mut(..new_right_len), count); . . // Move elements from the left child to the right one. . move_to_slice( 3,250 ( 0.00%) left_node.key_area_mut(new_left_len + 1..old_left_len), 1,625 ( 0.00%) right_node.key_area_mut(..count - 1), . ); . move_to_slice( . left_node.val_area_mut(new_left_len + 1..old_left_len), . right_node.val_area_mut(..count - 1), . ); . . // Move the left-most stolen pair to the parent. 1,623 ( 0.00%) let k = left_node.key_area_mut(new_left_len).assume_init_read(); . let v = left_node.val_area_mut(new_left_len).assume_init_read(); 4,400 ( 0.00%) let (k, v) = self.parent.replace_kv(k, v); . . // Move parent's key-value pair to the right child. . right_node.key_area_mut(count - 1).write(k); . right_node.val_area_mut(count - 1).write(v); . } . 8,125 ( 0.00%) match (left_node.reborrow_mut().force(), right_node.reborrow_mut().force()) { . (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => { . // Make room for stolen edges. . slice_shr(right.edge_area_mut(..new_right_len + 1), count); . . // Steal edges. . move_to_slice( . left.edge_area_mut(new_left_len + 1..old_left_len + 1), . right.edge_area_mut(..count), -- line 1432 ---------------------------------------- -- line 1433 ---------------------------------------- . ); . . right.correct_childrens_parent_links(0..new_right_len + 1); . } . (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {} . _ => unreachable!(), . } . } 13,000 ( 0.00%) } . . /// The symmetric clone of `bulk_steal_left`. 8,456 ( 0.00%) pub fn bulk_steal_right(&mut self, count: usize) { 2,416 ( 0.00%) assert!(count > 0); . unsafe { . let left_node = &mut self.left_child; 1,208 ( 0.00%) let old_left_len = left_node.len(); . let right_node = &mut self.right_child; . let old_right_len = right_node.len(); . . // Make sure that we may steal safely. 6,040 ( 0.00%) assert!(old_left_len + count <= CAPACITY); 2,563 ( 0.00%) assert!(old_right_len >= count); . . let new_left_len = old_left_len + count; . let new_right_len = old_right_len - count; 1,208 ( 0.00%) *left_node.len_mut() = new_left_len as u16; 1,208 ( 0.00%) *right_node.len_mut() = new_right_len as u16; . . // Move leaf data. . { . // Move the right-most stolen pair to the parent. 2,240 ( 0.00%) let k = right_node.key_area_mut(count - 1).assume_init_read(); . let v = right_node.val_area_mut(count - 1).assume_init_read(); 4,128 ( 0.00%) let (k, v) = self.parent.replace_kv(k, v); . . // Move parent's key-value pair to the left child. . left_node.key_area_mut(old_left_len).write(k); . left_node.val_area_mut(old_left_len).write(v); . . // Move elements from the right child to the left one. . move_to_slice( . right_node.key_area_mut(..count - 1), 1,208 ( 0.00%) left_node.key_area_mut(old_left_len + 1..new_left_len), . ); . move_to_slice( . right_node.val_area_mut(..count - 1), . left_node.val_area_mut(old_left_len + 1..new_left_len), . ); . . // Fill gap where stolen elements used to be. . slice_shl(right_node.key_area_mut(..old_right_len), count); . slice_shl(right_node.val_area_mut(..old_right_len), count); . } . 6,040 ( 0.00%) match (left_node.reborrow_mut().force(), right_node.reborrow_mut().force()) { . (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => { . // Steal edges. . move_to_slice( . right.edge_area_mut(..count), 127 ( 0.00%) left.edge_area_mut(old_left_len + 1..new_left_len + 1), . ); . . // Fill gap where stolen edges used to be. 127 ( 0.00%) slice_shl(right.edge_area_mut(..old_right_len + 1), count); . . left.correct_childrens_parent_links(old_left_len + 1..new_left_len + 1); 254 ( 0.00%) right.correct_childrens_parent_links(0..new_right_len + 1); . } . (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {} . _ => unreachable!(), . } . } 9,664 ( 0.00%) } . } . . impl Handle, marker::Edge> { . pub fn forget_node_type( . self, . ) -> Handle, marker::Edge> { . unsafe { Handle::new_edge(self.node.forget_type(), self.idx) } . } -- line 1513 ---------------------------------------- -- line 1681 ---------------------------------------- . /// . /// # Safety . /// The slice has more than `idx` elements. . unsafe fn slice_insert(slice: &mut [MaybeUninit], idx: usize, val: T) { . unsafe { . let len = slice.len(); . debug_assert!(len > idx); . let slice_ptr = slice.as_mut_ptr(); 9,613,275 ( 0.06%) if len > idx + 1 { 412,500 ( 0.00%) ptr::copy(slice_ptr.add(idx), slice_ptr.add(idx + 1), len - idx - 1); . } . (*slice_ptr.add(idx)).write(val); . } . } . . /// Removes and returns a value from a slice of all initialized elements, leaving behind one . /// trailing uninitialized element. . /// -- line 1698 ---------------------------------------- -- line 1699 ---------------------------------------- . /// # Safety . /// The slice has more than `idx` elements. . unsafe fn slice_remove(slice: &mut [MaybeUninit], idx: usize) -> T { . unsafe { . let len = slice.len(); . debug_assert!(idx < len); . let slice_ptr = slice.as_mut_ptr(); . let ret = (*slice_ptr.add(idx)).assume_init_read(); 10,426,000 ( 0.06%) ptr::copy(slice_ptr.add(idx + 1), slice_ptr.add(idx), len - idx - 1); . ret . } . } . . /// Shifts the elements in a slice `distance` positions to the left. . /// . /// # Safety . /// The slice has at least `distance` elements. . unsafe fn slice_shl(slice: &mut [MaybeUninit], distance: usize) { . unsafe { . let slice_ptr = slice.as_mut_ptr(); 254 ( 0.00%) ptr::copy(slice_ptr.add(distance), slice_ptr, slice.len() - distance); . } . } . . /// Shifts the elements in a slice `distance` positions to the right. . /// . /// # Safety . /// The slice has at least `distance` elements. . unsafe fn slice_shr(slice: &mut [MaybeUninit], distance: usize) { . unsafe { . let slice_ptr = slice.as_mut_ptr(); 4,128 ( 0.00%) ptr::copy(slice_ptr, slice_ptr.add(distance), slice.len() - distance); . } . } . . /// Moves all values from a slice of initialized elements to a slice . /// of uninitialized elements, leaving behind `src` as all uninitialized. . /// Works like `dst.copy_from_slice(src)` but does not require `T` to be `Copy`. . fn move_to_slice(src: &mut [MaybeUninit], dst: &mut [MaybeUninit]) { 600,888 ( 0.00%) assert!(src.len() == dst.len()); . unsafe { . ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), src.len()); . } . } . . #[cfg(test)] . mod tests; 29,088,473 ( 0.17%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/hash/sip.rs -------------------------------------------------------------------------------- Ir -- line 124 ---------------------------------------- . /// sizes and avoid calling `memcpy`, which is good for speed. . /// . /// Unsafe because: unchecked indexing at start..start+len . #[inline] . unsafe fn u8to64_le(buf: &[u8], start: usize, len: usize) -> u64 { . debug_assert!(len < 8); . let mut i = 0; // current byte index (from LSB) in the output u64 . let mut out = 0; 7,968,672 ( 0.05%) if i + 3 < len { . // SAFETY: `i` cannot be greater than `len`, and the caller must guarantee . // that the index start..start+len is in bounds. . out = unsafe { load_int_le!(buf, start + i, u32) } as u64; . i += 4; . } 16,564,567 ( 0.10%) if i + 1 < len { . // SAFETY: same as above. 8,282,312 ( 0.05%) out |= (unsafe { load_int_le!(buf, start + i, u16) } as u64) << (i * 8); 4,140,940 ( 0.02%) i += 2 . } 9,252,815 ( 0.06%) if i < len { . // SAFETY: same as above. 13,205,211 ( 0.08%) out |= (unsafe { *buf.get_unchecked(start + i) } as u64) << (i * 8); . i += 1; . } . debug_assert_eq!(i, len); . out . } . . impl SipHasher { . /// Creates a new `SipHasher` with the two initial keys set to 0. -- line 153 ---------------------------------------- -- line 190 ---------------------------------------- . /// Creates a `SipHasher13` that is keyed off the provided keys. . #[inline] . #[unstable(feature = "hashmap_internals", issue = "none")] . #[rustc_deprecated( . since = "1.13.0", . reason = "use `std::collections::hash_map::DefaultHasher` instead" . )] . pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher13 { 1,599,560 ( 0.01%) SipHasher13 { hasher: Hasher::new_with_keys(key0, key1) } . } . } . . impl Hasher { . #[inline] . fn new_with_keys(key0: u64, key1: u64) -> Hasher { 2,586 ( 0.00%) let mut state = Hasher { . k0: key0, . k1: key1, . length: 0, . state: State { v0: 0, v1: 0, v2: 0, v3: 0 }, . tail: 0, . ntail: 0, . _marker: PhantomData, . }; . state.reset(); . state . } . . #[inline] . fn reset(&mut self) { . self.length = 0; 2,398,047 ( 0.01%) self.state.v0 = self.k0 ^ 0x736f6d6570736575; 2,554,854 ( 0.02%) self.state.v1 = self.k1 ^ 0x646f72616e646f6d; . self.state.v2 = self.k0 ^ 0x6c7967656e657261; . self.state.v3 = self.k1 ^ 0x7465646279746573; . self.ntail = 0; . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl super::Hasher for SipHasher { -- line 230 ---------------------------------------- -- line 258 ---------------------------------------- . // in librustc_data_structures/sip128.rs, and add `write_u*`/`write_i*` . // methods to `SipHasher`, `SipHasher13`, and `DefaultHasher`. This would . // greatly speed up integer hashing by those hashers, at the cost of . // slightly slowing down compile speeds on some benchmarks. See #69152 for . // details. . #[inline] . fn write(&mut self, msg: &[u8]) { . let length = msg.len(); 10,181,210 ( 0.06%) self.length += length; . . let mut needed = 0; . 10,024,392 ( 0.06%) if self.ntail != 0 { 5,084,095 ( 0.03%) needed = 8 - self.ntail; . // SAFETY: `cmp::min(length, needed)` is guaranteed to not be over `length` 25,420,430 ( 0.15%) self.tail |= unsafe { u8to64_le(msg, 0, cmp::min(length, needed)) } << (8 * self.ntail); 5,084,086 ( 0.03%) if length < needed { 3,484,764 ( 0.02%) self.ntail += length; . return; . } else { 799,661 ( 0.00%) self.state.v3 ^= self.tail; . S::c_rounds(&mut self.state); 1,599,322 ( 0.01%) self.state.v0 ^= self.tail; 799,661 ( 0.00%) self.ntail = 0; . } . } . . // Buffered tail is now flushed, process new input. 2,884,539 ( 0.02%) let len = length - needed; 2,884,550 ( 0.02%) let left = len & 0x7; // len % 8 . . let mut i = needed; 4,327,147 ( 0.03%) while i < len - left { . // SAFETY: because `len - left` is the biggest multiple of 8 under . // `len`, and because `i` starts at `needed` where `len` is `length - needed`, . // `i + 8` is guaranteed to be less than or equal to `length`. . let mi = unsafe { load_int_le!(msg, i, u64) }; . 161 ( 0.00%) self.state.v3 ^= mi; . S::c_rounds(&mut self.state); 161 ( 0.00%) self.state.v0 ^= mi; . 322 ( 0.00%) i += 8; . } . . // SAFETY: `i` is now `needed + len.div_euclid(8) * 8`, . // so `i + left` = `needed + len` = `length`, which is by . // definition equal to `msg.len()`. 3,041,346 ( 0.02%) self.tail = unsafe { u8to64_le(msg, i, left) }; . self.ntail = left; . } . . #[inline] . fn finish(&self) -> u64 { 799,352 ( 0.00%) let mut state = self.state; . 3,996,760 ( 0.02%) let b: u64 = ((self.length as u64 & 0xff) << 56) | self.tail; . 799,352 ( 0.00%) state.v3 ^= b; . S::c_rounds(&mut state); 799,352 ( 0.00%) state.v0 ^= b; . 799,352 ( 0.00%) state.v2 ^= 0xff; . S::d_rounds(&mut state); . 1,598,704 ( 0.01%) state.v0 ^ state.v1 ^ state.v2 ^ state.v3 . } . } . . impl Clone for Hasher { . #[inline] . fn clone(&self) -> Hasher { . Hasher { . k0: self.k0, -- line 331 ---------------------------------------- -- line 354 ---------------------------------------- . } . . #[derive(Debug, Clone, Default)] . struct Sip13Rounds; . . impl Sip for Sip13Rounds { . #[inline] . fn c_rounds(state: &mut State) { 10,395,235 ( 0.06%) compress!(state); . } . . #[inline] . fn d_rounds(state: &mut State) { 3,197,408 ( 0.02%) compress!(state); 3,197,408 ( 0.02%) compress!(state); 2,398,056 ( 0.01%) compress!(state); . } . } . . #[derive(Debug, Clone, Default)] . struct Sip24Rounds; . . impl Sip for Sip24Rounds { . #[inline] -- line 377 ---------------------------------------- 23,678,906 ( 0.14%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs -------------------------------------------------------------------------------- Ir -- line 223 ---------------------------------------- . fn eq(&self, other: &Rhs) -> bool; . . /// This method tests for `!=`. . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] . fn ne(&self, other: &Rhs) -> bool { 221,847 ( 0.00%) !self.eq(other) . } . } . . /// Derive macro generating an impl of the trait `PartialEq`. . #[rustc_builtin_macro] . #[stable(feature = "builtin_macro_prelude", since = "1.38.0")] . #[allow_internal_unstable(core_intrinsics, structural_match)] . pub macro PartialEq($item:item) { -- line 239 ---------------------------------------- -- line 328 ---------------------------------------- . /// assert_eq!(Ordering::Less, result); . /// . /// let result = 1.cmp(&1); . /// assert_eq!(Ordering::Equal, result); . /// . /// let result = 2.cmp(&1); . /// assert_eq!(Ordering::Greater, result); . /// ``` 71,652 ( 0.00%) #[derive(Clone, Copy, PartialEq, Debug, Hash)] . #[stable(feature = "rust1", since = "1.0.0")] . #[repr(i8)] . pub enum Ordering { . /// An ordering where a compared value is less than another. . #[stable(feature = "rust1", since = "1.0.0")] . Less = -1, . /// An ordering where a compared value is equal to another. . #[stable(feature = "rust1", since = "1.0.0")] -- line 344 ---------------------------------------- -- line 569 ---------------------------------------- . /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2)); . /// . /// assert_eq!(result, Ordering::Less); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "ordering_chaining", since = "1.17.0")] . pub fn then_with Ordering>(self, f: F) -> Ordering { 114,873 ( 0.00%) match self { . Equal => f(), . _ => self, . } . } . } . . /// A helper struct for reverse ordering. . /// -- line 585 ---------------------------------------- -- line 792 ---------------------------------------- . /// ``` . #[stable(feature = "ord_max_min", since = "1.21.0")] . #[inline] . #[must_use] . fn max(self, other: Self) -> Self . where . Self: Sized, . { 319,740 ( 0.00%) max_by(self, other, Ord::cmp) . } . . /// Compares and returns the minimum of two values. . /// . /// Returns the first argument if the comparison determines them to be equal. . /// . /// # Examples . /// -- line 808 ---------------------------------------- -- line 812 ---------------------------------------- . /// ``` . #[stable(feature = "ord_max_min", since = "1.21.0")] . #[inline] . #[must_use] . fn min(self, other: Self) -> Self . where . Self: Sized, . { 6,264 ( 0.00%) min_by(self, other, Ord::cmp) . } . . /// Restrict a value to a certain interval. . /// . /// Returns `max` if `self` is greater than `max`, and `min` if `self` is . /// less than `min`. Otherwise this returns `self`. . /// . /// # Panics -- line 828 ---------------------------------------- -- line 1097 ---------------------------------------- . /// let result = 2.0 < 1.0; . /// assert_eq!(result, false); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] . fn lt(&self, other: &Rhs) -> bool { 558,384 ( 0.00%) matches!(self.partial_cmp(other), Some(Less)) . } . . /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=` . /// operator. . /// . /// # Examples . /// . /// ``` -- line 1113 ---------------------------------------- -- line 1121 ---------------------------------------- . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] . fn le(&self, other: &Rhs) -> bool { . // Pattern `Some(Less | Eq)` optimizes worse than negating `None | Some(Greater)`. . // FIXME: The root cause was fixed upstream in LLVM with: . // https://github.com/llvm/llvm-project/commit/9bad7de9a3fb844f1ca2965f35d0c2a3d1e11775 . // Revert this workaround once support for LLVM 12 gets dropped. 2,748,503 ( 0.02%) !matches!(self.partial_cmp(other), None | Some(Greater)) . } . . /// This method tests greater than (for `self` and `other`) and is used by the `>` operator. . /// . /// # Examples . /// . /// ``` . /// let result = 1.0 > 2.0; -- line 1137 ---------------------------------------- -- line 1140 ---------------------------------------- . /// let result = 2.0 > 2.0; . /// assert_eq!(result, false); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] . fn gt(&self, other: &Rhs) -> bool { 3,044,134 ( 0.02%) matches!(self.partial_cmp(other), Some(Greater)) . } . . /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` . /// operator. . /// . /// # Examples . /// . /// ``` -- line 1156 ---------------------------------------- -- line 1160 ---------------------------------------- . /// let result = 2.0 >= 2.0; . /// assert_eq!(result, true); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] . fn ge(&self, other: &Rhs) -> bool { 3,470 ( 0.00%) matches!(self.partial_cmp(other), Some(Greater | Equal)) . } . } . . /// Derive macro generating an impl of the trait `PartialOrd`. . #[rustc_builtin_macro] . #[stable(feature = "builtin_macro_prelude", since = "1.38.0")] . #[allow_internal_unstable(core_intrinsics)] . pub macro PartialOrd($item:item) { -- line 1176 ---------------------------------------- -- line 1210 ---------------------------------------- . /// . /// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1); . /// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "cmp_min_max_by", since = "1.53.0")] . pub fn min_by Ordering>(v1: T, v2: T, compare: F) -> T { 3,424,777 ( 0.02%) match compare(&v1, &v2) { . Ordering::Less | Ordering::Equal => v1, . Ordering::Greater => v2, . } 58 ( 0.00%) } . . /// Returns the element that gives the minimum value from the specified function. . /// . /// Returns the first argument if the comparison determines them to be equal. . /// . /// # Examples . /// . /// ``` -- line 1230 ---------------------------------------- -- line 1231 ---------------------------------------- . /// use std::cmp; . /// . /// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1); . /// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "cmp_min_max_by", since = "1.53.0")] 348 ( 0.00%) pub fn min_by_key K, K: Ord>(v1: T, v2: T, mut f: F) -> T { 232 ( 0.00%) min_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2))) 232 ( 0.00%) } . . /// Compares and returns the maximum of two values. . /// . /// Returns the second argument if the comparison determines them to be equal. . /// . /// Internally uses an alias to [`Ord::max`]. . /// . /// # Examples -- line 1249 ---------------------------------------- -- line 1273 ---------------------------------------- . /// . /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2); . /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "cmp_min_max_by", since = "1.53.0")] . pub fn max_by Ordering>(v1: T, v2: T, compare: F) -> T { 2,354,253 ( 0.01%) match compare(&v1, &v2) { 2,040 ( 0.00%) Ordering::Less | Ordering::Equal => v2, . Ordering::Greater => v1, . } . } . . /// Returns the element that gives the maximum value from the specified function. . /// . /// Returns the second argument if the comparison determines them to be equal. . /// -- line 1290 ---------------------------------------- -- line 1308 ---------------------------------------- . use crate::cmp::Ordering::{self, Equal, Greater, Less}; . use crate::hint::unreachable_unchecked; . . macro_rules! partial_eq_impl { . ($($t:ty)*) => ($( . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq for $t { . #[inline] 185,085 ( 0.00%) fn eq(&self, other: &$t) -> bool { (*self) == (*other) } . #[inline] 108,318 ( 0.00%) fn ne(&self, other: &$t) -> bool { (*self) != (*other) } . } . )*) . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq for () { . #[inline] . fn eq(&self, _other: &()) -> bool { -- line 1326 ---------------------------------------- -- line 1392 ---------------------------------------- . ($($t:ty)*) => ($( . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialOrd for $t { . #[inline] . fn partial_cmp(&self, other: &$t) -> Option { . Some(self.cmp(other)) . } . #[inline] 15,382,145 ( 0.09%) fn lt(&self, other: &$t) -> bool { (*self) < (*other) } . #[inline] 368,108 ( 0.00%) fn le(&self, other: &$t) -> bool { (*self) <= (*other) } . #[inline] . fn ge(&self, other: &$t) -> bool { (*self) >= (*other) } . #[inline] . fn gt(&self, other: &$t) -> bool { (*self) > (*other) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Ord for $t { . #[inline] . fn cmp(&self, other: &$t) -> Ordering { . // The order here is important to generate more optimal assembly. . // See for more info. 156,326,497 ( 0.93%) if *self < *other { Less } . else if *self == *other { Equal } . else { Greater } . } . } . )*) . } . . #[stable(feature = "rust1", since = "1.0.0")] -- line 1423 ---------------------------------------- -- line 1430 ---------------------------------------- . . #[stable(feature = "rust1", since = "1.0.0")] . impl Ord for bool { . #[inline] . fn cmp(&self, other: &bool) -> Ordering { . // Casting to i8's and converting the difference to an Ordering generates . // more optimal assembly. . // See for more info. 29,082 ( 0.00%) match (*self as i8) - (*other as i8) { . -1 => Less, . 0 => Equal, . 1 => Greater, . // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else . _ => unsafe { unreachable_unchecked() }, . } . } . } -- line 1446 ---------------------------------------- -- line 1474 ---------------------------------------- . // & pointers . . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq<&B> for &A . where . A: PartialEq, . { . #[inline] 1,494 ( 0.00%) fn eq(&self, other: &&B) -> bool { 3,991,039 ( 0.02%) PartialEq::eq(*self, *other) 363,097 ( 0.00%) } . #[inline] 8,900 ( 0.00%) fn ne(&self, other: &&B) -> bool { 66 ( 0.00%) PartialEq::ne(*self, *other) 123,967 ( 0.00%) } . } . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialOrd<&B> for &A . where . A: PartialOrd, . { . #[inline] . fn partial_cmp(&self, other: &&B) -> Option { -- line 1496 ---------------------------------------- -- line 1516 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . impl Ord for &A . where . A: Ord, . { . #[inline] . fn cmp(&self, other: &Self) -> Ordering { . Ord::cmp(*self, *other) 77,036 ( 0.00%) } . } . #[stable(feature = "rust1", since = "1.0.0")] . impl Eq for &A where A: Eq {} . . // &mut pointers . . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq<&mut B> for &mut A -- line 1532 ---------------------------------------- 14,275,984 ( 0.09%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs -------------------------------------------------------------------------------- Ir -- line 326 ---------------------------------------- . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_size_of_val", issue = "46571")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_size_of_val")] . pub const fn size_of_val(val: &T) -> usize { . // SAFETY: `val` is a reference, so it's a valid raw pointer 61,367 ( 0.00%) unsafe { intrinsics::size_of_val(val) } . } . . /// Returns the size of the pointed-to value in bytes. . /// . /// This is usually the same as `size_of::()`. However, when `T` *has* no . /// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object], . /// then `size_of_val_raw` can be used to get the dynamically-known size. . /// -- line 342 ---------------------------------------- -- line 375 ---------------------------------------- . /// assert_eq!(13, unsafe { mem::size_of_val_raw(y) }); . /// ``` . #[inline] . #[must_use] . #[unstable(feature = "layout_for_ptr", issue = "69835")] . #[rustc_const_unstable(feature = "const_size_of_val_raw", issue = "46571")] . pub const unsafe fn size_of_val_raw(val: *const T) -> usize { . // SAFETY: the caller must provide a valid raw pointer 238 ( 0.00%) unsafe { intrinsics::size_of_val(val) } . } . . /// Returns the [ABI]-required minimum alignment of a type. . /// . /// Every reference to a value of the type `T` must be a multiple of this number. . /// . /// This is the alignment used for struct fields. It may be smaller than the preferred alignment. . /// -- line 391 ---------------------------------------- -- line 831 ---------------------------------------- . #[must_use = "if you don't need the old value, you can just assign the new value directly"] . #[rustc_const_unstable(feature = "const_replace", issue = "83164")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_replace")] . pub const fn replace(dest: &mut T, src: T) -> T { . // SAFETY: We read from `dest` but directly write `src` into it afterwards, . // such that the old value is not duplicated. Nothing is dropped and . // nothing here can panic. . unsafe { 803,989 ( 0.00%) let result = ptr::read(dest); 92,822,389 ( 0.55%) ptr::write(dest, src); . result . } . } . . /// Disposes of a value. . /// . /// This does so by calling the argument's implementation of [`Drop`][drop]. . /// -- line 848 ---------------------------------------- -- line 901 ---------------------------------------- . /// . /// println!("x: {}, y: {}", x, y.0); // still available . /// ``` . /// . /// [`RefCell`]: crate::cell::RefCell . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_drop")] 405 ( 0.00%) pub fn drop(_x: T) {} . . /// Interprets `src` as having type `&U`, and then reads `src` without moving . /// the contained value. . /// . /// This function will unsafely assume the pointer `src` is valid for [`size_of::`][size_of] . /// bytes by transmuting `&T` to `&U` and then reading the `&U` (except that this is done in a way . /// that is correct even when `&U` makes stricter alignment requirements than `&T`). It will also . /// unsafely create a copy of the contained value instead of moving out of `src`. -- line 917 ---------------------------------------- -- line 991 ---------------------------------------- . } . } . . #[stable(feature = "discriminant_value", since = "1.21.0")] . impl cmp::Eq for Discriminant {} . . #[stable(feature = "discriminant_value", since = "1.21.0")] . impl hash::Hash for Discriminant { 6,480 ( 0.00%) fn hash(&self, state: &mut H) { . self.0.hash(state); 11,814 ( 0.00%) } . } . . #[stable(feature = "discriminant_value", since = "1.21.0")] . impl fmt::Debug for Discriminant { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt.debug_tuple("Discriminant").field(&self.0).finish() . } . } -- line 1009 ---------------------------------------- -- line 1031 ---------------------------------------- . /// assert_eq!(mem::discriminant(&Foo::A("bar")), mem::discriminant(&Foo::A("baz"))); . /// assert_eq!(mem::discriminant(&Foo::B(1)), mem::discriminant(&Foo::B(2))); . /// assert_ne!(mem::discriminant(&Foo::B(3)), mem::discriminant(&Foo::C(3))); . /// ``` . #[stable(feature = "discriminant_value", since = "1.21.0")] . #[rustc_const_unstable(feature = "const_discriminant", issue = "69821")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_discriminant")] . pub const fn discriminant(v: &T) -> Discriminant { 128,496 ( 0.00%) Discriminant(intrinsics::discriminant_value(v)) . } . . /// Returns the number of variants in the enum type `T`. . /// . /// If `T` is not an enum, calling this function will not result in undefined behavior, but the . /// return value is unspecified. Equally, if `T` is an enum with more variants than `usize::MAX` . /// the return value is unspecified. Uninhabited variants will be counted. . /// -- line 1047 ---------------------------------------- 101,096 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs -------------------------------------------------------------------------------- Ir -- line 21 ---------------------------------------- . . pub(super) trait DecodeMut<'a, 's, S>: Sized { . fn decode(r: &mut Reader<'a>, s: &'s mut S) -> Self; . } . . macro_rules! rpc_encode_decode { . (le $ty:ty) => { . impl Encode for $ty { 14,597,052 ( 0.09%) fn encode(self, w: &mut Writer, _: &mut S) { . w.extend_from_array(&self.to_le_bytes()); 18,246,315 ( 0.11%) } . } . . impl DecodeMut<'_, '_, S> for $ty { . fn decode(r: &mut Reader<'_>, _: &mut S) -> Self { . const N: usize = ::std::mem::size_of::<$ty>(); . . let mut bytes = [0; N]; 2,271,788 ( 0.01%) bytes.copy_from_slice(&r[..N]); 9,129,413 ( 0.05%) *r = &r[N..]; . . Self::from_le_bytes(bytes) . } . } . }; . (struct $name:ident { $($field:ident),* $(,)? }) => { . impl Encode for $name { . fn encode(self, w: &mut Writer, s: &mut S) { -- line 48 ---------------------------------------- -- line 55 ---------------------------------------- . $name { . $($field: DecodeMut::decode(r, s)),* . } . } . } . }; . (enum $name:ident $(<$($T:ident),+>)? { $($variant:ident $(($field:ident))*),* $(,)? }) => { . impl),+)?> Encode for $name $(<$($T),+>)? { 38,960,523 ( 0.23%) fn encode(self, w: &mut Writer, s: &mut S) { . // HACK(eddyb): `Tag` enum duplicated between the . // two impls as there's no other place to stash it. . #[allow(non_upper_case_globals)] . mod tag { . #[repr(u8)] enum Tag { $($variant),* } . . $(pub const $variant: u8 = Tag::$variant as u8;)* . } . 21,509,772 ( 0.13%) match self { 4,539,508 ( 0.03%) $($name::$variant $(($field))* => { 346,220 ( 0.00%) tag::$variant.encode(w, s); 5,778,704 ( 0.03%) $($field.encode(w, s);)* . })* . } 30,505,562 ( 0.18%) } . } . . impl<'a, S, $($($T: for<'s> DecodeMut<'a, 's, S>),+)?> DecodeMut<'a, '_, S> . for $name $(<$($T),+>)? . { 9,897,953 ( 0.06%) fn decode(r: &mut Reader<'a>, s: &mut S) -> Self { . // HACK(eddyb): `Tag` enum duplicated between the . // two impls as there's no other place to stash it. . #[allow(non_upper_case_globals)] . mod tag { . #[repr(u8)] enum Tag { $($variant),* } . . $(pub const $variant: u8 = Tag::$variant as u8;)* . } . 9,359,711 ( 0.06%) match u8::decode(r, s) { . $(tag::$variant => { 252,863 ( 0.00%) $(let $field = DecodeMut::decode(r, s);)* 6,751,230 ( 0.04%) $name::$variant $(($field))* 126,334 ( 0.00%) })* . _ => unreachable!(), . } 17,225,220 ( 0.10%) } . } . } . } . . impl Encode for () { . fn encode(self, _: &mut Writer, _: &mut S) {} . } . . impl DecodeMut<'_, '_, S> for () { . fn decode(_: &mut Reader<'_>, _: &mut S) -> Self {} . } . . impl Encode for u8 { 1,655,562 ( 0.01%) fn encode(self, w: &mut Writer, _: &mut S) { . w.push(self); 1,379,635 ( 0.01%) } . } . . impl DecodeMut<'_, '_, S> for u8 { . fn decode(r: &mut Reader<'_>, _: &mut S) -> Self { 38,649,802 ( 0.23%) let x = r[0]; 21,619,813 ( 0.13%) *r = &r[1..]; . x . } . } . . rpc_encode_decode!(le u32); . rpc_encode_decode!(le usize); . . impl Encode for bool { . fn encode(self, w: &mut Writer, s: &mut S) { 269,973 ( 0.00%) (self as u8).encode(w, s); . } . } . . impl DecodeMut<'_, '_, S> for bool { . fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { 179,982 ( 0.00%) match u8::decode(r, s) { . 0 => false, . 1 => true, . _ => unreachable!(), . } . } . } . . impl Encode for char { . fn encode(self, w: &mut Writer, s: &mut S) { 265,016 ( 0.00%) (self as u32).encode(w, s); . } . } . . impl DecodeMut<'_, '_, S> for char { . fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { . char::from_u32(u32::decode(r, s)).unwrap() . } . } . . impl Encode for NonZeroU32 { . fn encode(self, w: &mut Writer, s: &mut S) { 10,844,973 ( 0.06%) self.get().encode(w, s); . } . } . . impl DecodeMut<'_, '_, S> for NonZeroU32 { . fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { . Self::new(u32::decode(r, s)).unwrap() . } . } . . impl, B: Encode> Encode for (A, B) { 715 ( 0.00%) fn encode(self, w: &mut Writer, s: &mut S) { . self.0.encode(w, s); . self.1.encode(w, s); . } . } . . impl<'a, S, A: for<'s> DecodeMut<'a, 's, S>, B: for<'s> DecodeMut<'a, 's, S>> DecodeMut<'a, '_, S> . for (A, B) . { -- line 181 ---------------------------------------- -- line 204 ---------------------------------------- . Ok(x), . Err(e), . } . ); . . impl Encode for &[u8] { . fn encode(self, w: &mut Writer, s: &mut S) { . self.len().encode(w, s); 312,516 ( 0.00%) w.write_all(self).unwrap(); . } . } . . impl<'a, S> DecodeMut<'a, '_, S> for &'a [u8] { . fn decode(r: &mut Reader<'a>, s: &mut S) -> Self { . let len = usize::decode(r, s); . let xs = &r[..len]; 539,932 ( 0.00%) *r = &r[len..]; . xs . } . } . . impl Encode for &str { 312,516 ( 0.00%) fn encode(self, w: &mut Writer, s: &mut S) { . self.as_bytes().encode(w, s); 390,645 ( 0.00%) } . } . . impl<'a, S> DecodeMut<'a, '_, S> for &'a str { 179,934 ( 0.00%) fn decode(r: &mut Reader<'a>, s: &mut S) -> Self { 359,868 ( 0.00%) str::from_utf8(<&[u8]>::decode(r, s)).unwrap() 359,868 ( 0.00%) } . } . . impl Encode for String { . fn encode(self, w: &mut Writer, s: &mut S) { 312,516 ( 0.00%) self[..].encode(w, s); . } . } . . impl DecodeMut<'_, '_, S> for String { . fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { 390,645 ( 0.00%) <&str>::decode(r, s).to_string() . } . } . . /// Simplified version of panic payloads, ignoring . /// types other than `&'static str` and `String`. . pub enum PanicMessage { . StaticStr(&'static str), . String(String), -- line 253 ---------------------------------------- 36,798,731 ( 0.22%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/scoped_cell.rs -------------------------------------------------------------------------------- Ir -- line 39 ---------------------------------------- . pub const fn new(value: >::Out) -> Self { . ScopedCell(Cell::new(value)) . } . . /// Sets the value in `self` to `replacement` while . /// running `f`, which gets the old value, mutably. . /// The old value will be restored after `f` exits, even . /// by panic, including modifications made to it by `f`. 18,662,783 ( 0.11%) pub fn replace<'a, R>( . &self, . replacement: >::Out, . f: impl for<'b, 'c> FnOnce(RefMutL<'b, 'c, T>) -> R, . ) -> R { . /// Wrapper that ensures that the cell always gets filled . /// (with the original state, optionally changed by `f`), . /// even if `f` had panicked. . struct PutBackOnDrop<'a, T: LambdaL> { . cell: &'a ScopedCell, . value: Option<>::Out>, . } . . impl<'a, T: LambdaL> Drop for PutBackOnDrop<'a, T> { . fn drop(&mut self) { 2,527,748 ( 0.02%) self.cell.0.set(self.value.take().unwrap()); . } . } . 5,055,495 ( 0.03%) let mut put_back_on_drop = PutBackOnDrop { . cell: self, . value: Some(self.0.replace(unsafe { . let erased = mem::transmute_copy(&replacement); . mem::forget(replacement); . erased . })), . }; . 1,528,706 ( 0.01%) f(RefMutL(put_back_on_drop.value.as_mut().unwrap())) 24,549,233 ( 0.15%) } . . /// Sets the value in `self` to `value` while running `f`. . pub fn set(&self, value: >::Out, f: impl FnOnce() -> R) -> R { . self.replace(value, |_| f()) . } . } 1,029,443 ( 0.01%) -------------------------------------------------------------------------------- -- 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. 11,712,470 ( 0.07%) #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub enum TokenTree { . /// A single token. 2,425,233 ( 0.01%) Token(Token), . /// A delimited sequence of token trees. 380,526 ( 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 { 3,438 ( 0.00%) match self { 7,081 ( 0.00%) TokenTree::Token(token) => token.span, 3,476 ( 0.00%) TokenTree::Delimited(sp, ..) => sp.entire(), . } 850 ( 0.00%) } . . /// Modify the `TokenTree`'s span in-place. . pub fn set_span(&mut self, span: Span) { 3,438 ( 0.00%) match self { 850 ( 0.00%) TokenTree::Token(token) => token.span = span, 1,738 ( 0.00%) TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span), . } 1,719 ( 0.00%) } . 387,078 ( 0.00%) pub fn token(kind: TokenKind, span: Span) -> TokenTree { 2,146,780 ( 0.01%) TokenTree::Token(Token::new(kind, span)) 387,078 ( 0.00%) } . . /// Returns the opening delimiter as a token tree. 75,302 ( 0.00%) pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 225,906 ( 0.00%) TokenTree::token(token::OpenDelim(delim), span.open) 75,302 ( 0.00%) } . . /// Returns the closing delimiter as a token tree. 74,315 ( 0.00%) pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 222,945 ( 0.00%) TokenTree::token(token::CloseDelim(delim), span.close) 74,315 ( 0.00%) } . 60,015 ( 0.00%) pub fn uninterpolate(self) -> TokenTree { 40,010 ( 0.00%) match self { 180,045 ( 0.00%) TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()), . tt => tt, . } 80,020 ( 0.00%) } . } . . impl HashStable for TokenStream . where . CTX: crate::HashStableContext, . { 21,501 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 169,900 ( 0.00%) for sub_tt in self.trees() { . sub_tt.hash_stable(hcx, hasher); . } 19,112 ( 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 135 ---------------------------------------- . . /// A lazy version of [`TokenStream`], which defers creation . /// of an actual `TokenStream` until it is needed. . /// `Box` is here only to reduce the structure size. . #[derive(Clone)] . pub struct LazyTokenStream(Lrc>); . . impl LazyTokenStream { 204 ( 0.00%) pub fn new(inner: impl CreateTokenStream + 'static) -> LazyTokenStream { . LazyTokenStream(Lrc::new(Box::new(inner))) 204 ( 0.00%) } . . pub fn create_token_stream(&self) -> AttrAnnotatedTokenStream { 14,853 ( 0.00%) self.0.create_token_stream() . } . } . . impl fmt::Debug for LazyTokenStream { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(f, "LazyTokenStream({:?})", self.create_token_stream()) . } . } -- line 156 ---------------------------------------- -- 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 { 355,228 ( 0.00%) pub fn new(tokens: Vec<(AttrAnnotatedTokenTree, Spacing)>) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream(Lrc::new(tokens)) 355,228 ( 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. 3,711 ( 0.00%) pub fn to_tokenstream(&self) -> TokenStream { 6,143 ( 0.00%) let trees: Vec<_> = self . .0 . .iter() 79,303 ( 0.00%) .flat_map(|tree| match &tree.0 { 44,762 ( 0.00%) AttrAnnotatedTokenTree::Token(inner) => { 111,905 ( 0.00%) smallvec![(TokenTree::Token(inner.clone()), tree.1)].into_iter() . } 48,640 ( 0.00%) AttrAnnotatedTokenTree::Delimited(span, delim, stream) => smallvec![( 7,296 ( 0.00%) TokenTree::Delimited(*span, *delim, stream.to_tokenstream()), 2,432 ( 0.00%) tree.1, . )] . .into_iter(), . AttrAnnotatedTokenTree::Attributes(data) => { . let mut outer_attrs = Vec::new(); . let mut inner_attrs = Vec::new(); . for attr in &data.attrs { . match attr.style { . crate::AttrStyle::Outer => { -- line 223 ---------------------------------------- -- line 279 ---------------------------------------- . flat.extend(attr.tokens().to_tokenstream().0.clone().iter().cloned()); . } . flat.extend(target_tokens); . flat.into_iter() . } . }) . .collect(); . TokenStream::new(trees) 7,422 ( 0.00%) } . } . . /// Stores the tokens for an attribute target, along . /// with its attributes. . /// . /// This is constructed during parsing when we need to capture . /// tokens. . /// -- line 295 ---------------------------------------- -- 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); . 1,254,526 ( 0.01%) #[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 { 1,463,455 ( 0.01%) TokenStream::new(vec![(tree, Spacing::Alone)]) . } . } . . impl From for TreeAndSpacing { . fn from(tree: TokenTree) -> TreeAndSpacing { 186,473 ( 0.00%) (tree, Spacing::Alone) . } . } . . impl iter::FromIterator for TokenStream { 5,482 ( 0.00%) fn from_iter>(iter: I) -> Self { 5,758 ( 0.00%) TokenStream::new(iter.into_iter().map(Into::into).collect::>()) 8,223 ( 0.00%) } . } . . impl Eq for TokenStream {} . . impl PartialEq for TokenStream { . fn eq(&self, other: &TokenStream) -> bool { . self.trees().eq(other.trees()) . } -- line 400 ---------------------------------------- -- line 401 ---------------------------------------- . } . . impl TokenStream { . pub fn new(streams: Vec) -> TokenStream { . TokenStream(Lrc::new(streams)) . } . . pub fn is_empty(&self) -> bool { 35,779 ( 0.00%) self.0.is_empty() 35,779 ( 0.00%) } . . pub fn len(&self) -> usize { 1,322,284 ( 0.01%) self.0.len() 7,924 ( 0.00%) } . 798,624 ( 0.00%) pub fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream { 399,306 ( 0.00%) 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 . // using `make_mut()` on the first stream, and in practice this . // doesn't cause cloning 99.9% of the time. . // -- line 425 ---------------------------------------- -- line 430 ---------------------------------------- . . // Determine how much the first stream will be extended. . // Needed to avoid quadratic blow up from on-the-fly . // reallocations (#57735). . let num_appends = streams.iter().skip(1).map(|ts| ts.len()).sum(); . . // Get the first stream. If it's `None`, create an empty . // stream. 198,088 ( 0.00%) let mut iter = streams.drain(..); 198,088 ( 0.00%) let mut first_stream_lrc = iter.next().unwrap().0; . . // Append the elements to the first stream, after reserving . // space for them. 99,044 ( 0.00%) let first_vec_mut = Lrc::make_mut(&mut first_stream_lrc); . first_vec_mut.reserve(num_appends); 1,658,649 ( 0.01%) for stream in iter { . first_vec_mut.extend(stream.0.iter().cloned()); . } . . // Create the final `TokenStream`. 198,088 ( 0.00%) TokenStream(first_stream_lrc) . } . } 898,452 ( 0.01%) } . . pub fn trees(&self) -> Cursor { 97,437 ( 0.00%) self.clone().into_trees() 194,874 ( 0.00%) } . 92,504 ( 0.00%) pub fn into_trees(self) -> Cursor { . Cursor::new(self) 185,008 ( 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 { 803 ( 0.00%) TokenStream(Lrc::new( . self.0 . .iter() . .enumerate() 10,314 ( 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]>); . . impl TokenStreamBuilder { 99,828 ( 0.00%) pub fn new() -> TokenStreamBuilder { 99,828 ( 0.00%) TokenStreamBuilder(SmallVec::new()) 99,828 ( 0.00%) } . 4,389,048 ( 0.03%) pub fn push>(&mut self, stream: T) { 487,672 ( 0.00%) let mut stream = stream.into(); . . // If `self` is not empty and the last tree within the last stream is a . // token tree marked with `Joint`... 1,463,016 ( 0.01%) if let Some(TokenStream(ref mut last_stream_lrc)) = self.0.last_mut() { 2,311,458 ( 0.01%) if let Some((TokenTree::Token(last_token), Spacing::Joint)) = last_stream_lrc.last() { . // ...and `stream` is not empty and the first tree within it is . // a token tree... . let TokenStream(ref mut stream_lrc) = stream; 231,364 ( 0.00%) if let Some((TokenTree::Token(token), spacing)) = stream_lrc.first() { . // ...and the two tokens can be glued together... 231,364 ( 0.00%) if let Some(glued_tok) = last_token.glue(&token) { . // ...then do so, by overwriting the last token . // tree in `self` and removing the first token tree . // from `stream`. This requires using `make_mut()` . // on the last stream in `self` and on `stream`, . // and in practice this doesn't cause cloning 99.9% . // of the time. . . // Overwrite the last token tree with the merged . // token. 33,052 ( 0.00%) let last_vec_mut = Lrc::make_mut(last_stream_lrc); 760,196 ( 0.00%) *last_vec_mut.last_mut().unwrap() = (TokenTree::Token(glued_tok), *spacing); . . // Remove the first token tree from `stream`. (This . // is almost always the only tree in `stream`.) 33,052 ( 0.00%) let stream_vec_mut = Lrc::make_mut(stream_lrc); 198,312 ( 0.00%) stream_vec_mut.remove(0); . . // Don't push `stream` if it's empty -- that could . // block subsequent token gluing, by getting . // between two token trees that should be glued . // together. 99,156 ( 0.00%) if !stream.is_empty() { . self.0.push(stream); . } . return; . } . } . } . } . self.0.push(stream); 3,901,376 ( 0.02%) } . 99,828 ( 0.00%) pub fn build(self) -> TokenStream { 598,968 ( 0.00%) TokenStream::from_streams(self.0) 199,656 ( 0.00%) } . } . . /// By-reference iterator over a [`TokenStream`]. . #[derive(Clone)] . pub struct CursorRef<'t> { . stream: &'t TokenStream, . index: usize, . } -- line 550 ---------------------------------------- -- line 572 ---------------------------------------- . pub struct Cursor { . pub stream: TokenStream, . index: usize, . } . . impl Iterator for Cursor { . type Item = TokenTree; . 663,999 ( 0.00%) fn next(&mut self) -> Option { 1,047,580 ( 0.01%) self.next_with_spacing().map(|(tree, _)| tree) 885,332 ( 0.01%) } . } . . impl Cursor { . fn new(stream: TokenStream) -> Self { . Cursor { stream, index: 0 } . } . 3,651,540 ( 0.02%) pub fn next_with_spacing(&mut self) -> Option { 2,854,923 ( 0.02%) if self.index < self.stream.len() { 1,367,088 ( 0.01%) self.index += 1; 3,860,577 ( 0.02%) Some(self.stream.0[self.index - 1].clone()) . } else { 357,594 ( 0.00%) None . } 4,381,848 ( 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; . } . 340,576 ( 0.00%) pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> { 681,152 ( 0.00%) self.stream.0[self.index..].get(n).map(|(tree, _)| tree) 681,152 ( 0.00%) } . } . 548,211 ( 0.00%) #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub struct DelimSpan { . pub open: Span, . pub close: Span, . } . . impl DelimSpan { 77,468 ( 0.00%) pub fn from_single(sp: Span) -> Self { . DelimSpan { open: sp, close: sp } 154,936 ( 0.00%) } . 10,316 ( 0.00%) pub fn from_pair(open: Span, close: Span) -> Self { . DelimSpan { open, close } 5,158 ( 0.00%) } . . pub fn dummy() -> Self { . Self::from_single(DUMMY_SP) 31,815 ( 0.00%) } . 79,040 ( 0.00%) pub fn entire(self) -> Span { . self.open.with_hi(self.close.hi()) 59,280 ( 0.00%) } . } 2,661,772 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs -------------------------------------------------------------------------------- Ir -- line 111 ---------------------------------------- . const EMPTY: u8 = 0b1111_1111; . . /// Control byte value for a deleted bucket. . const DELETED: u8 = 0b1000_0000; . . /// Checks whether a control byte represents a full bucket (top bit is clear). . #[inline] . fn is_full(ctrl: u8) -> bool { 5,883,337 ( 0.04%) 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)); 510,349 ( 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::()); 121,748,286 ( 0.73%) 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" . ); . 661,000 ( 0.00%) self.stride += Group::WIDTH; 661,000 ( 0.00%) self.pos += self.stride; 575,836 ( 0.00%) self.pos &= bucket_mask; . } . } . . /// Returns the number of buckets needed to hold the given number of items, . /// taking the maximum load factor into account. . /// . /// Returns `None` if an overflow occurs. . // Workaround for emscripten bug emscripten-core/emscripten-fastcomp#258 . #[cfg_attr(target_os = "emscripten", inline(never))] . #[cfg_attr(not(target_os = "emscripten"), inline)] . fn capacity_to_buckets(cap: usize) -> Option { . debug_assert_ne!(cap, 0); . . // For small tables we require at least 1 empty bucket so that lookups are . // guaranteed to terminate if an element doesn't exist in the table. 622,908 ( 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. 1,369,130 ( 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. 225,768 ( 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 { 1,535,480 ( 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. 287,164 ( 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 = 1,333,925 ( 0.01%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 1,744,068 ( 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 { 1,968 ( 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 { 5,835 ( 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 { 3,815 ( 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 { 43,360 ( 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")] 67,447 ( 0.00%) pub unsafe fn erase_no_drop(&mut self, item: &Bucket) { 67,447 ( 0.00%) let index = self.bucket_index(item); . self.table.erase(index); 134,894 ( 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. 35,330 ( 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 { 99,564 ( 0.00%) self.erase_no_drop(&item); 1,210 ( 0.00%) item.read() . } . . /// Finds and removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] 2,377,630 ( 0.01%) pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option { . // Avoid `Option::map` because it bloats LLVM IR. 7,718 ( 0.00%) match self.find(hash, eq) { 26,743 ( 0.00%) Some(bucket) => Some(unsafe { self.remove(bucket) }), 599,088 ( 0.00%) None => None, . } 3,488,421 ( 0.02%) } . . /// 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) { 81,766 ( 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) { 1,390,878 ( 0.01%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 1,040,903 ( 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)] 2,490,540 ( 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 . }, . ) . } 1,821,016 ( 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)] 8,831,936 ( 0.05%) 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. 33,037 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 5,524,410 ( 0.03%) if unlikely(self.table.growth_left == 0 && special_is_empty(old_ctrl)) { . self.reserve(1, hasher); . index = self.table.find_insert_slot(hash); . } . . self.table.record_item_insert_at(index, old_ctrl, hash); . . let bucket = self.bucket(index); 4 ( 0.00%) bucket.write(value); . bucket . } 6,496,761 ( 0.04%) } . . /// 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)] 809,232 ( 0.00%) pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T { 166 ( 0.00%) unsafe { self.insert(hash, value, hasher).as_mut() } 606,924 ( 0.00%) } . . /// Inserts a new element into the table, without growing the table. . /// . /// There must be enough space in the table to insert the new element. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] . #[cfg(any(feature = "raw", feature = "rustc-internal-api"))] 6,456 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 1,452,039 ( 0.01%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 29,579 ( 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. 2,937,211 ( 0.02%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 2,357,035 ( 0.01%) self.table.items += 1; . bucket 12,803 ( 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] 179,109 ( 0.00%) pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { 36,168 ( 0.00%) let result = self.table.find_inner(hash, &mut |index| unsafe { 173,105 ( 0.00%) eq(self.bucket(index).as_ref()) 11,466 ( 0.00%) }); . . // Avoid `Option::map` because it bloats LLVM IR. . match result { 4,663 ( 0.00%) Some(index) => Some(unsafe { self.bucket(index) }), . None => None, . } 202,216 ( 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. 103,636 ( 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] 1,946 ( 0.00%) pub fn get_mut(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&mut T> { . // Avoid `Option::map` because it bloats LLVM IR. 99,520 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_mut() }), . None => None, . } 2,224 ( 0.00%) } . . /// Attempts to get mutable references to `N` entries in the table at once. . /// . /// Returns an array of length `N` with the results of each query. . /// . /// At most one mutable reference will be returned to any entry. `None` will be returned if any . /// of the hashes are duplicates. `None` will be returned if the hash is not found. . /// -- line 859 ---------------------------------------- -- line 920 ---------------------------------------- . #[inline] . pub fn len(&self) -> usize { . self.table.items . } . . /// Returns `true` if the table contains no elements. . #[inline] . pub fn is_empty(&self) -> bool { 3,790,581 ( 0.02%) self.len() == 0 . } . . /// Returns the number of buckets in the table. . #[inline] . pub fn buckets(&self) -> usize { . self.table.bucket_mask + 1 . } . -- line 936 ---------------------------------------- -- line 938 ---------------------------------------- . /// the caller to ensure that the `RawTable` outlives the `RawIter`. . /// Because we cannot make the `next` method unsafe on the `RawIter` . /// struct, we have to make the `iter` method unsafe. . #[inline] . pub unsafe fn iter(&self) -> RawIter { . let data = Bucket::from_base_index(self.data_end(), 0); . RawIter { . iter: RawIterRange::new(self.table.ctrl.as_ptr(), data, self.table.buckets()), 527,101 ( 0.00%) items: self.table.items, . } . } . . /// Returns an iterator over occupied buckets that could match a given hash. . /// . /// `RawTable` only stores 7 bits of the hash value, so this iterator may . /// return items that have a hash value different than the one provided. You . /// should always validate the returned values before using them. -- line 954 ---------------------------------------- -- line 995 ---------------------------------------- . /// Iteration starts at the provided iterator's current location. . /// . /// It is up to the caller to ensure that the iterator is valid for this . /// `RawTable` and covers all items that remain in the table. . pub unsafe fn into_iter_from(self, iter: RawIter) -> RawIntoIter { . debug_assert_eq!(iter.len(), self.len()); . . let alloc = self.table.alloc.clone(); 58,932 ( 0.00%) let allocation = self.into_allocation(); 44,199 ( 0.00%) RawIntoIter { 73,665 ( 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)> { 27,907 ( 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(( 4,839 ( 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 { 3,267,471 ( 0.02%) 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)] 2,499,205 ( 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()); . } . 544,634 ( 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)); 1,369,848 ( 0.01%) Ok(Self { . ctrl, 540,525 ( 0.00%) bucket_mask: buckets - 1, . items: 0, . growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 1,818,342 ( 0.01%) } . . #[inline] 138,800 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 36,938 ( 0.00%) if capacity == 0 { 24,117 ( 0.00%) Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = . capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 1,133,251 ( 0.01%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; . result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 78,293 ( 0.00%) Ok(result) . } . } 138,800 ( 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] 503,976 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { . let index = self.find_insert_slot(hash); 503,976 ( 0.00%) let old_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . (index, old_ctrl) 1,007,952 ( 0.01%) } . . /// Searches for an empty or deleted bucket which is suitable for inserting . /// a new element. . /// . /// There must be at least 1 empty bucket in the table. . #[inline] . fn find_insert_slot(&self, hash: u64) -> usize { . let mut probe_seq = self.probe_seq(hash); . loop { . unsafe { . let group = Group::load(self.ctrl(probe_seq.pos)); 3,833,915 ( 0.02%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 11,280,307 ( 0.07%) 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). 5,139,049 ( 0.03%) 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); . 337,096 ( 0.00%) loop { . let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 14,643,027 ( 0.09%) for bit in group.match_byte(h2_hash) { 30,327,510 ( 0.18%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 20,147,495 ( 0.12%) if likely(eq(index)) { . return Some(index); . } . } . 3,827,749 ( 0.02%) 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(); 13,121,960 ( 0.08%) 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 { 79,974,612 ( 0.48%) 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) { 6,904,243 ( 0.04%) self.growth_left -= special_is_empty(old_ctrl) as usize; . self.set_ctrl_h2(index, hash); 5,523,364 ( 0.03%) 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] | . // --------------------------------------------- 10,599,681 ( 0.06%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 3,531,435 ( 0.02%) *self.ctrl(index) = ctrl; 3,532,309 ( 0.02%) *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 { 1,617,201 ( 0.01%) self.bucket_mask + 1 . } . . #[inline] . fn num_ctrl_bytes(&self) -> usize { 1,253,586 ( 0.01%) self.bucket_mask + 1 + Group::WIDTH . } . . #[inline] . fn is_empty_singleton(&self) -> bool { 6,012,416 ( 0.04%) 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. 20,649 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( . self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 656,647 ( 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_| { 305,288 ( 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. 610,580 ( 0.00%) let new_items = match self.items.checked_add(additional) { . Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 610,576 ( 0.00%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 1,277,551 ( 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( 305,288 ( 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> { 52,821 ( 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() { 2,125,129 ( 0.01%) if !is_full(*self.ctrl(i)) { . continue; . } . . // This may panic. . let hash = hasher(self, i); . . // We can use a simpler version of insert() here since: . // - there are no DELETED entries. -- line 1444 ---------------------------------------- -- line 1454 ---------------------------------------- . } . . // We successfully copied all elements without panicking. Now replace . // self with the new table. The old table will have its memory freed but . // the items will not be dropped (since they have been moved into the . // new table). . mem::swap(self, &mut new_table); . 305,288 ( 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( 205,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) { 36,214 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 57,749 ( 0.00%) self.items = 0; 36,233 ( 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))); 400,773 ( 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. 1,603,092 ( 0.01%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 2,000,100 ( 0.01%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 1,603,092 ( 0.01%) self.items -= 1; . } . } . . impl Clone for RawTable { 15,576 ( 0.00%) fn clone(&self) -> Self { 2,718 ( 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) . } . } 17,523 ( 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; 1,526 ( 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)] 3,401,882 ( 0.02%) fn drop(&mut self) { 2,598,180 ( 0.02%) if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); . self.free_buckets(); . } . } 3,626,234 ( 0.02%) } . } . #[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)] 58,932 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 73,665 ( 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 { 2,236,881 ( 0.01%) if let Some(index) = self.current_group.lowest_set_bit() { 176,619 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 319,872 ( 0.00%) return Some(self.data.next_n(index)); . } . 1,233,112 ( 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). 19,216 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); 24,673 ( 0.00%) self.data = self.data.next_n(Group::WIDTH); 25,552 ( 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) { 11,328 ( 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)] 247,963 ( 0.00%) fn next(&mut self) -> Option> { 2,672,888 ( 0.02%) if let Some(b) = self.iter.next() { 3,462,820 ( 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 . } 495,926 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { . (self.items, Some(self.items)) . } . } . . impl ExactSizeIterator for RawIter {} -- line 2151 ---------------------------------------- -- line 2177 ---------------------------------------- . T: Sync, . A: Sync, . { . } . . #[cfg(feature = "nightly")] . unsafe impl<#[may_dangle] T, A: Allocator + Clone> Drop for RawIntoIter { . #[cfg_attr(feature = "inline-more", inline)] 23,498 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 130,755 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 646 ( 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)] 6,568 ( 0.00%) fn next(&mut self) -> Option { 921 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 16,076 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 4 ( 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)] 6,488 ( 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. 811 ( 0.00%) self.orig_table . .as_ptr() . .copy_from_nonoverlapping(&*self.table, 1); . } 6,488 ( 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 ---------------------------------------- 51,341,333 ( 0.31%) -------------------------------------------------------------------------------- -- 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, . ) { 36,609 ( 0.00%) if let Some((file, file_idx)) = new_file_and_idx { 11,019 ( 0.00%) self.file = file; 13,026 ( 0.00%) self.file_index = file_idx; . } . 27,568 ( 0.00%) let line_index = self.file.lookup_line(pos).unwrap(); . let line_bounds = self.file.line_bounds(line_index); 71,166 ( 0.00%) self.line_number = line_index + 1; 107,738 ( 0.00%) self.line = line_bounds; . self.touch(time_stamp); . } . . #[inline] . fn touch(&mut self, time_stamp: usize) { 656,785 ( 0.00%) 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> { 22,746 ( 0.00%) pub fn new(source_map: &'sm SourceMap) -> CachingSourceMapView<'sm> { . let files = source_map.files(); 11,373 ( 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, . }; . 56,865 ( 0.00%) CachingSourceMapView { . source_map, 79,611 ( 0.00%) line_cache: [entry.clone(), entry.clone(), entry], . time_stamp: 0, . } 45,492 ( 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)) . } . 2,412,774 ( 0.01%) pub fn span_data_to_lines_and_cols( . &mut self, . span_data: &SpanData, . ) -> Option<(Lrc, usize, BytePos, usize, BytePos)> { 1,378,728 ( 0.01%) self.time_stamp += 1; . . // Check if lo and hi are in the cached lines. 344,682 ( 0.00%) let lo_cache_idx = self.cache_entry_index(span_data.lo); 344,682 ( 0.00%) let hi_cache_idx = self.cache_entry_index(span_data.hi); . 625,054 ( 0.00%) 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 = { 624,206 ( 0.00%) let lo = &self.line_cache[lo_cache_idx as usize]; . let hi = &self.line_cache[hi_cache_idx as usize]; . 1,872,618 ( 0.01%) if lo.file_index != hi.file_index { . return None; . } . . ( 624,206 ( 0.00%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 312,103 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . ) . }; . 312,103 ( 0.00%) self.line_cache[lo_cache_idx as usize].touch(self.time_stamp); 312,103 ( 0.00%) self.line_cache[hi_cache_idx as usize].touch(self.time_stamp); . 1,248,412 ( 0.01%) return Some(result); . } . . // No cache hit or cache hit for only one of span lo and hi. 64,310 ( 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. 253,916 ( 0.00%) let new_file_and_idx = if !file_contains(&self.line_cache[oldest].file, span_data.lo) { 25,055 ( 0.00%) let new_file_and_idx = self.file_for_position(span_data.lo)?; 30,066 ( 0.00%) if !file_contains(&new_file_and_idx.0, span_data.hi) { . return None; . } . 20,044 ( 0.00%) Some(new_file_and_idx) . } else { . let file = &self.line_cache[oldest].file; 82,704 ( 0.00%) if !file_contains(&file, span_data.hi) { . return None; . } . 82,704 ( 0.00%) None . }; . . // Update the cache entries. 162,895 ( 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); . 90,420 ( 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); 848 ( 0.00%) let hi = &mut self.line_cache[hi_cache_idx as usize]; 1,272 ( 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]; 2,015 ( 0.00%) hi.update(new_file_and_idx, span_data.hi, self.time_stamp); 4,030 ( 0.00%) let lo = &mut self.line_cache[lo_cache_idx as usize]; 8,060 ( 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. 65,158 ( 0.00%) assert!(span_data.lo >= lo.line.start); 32,579 ( 0.00%) assert!(span_data.lo <= lo.line.end); 65,158 ( 0.00%) assert!(span_data.hi >= hi.line.start); 32,579 ( 0.00%) assert!(span_data.hi <= hi.line.end); 162,895 ( 0.00%) assert!(lo.file.contains(span_data.lo)); 97,737 ( 0.00%) assert!(lo.file.contains(span_data.hi)); 97,737 ( 0.00%) assert_eq!(lo.file_index, hi.file_index); . 97,737 ( 0.00%) Some(( 32,579 ( 0.00%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 32,579 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . )) 3,102,138 ( 0.02%) } . . fn cache_entry_index(&self, pos: BytePos) -> isize { . for (idx, cache_entry) in self.line_cache.iter().enumerate() { 3,182,072 ( 0.02%) 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() { 180,840 ( 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() { 32,027 ( 0.00%) if idx != avoid_idx 17,581 ( 0.00%) && self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp . { . oldest = idx; . } . } . . oldest . } . 25,055 ( 0.00%) fn file_for_position(&self, pos: BytePos) -> Option<(Lrc, usize)> { 5,011 ( 0.00%) if !self.source_map.files().is_empty() { 10,022 ( 0.00%) let file_idx = self.source_map.lookup_source_file_idx(pos); . let file = &self.source_map.files()[file_idx]; . 40,088 ( 0.00%) if file_contains(file, pos) { . return Some((file.clone(), file_idx)); . } . } . . None 25,055 ( 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 ---------------------------------------- 4,082,385 ( 0.02%) -------------------------------------------------------------------------------- -- 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 . // . 21,704,790 ( 0.13%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 16,278,591 ( 0.10%) 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. 1,069,472 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 1,604,208 ( 0.01%) 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) { 5,692,879 ( 0.03%) libc::free(ptr as *mut libc::c_void) . } . . #[inline] . unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { 1,956,816 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 3,913,632 ( 0.02%) libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8 . } else { . realloc_fallback(self, ptr, layout, new_size) . } . } . } . . cfg_if::cfg_if! { . if #[cfg(any( -- line 56 ---------------------------------------- -- line 84 ---------------------------------------- . } else if #[cfg(target_os = "wasi")] { . #[inline] . unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { . libc::aligned_alloc(layout.align(), layout.size()) as *mut u8 . } . } else { . #[inline] . unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { 1 ( 0.00%) let mut out = ptr::null_mut(); . // posix_memalign requires that the alignment be a multiple of `sizeof(void*)`. . // Since these are all powers of 2, we can just use max. . let align = layout.align().max(crate::mem::size_of::()); 2 ( 0.00%) let ret = libc::posix_memalign(&mut out, align, layout.size()); 2 ( 0.00%) if ret != 0 { ptr::null_mut() } else { out as *mut u8 } . } . } . } 1 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/remove.rs -------------------------------------------------------------------------------- Ir . use super::map::MIN_LEN; . use super::node::{marker, ForceResult::*, Handle, LeftOrRight::*, NodeRef}; . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::LeafOrInternal>, marker::KV> { . /// Removes a key-value pair from the tree, and returns that pair, as well as . /// the leaf edge corresponding to that former pair. It's possible this empties . /// a root node that is internal, which the caller should pop from the map . /// holding the tree. The caller should also decrement the map's length. 5,198,831 ( 0.03%) pub fn remove_kv_tracking( . self, . handle_emptied_internal_root: F, . ) -> ((K, V), Handle, K, V, marker::Leaf>, marker::Edge>) { 4,158,848 ( 0.02%) match self.force() { 7,265,720 ( 0.04%) Leaf(node) => node.remove_leaf_kv(handle_emptied_internal_root), . Internal(node) => node.remove_internal_kv(handle_emptied_internal_root), . } 6,238,543 ( 0.04%) } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::KV> { 7,277,984 ( 0.04%) fn remove_leaf_kv( . self, . handle_emptied_internal_root: F, . ) -> ((K, V), Handle, K, V, marker::Leaf>, marker::Edge>) { 4,911,535 ( 0.03%) let (old_kv, mut pos) = self.remove(); . let len = pos.reborrow().into_node().len(); 2,079,424 ( 0.01%) if len < MIN_LEN { . let idx = pos.idx(); . // We have to temporarily forget the child type, because there is no . // distinct node type for the immediate parents of a leaf. . let new_pos = match pos.into_node().forget_type().choose_parent_kv() { . Ok(Left(left_parent_kv)) => { . debug_assert!(left_parent_kv.right_child_len() == MIN_LEN - 1); 120,349 ( 0.00%) if left_parent_kv.can_merge() { 1,658,522 ( 0.01%) left_parent_kv.merge_tracking_child_edge(Right(idx)) . } else { . debug_assert!(left_parent_kv.left_child_len() > MIN_LEN); 13,749 ( 0.00%) left_parent_kv.steal_left(idx) . } . } . Ok(Right(right_parent_kv)) => { . debug_assert!(right_parent_kv.left_child_len() == MIN_LEN - 1); 3,816 ( 0.00%) if right_parent_kv.can_merge() { 35,677 ( 0.00%) right_parent_kv.merge_tracking_child_edge(Left(idx)) . } else { . debug_assert!(right_parent_kv.right_child_len() > MIN_LEN); 8,919 ( 0.00%) right_parent_kv.steal_right(idx) . } . } . Err(pos) => unsafe { Handle::new_edge(pos, idx) }, . }; . // SAFETY: `new_pos` is the leaf we started from or a sibling. 1,403,714 ( 0.01%) pos = unsafe { new_pos.cast_to_leaf_unchecked() }; . . // Only if we merged, the parent (if any) has shrunk, but skipping . // the following step otherwise does not pay off in benchmarks. . // . // SAFETY: We won't destroy or rearrange the leaf where `pos` is at . // by handling its parent recursively; at worst we will destroy or . // rearrange the parent through the grandparent, thus change the . // link to the parent inside the leaf. . if let Ok(parent) = unsafe { pos.reborrow_mut() }.into_node().ascend() { 40,628 ( 0.00%) if !parent.into_node().forget_type().fix_node_and_affected_ancestors() { . handle_emptied_internal_root(); . } . } . } 8,561,652 ( 0.05%) (old_kv, pos) 8,317,696 ( 0.05%) } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::KV> { . fn remove_internal_kv( . self, . handle_emptied_internal_root: F, . ) -> ((K, V), Handle, K, V, marker::Leaf>, marker::Edge>) { . // Remove an adjacent KV from its leaf and then put it back in place of . // the element we were asked to remove. Prefer the left adjacent KV, . // for the reasons listed in `choose_parent_kv`. . let left_leaf_kv = self.left_edge().descend().last_leaf_edge().left_kv(); . let left_leaf_kv = unsafe { left_leaf_kv.ok().unwrap_unchecked() }; 25,316 ( 0.00%) let (left_kv, left_hole) = left_leaf_kv.remove_leaf_kv(handle_emptied_internal_root); . . // The internal node may have been stolen from or merged. Go back right . // to find where the original KV ended up. . let mut internal = unsafe { left_hole.next_kv().ok().unwrap_unchecked() }; 1,265 ( 0.00%) let old_kv = internal.replace_kv(left_kv.0, left_kv.1); . let pos = internal.next_leaf_edge(); 15,097 ( 0.00%) (old_kv, pos) . } . } 5,505,700 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/buffer.rs -------------------------------------------------------------------------------- Ir -- line 21 ---------------------------------------- . fn default() -> Self { . Self::from(vec![]) . } . } . . impl Deref for Buffer { . type Target = [T]; . fn deref(&self) -> &[T] { 5,783,797 ( 0.03%) unsafe { slice::from_raw_parts(self.data as *const T, self.len) } . } . } . . impl DerefMut for Buffer { . fn deref_mut(&mut self) -> &mut [T] { . unsafe { slice::from_raw_parts_mut(self.data, self.len) } . } . } . . impl Buffer { . pub(super) fn new() -> Self { . Self::default() . } . . pub(super) fn clear(&mut self) { 12,118,243 ( 0.07%) self.len = 0; . } . . pub(super) fn take(&mut self) -> Self { . mem::take(self) . } . . // We have the array method separate from extending from a slice. This is . // because in the case of small arrays, codegen can be more efficient . // (avoiding a memmove call). With extend_from_slice, LLVM at least . // currently is not able to make that optimization. . pub(super) fn extend_from_array(&mut self, xs: &[T; N]) { 26,412,837 ( 0.16%) if xs.len() > (self.capacity - self.len) { . let b = self.take(); 2,730 ( 0.00%) *self = (b.reserve)(b, xs.len()); . } . unsafe { 4,516,845 ( 0.03%) xs.as_ptr().copy_to_nonoverlapping(self.data.add(self.len), xs.len()); 13,652,015 ( 0.08%) self.len += xs.len(); . } . } . 611,220 ( 0.00%) pub(super) fn extend_from_slice(&mut self, xs: &[T]) { 1,079,994 ( 0.01%) if xs.len() > (self.capacity - self.len) { . let b = self.take(); 5,460 ( 0.00%) *self = (b.reserve)(b, xs.len()); . } . unsafe { 260 ( 0.00%) xs.as_ptr().copy_to_nonoverlapping(self.data.add(self.len), xs.len()); 539,997 ( 0.00%) self.len += xs.len(); . } 713,090 ( 0.00%) } . . pub(super) fn push(&mut self, v: T) { . // The code here is taken from Vec::push, and we know that reserve() . // will panic if we're exceeding isize::MAX bytes and so there's no need . // to check for overflow. 29,656,626 ( 0.18%) if self.len == self.capacity { . let b = self.take(); . *self = (b.reserve)(b, 1); . } . unsafe { 19,449,251 ( 0.12%) *self.data.add(self.len) = v; 17,387,257 ( 0.10%) self.len += 1; . } . } . } . . impl Write for Buffer { . fn write(&mut self, xs: &[u8]) -> io::Result { . self.extend_from_slice(xs); . Ok(xs.len()) . } . 468,774 ( 0.00%) fn write_all(&mut self, xs: &[u8]) -> io::Result<()> { 305,610 ( 0.00%) self.extend_from_slice(xs); . Ok(()) 703,161 ( 0.00%) } . . fn flush(&mut self) -> io::Result<()> { . Ok(()) . } . } . . impl Drop for Buffer { . fn drop(&mut self) { . let b = self.take(); 30,333,744 ( 0.18%) (b.drop)(b); . } . } . . impl From> for Buffer { . fn from(mut v: Vec) -> Self { . let (data, len, capacity) = (v.as_mut_ptr(), v.len(), v.capacity()); . mem::forget(v); . -- line 120 ---------------------------------------- -- line 123 ---------------------------------------- . fn to_vec(b: Buffer) -> Vec { . unsafe { . let Buffer { data, len, capacity, .. } = b; . mem::forget(b); . Vec::from_raw_parts(data, len, capacity) . } . } . 1,560 ( 0.00%) extern "C" fn reserve(b: Buffer, additional: usize) -> Buffer { 1,170 ( 0.00%) let mut v = to_vec(b); . v.reserve(additional); 1,170 ( 0.00%) Buffer::from(v) 1,560 ( 0.00%) } . . extern "C" fn drop(b: Buffer) { 2,527,877 ( 0.02%) mem::drop(to_vec(b)); 2,527,747 ( 0.02%) } . 3,250 ( 0.00%) Buffer { data, len, capacity, reserve, drop } . } . } 12,208,635 ( 0.07%) -------------------------------------------------------------------------------- -- 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}; . 113,948 ( 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); . } . } . } . }; . } . 114,796 ( 0.00%) #[derive(Clone)] . pub struct Parser<'a> { 4,402 ( 0.00%) pub sess: &'a ParseSess, . /// The current token. 3,294 ( 0.00%) pub token: Token, . /// The spacing for the current token 1,945 ( 0.00%) pub token_spacing: Spacing, . /// The previous token. 4,941 ( 0.00%) pub prev_token: Token, 2,243 ( 0.00%) pub capture_cfg: bool, 4,784 ( 0.00%) restrictions: Restrictions, 3,890 ( 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, 3,890 ( 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. 3,890 ( 0.00%) unmatched_angle_bracket_count: u32, 5,835 ( 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. 1,945 ( 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` 1,945 ( 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, . } . 8,590 ( 0.00%) #[derive(Clone)] . struct CaptureState { 7,780 ( 0.00%) capturing: Capturing, 1,945 ( 0.00%) replace_ranges: Vec, . inner_attr_ranges: FxHashMap, . } . . impl<'a> Drop for Parser<'a> { . fn drop(&mut self) { 43,419 ( 0.00%) emit_unclosed_delims(&mut self.unclosed_delims, &self.sess); . } . } . 985,004 ( 0.01%) #[derive(Clone)] . struct TokenCursor { . frame: TokenCursorFrame, 227,718 ( 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. 72,510 ( 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, . } . 450,492 ( 0.00%) #[derive(Clone)] . struct TokenCursorFrame { 182,997 ( 0.00%) delim: token::DelimToken, . span: DelimSpan, . open_delim: bool, 365,994 ( 0.00%) tree_cursor: tokenstream::Cursor, . close_delim: bool, . } . . impl TokenCursorFrame { . fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self { 48,745 ( 0.00%) TokenCursorFrame { . delim, . span, . open_delim: false, 94,938 ( 0.00%) tree_cursor: tts.into_trees(), . close_delim: false, . } . } . } . . impl TokenCursor { 6,539,100 ( 0.04%) fn next(&mut self) -> (Token, Spacing) { . loop { 3,248,107 ( 0.02%) let (tree, spacing) = if !self.frame.open_delim { 75,302 ( 0.00%) self.frame.open_delim = true; 376,510 ( 0.00%) TokenTree::open_tt(self.frame.span, self.frame.delim).into() 6,311,858 ( 0.04%) } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() { . tree 317,588 ( 0.00%) } else if !self.frame.close_delim { 74,315 ( 0.00%) self.frame.close_delim = true; 371,575 ( 0.00%) TokenTree::close_tt(self.frame.span, self.frame.delim).into() 147,662 ( 0.00%) } else if let Some(frame) = self.stack.pop() { 959,803 ( 0.01%) self.frame = frame; . continue; . } else { 191,664 ( 0.00%) (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone) . }; . 1,240,178 ( 0.01%) match tree { . TokenTree::Token(token) => { 4,359,400 ( 0.03%) return (token, spacing); . } . TokenTree::Delimited(sp, delim, tts) => { . let frame = TokenCursorFrame::new(sp, delim, tts); . self.stack.push(mem::replace(&mut self.frame, frame)); . } . } . } 4,359,400 ( 0.03%) } . 71,400 ( 0.00%) fn next_desugared(&mut self) -> (Token, Spacing) { 21,696 ( 0.00%) let (data, attr_style, sp) = match self.next() { 414 ( 0.00%) (Token { kind: token::DocComment(_, attr_style, data), span }, _) => { . (data, attr_style, span) . } 35,010 ( 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; 32,864 ( 0.00%) for ch in data.as_str().chars() { . count = match ch { . '"' => 1, 10 ( 0.00%) '#' if count > 0 => count + 1, . _ => 0, . }; . num_of_hashes = cmp::max(num_of_hashes, count); . } . 552 ( 0.00%) let delim_span = DelimSpan::from_single(sp); 690 ( 0.00%) let body = TokenTree::Delimited( . delim_span, . token::Bracket, 1,656 ( 0.00%) [ 966 ( 0.00%) TokenTree::token(token::Ident(sym::doc, false), sp), 552 ( 0.00%) TokenTree::token(token::Eq, sp), 1,104 ( 0.00%) TokenTree::token(TokenKind::lit(token::StrRaw(num_of_hashes), data, None), sp), . ] . .iter() . .cloned() . .collect::(), 138 ( 0.00%) ); . . self.stack.push(mem::replace( . &mut self.frame, . TokenCursorFrame::new( . delim_span, . token::NoDelim, 138 ( 0.00%) if attr_style == AttrStyle::Inner { . [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body] . .iter() . .cloned() . .collect::() . } else { 1,656 ( 0.00%) [TokenTree::token(token::Pound, sp), body] . .iter() . .cloned() . .collect::() . }, . ), . )); . 414 ( 0.00%) self.next() 64,260 ( 0.00%) } . } . 431,975 ( 0.00%) #[derive(Debug, Clone, PartialEq)] . enum TokenType { 345,607 ( 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 { 51 ( 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> { 33,542 ( 0.00%) Some(match token.kind { 67,084 ( 0.00%) _ if token.is_special_ident() => "reserved identifier", 67,084 ( 0.00%) _ if token.is_used_keyword() => "keyword", 67,084 ( 0.00%) _ if token.is_unused_keyword() => "reserved keyword", . token::DocComment(..) => "doc comment", . _ => return None, . }) . } . 117,397 ( 0.00%) pub(super) fn token_descr(token: &Token) -> String { 33,542 ( 0.00%) let token_str = pprust::token_to_string(token); . match token_descr_opt(token) { . Some(prefix) => format!("{} `{}`", prefix, token_str), 117,397 ( 0.00%) _ => format!("`{}`", token_str), . } 83,855 ( 0.00%) } . . impl<'a> Parser<'a> { 136,486 ( 0.00%) pub fn new( . sess: &'a ParseSess, . tokens: TokenStream, . desugar_doc_comments: bool, . subparser_name: Option<&'static str>, . ) -> Self { 9,749 ( 0.00%) let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens); 19,498 ( 0.00%) start_frame.open_delim = true; . start_frame.close_delim = true; . 302,219 ( 0.00%) let mut parser = Parser { . sess, 9,749 ( 0.00%) token: Token::dummy(), . token_spacing: Spacing::Alone, 9,749 ( 0.00%) prev_token: Token::dummy(), . capture_cfg: false, . restrictions: Restrictions::empty(), . expected_tokens: Vec::new(), . token_cursor: TokenCursor { 58,494 ( 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. 19,498 ( 0.00%) parser.bump(); . . parser 87,741 ( 0.00%) } . . fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) { . loop { 3,030,492 ( 0.02%) let (mut next, spacing) = if self.desugar_doc_comments { 28,560 ( 0.00%) self.token_cursor.next_desugared() . } else { 1,493,826 ( 0.01%) self.token_cursor.next() . }; 2,020,328 ( 0.01%) self.token_cursor.num_next_calls += 1; . // We've retrieved an token from the underlying . // cursor, so we no longer need to worry about . // an unglued token. See `break_and_eat` for more details 505,082 ( 0.00%) self.token_cursor.break_last_token = false; 2,020,328 ( 0.01%) if next.span.is_dummy() { . // Tweak the location for better diagnostics, but keep syntactic context intact. 39,008 ( 0.00%) next.span = fallback_span.with_ctxt(next.span.ctxt()); . } 1,724,163 ( 0.01%) if matches!( 1,010,164 ( 0.01%) next.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 2,005,936 ( 0.01%) return (next, spacing); . } . } . . pub fn unexpected(&mut self) -> PResult<'a, T> { . match self.expect_one_of(&[], &[]) { . Err(e) => Err(e), . // We can get `Ok(true)` from `recover_closing_delimiter` . // which is called in `expected_one_of_not_found`. . Ok(_) => FatalError.raise(), . } . } . . /// Expects and consumes the token `t`. Signals an error if the next token is not `t`. 821,853 ( 0.00%) pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { 91,317 ( 0.00%) if self.expected_tokens.is_empty() { 98,532 ( 0.00%) if self.token == *t { 82,110 ( 0.00%) self.bump(); . Ok(false) . } else { . self.unexpected_try_recover(t) . } . } else { 898,740 ( 0.01%) self.expect_one_of(slice::from_ref(t), &[]) . } 1,369,755 ( 0.01%) } . . /// 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. 1,040,664 ( 0.01%) pub fn expect_one_of( . &mut self, . edible: &[TokenKind], . inedible: &[TokenKind], . ) -> PResult<'a, bool /* recovered */> { 173,444 ( 0.00%) if edible.contains(&self.token.kind) { 225,054 ( 0.00%) 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) . } 1,300,830 ( 0.01%) } . . // Public for rustfmt usage. . pub fn parse_ident(&mut self) -> PResult<'a, Ident> { 484,740 ( 0.00%) self.parse_ident_common(true) . } . . fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> { 362,139 ( 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(), . }) . } . 844,557 ( 0.01%) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { 120,651 ( 0.00%) let (ident, is_raw) = self.ident_or_err()?; 723,906 ( 0.00%) if !is_raw && ident.is_reserved() { . let mut err = self.expected_ident_found(); . if recover { . err.emit(); . } else { . return Err(err); . } . } 482,604 ( 0.00%) self.bump(); . Ok(ident) 1,206,510 ( 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. 8,646,400 ( 0.05%) fn check(&mut self, tok: &TokenKind) -> bool { 3,752,077 ( 0.02%) let is_present = self.token == *tok; 2,531,168 ( 0.02%) if !is_present { 5,061,095 ( 0.03%) self.expected_tokens.push(TokenType::Token(tok.clone())); . } . is_present 8,646,400 ( 0.05%) } . . /// Consumes a token 'tok' if it exists. Returns whether the given token was present. 12 ( 0.00%) pub fn eat(&mut self, tok: &TokenKind) -> bool { 1,942,522 ( 0.01%) let is_present = self.check(tok); 1,281,364 ( 0.01%) if is_present { 287,284 ( 0.00%) self.bump() . } . is_present 15 ( 0.00%) } . . /// If the next token is the given keyword, returns `true` without eating it. . /// An expectation is also added for diagnostics purposes. 293,540 ( 0.00%) fn check_keyword(&mut self, kw: Symbol) -> bool { 80,581 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw)); 2,245,095 ( 0.01%) 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. 518,375 ( 0.00%) pub fn eat_keyword(&mut self, kw: Symbol) -> bool { 424,402 ( 0.00%) if self.check_keyword(kw) { 58,556 ( 0.00%) self.bump(); . true . } else { . false . } 518,375 ( 0.00%) } . . fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { 91,772 ( 0.00%) if self.token.is_keyword(kw) { 22,688 ( 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. 8,875 ( 0.00%) fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { . if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } 7,100 ( 0.00%) } . . /// Is the given keyword `kw` followed by a non-reserved identifier? 525,544 ( 0.00%) fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { 262,772 ( 0.00%) self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) 591,237 ( 0.00%) } . 326,574 ( 0.00%) fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { 143,686 ( 0.00%) if ok { . true . } else { 61,280 ( 0.00%) self.expected_tokens.push(typ); . false . } 326,574 ( 0.00%) } . . fn check_ident(&mut self) -> bool { 69,015 ( 0.00%) self.check_or_expected(self.token.is_ident(), TokenType::Ident) . } . 124,576 ( 0.00%) fn check_path(&mut self) -> bool { 268,347 ( 0.00%) self.check_or_expected(self.token.is_path_start(), TokenType::Path) 155,720 ( 0.00%) } . . fn check_type(&mut self) -> bool { 9,064 ( 0.00%) self.check_or_expected(self.token.can_begin_type(), TokenType::Type) . } . . fn check_const_arg(&mut self) -> bool { 9,016 ( 0.00%) self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) . } . 69,048 ( 0.00%) fn check_inline_const(&self, dist: usize) -> bool { 38,360 ( 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, . }) 69,048 ( 0.00%) } . . /// Checks to see if the next token is either `+` or `+=`. . /// Otherwise returns `false`. . fn check_plus(&mut self) -> bool { 52,620 ( 0.00%) self.check_or_expected( 26,310 ( 0.00%) self.token.is_like_plus(), 26,310 ( 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. 577,176 ( 0.00%) fn break_and_eat(&mut self, expected: TokenKind) -> bool { 336,686 ( 0.00%) if self.token.kind == expected { 33,538 ( 0.00%) self.bump(); . return true; . } 156,645 ( 0.00%) match self.token.kind.break_two_token_op() { 525 ( 0.00%) Some((first, second)) if first == expected => { 300 ( 0.00%) let first_span = self.sess.source_map().start_point(self.token.span); 375 ( 0.00%) let second_span = self.token.span.with_lo(first_span.hi()); 675 ( 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` 75 ( 0.00%) self.token_cursor.break_last_token = true; . // Use the spacing of the glued token as the spacing . // of the unglued second token. 1,050 ( 0.00%) self.bump_with((Token::new(second, second_span), self.token_spacing)); . true . } . _ => { 93,762 ( 0.00%) self.expected_tokens.push(TokenType::Token(expected)); . false . } . } 557,898 ( 0.00%) } . . /// Eats `+` possibly breaking tokens like `+=` in process. . fn eat_plus(&mut self) -> bool { 756 ( 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, ()> { 36,552 ( 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, ()> { 102 ( 0.00%) if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `<` possibly breaking tokens like `<<` in process. 45,024 ( 0.00%) fn eat_lt(&mut self) -> bool { 128,658 ( 0.00%) let ate = self.break_and_eat(token::Lt); 82,482 ( 0.00%) if ate { . // See doc comment for `unmatched_angle_bracket_count`. 38,444 ( 0.00%) self.unmatched_angle_bracket_count += 1; 43,112 ( 0.00%) self.max_angle_bracket_count += 1; . debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); . } . ate 45,024 ( 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, ()> { 6,732 ( 0.00%) if self.break_and_eat(token::Gt) { . // See doc comment for `unmatched_angle_bracket_count`. 3,366 ( 0.00%) if self.unmatched_angle_bracket_count > 0 { 2,244 ( 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 { 176,046 ( 0.00%) TokenExpectType::Expect => self.check(k), 351 ( 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) { 144,269 ( 0.00%) if let token::CloseDelim(..) | token::Eof = self.token.kind { . break; . } 110,614 ( 0.00%) if let Some(ref t) = sep.sep { 155,563 ( 0.00%) if first { . first = false; . } else { 49,736 ( 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; . } . } . } . } . } . } 53,802 ( 0.00%) if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) { . trailing = true; . break; . } . 35,458 ( 0.00%) let t = f(self)?; 102,486 ( 0.00%) v.push(t); . } . 107,732 ( 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)> { 112,609 ( 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. 126,370 ( 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 */)> { 66,637 ( 0.00%) let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; 41,027 ( 0.00%) if !recovered { . self.eat(ket); . } 167,786 ( 0.00%) Ok((val, trailing)) 101,096 ( 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)> { 59,775 ( 0.00%) self.expect(bra)?; 101,096 ( 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( 25,972 ( 0.00%) &token::OpenDelim(delim), 39,307 ( 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. 6,520,267 ( 0.04%) fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) { . // Bumping after EOF is a bad sign, usually an infinite loop. 3,009,354 ( 0.02%) if self.prev_token.kind == TokenKind::Eof { . let msg = "attempted to bump the parser past EOF (may be stuck in a loop)"; . self.span_bug(self.token.span, msg); . } . . // Update the current and previous tokens. 2,006,236 ( 0.01%) self.prev_token = mem::replace(&mut self.token, next_token); 501,559 ( 0.00%) self.token_spacing = next_spacing; . . // Diagnostics. 501,559 ( 0.00%) self.expected_tokens.clear(); . } . . /// Advance the parser by one token. 4,011,872 ( 0.02%) pub fn bump(&mut self) { 2,005,936 ( 0.01%) let next_token = self.next_tok(self.token.span); 3,008,904 ( 0.02%) self.bump_with(next_token); 4,011,872 ( 0.02%) } . . /// 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 { 38,454 ( 0.00%) if dist == 0 { 15,097 ( 0.00%) return looker(&self.token); . } . 153,656 ( 0.00%) let frame = &self.token_cursor.frame; 177,459 ( 0.00%) if frame.delim != DelimToken::NoDelim { . let all_normal = (0..dist).all(|i| { 507,762 ( 0.00%) let token = frame.tree_cursor.look_ahead(i); 656,723 ( 0.00%) !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _))) . }); . if all_normal { 820,187 ( 0.00%) return match frame.tree_cursor.look_ahead(dist - 1) { 271,932 ( 0.00%) Some(tree) => match tree { 121,645 ( 0.00%) TokenTree::Token(token) => looker(token), . TokenTree::Delimited(dspan, delim, _) => { 102,921 ( 0.00%) looker(&Token::new(token::OpenDelim(*delim), dspan.open)) . } . }, 217,025 ( 0.00%) None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)), . }; . } . } . . let mut cursor = self.token_cursor.clone(); . let mut i = 0; 12,695 ( 0.00%) let mut token = Token::dummy(); 1,786 ( 0.00%) while i < dist { 113,663 ( 0.00%) token = cursor.next().0; 59,266 ( 0.00%) if matches!( 32,166 ( 0.00%) token.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 940 ( 0.00%) i += 1; . } 144 ( 0.00%) return looker(&token); . } . . /// Returns whether any of the given keywords are `dist` tokens ahead of the current one. 156,690 ( 0.00%) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool { 52,858 ( 0.00%) self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw))) 156,690 ( 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. 13,142 ( 0.00%) fn parse_unsafety(&mut self) -> Unsafe { . if self.eat_keyword(kw::Unsafe) { 4,360 ( 0.00%) Unsafe::Yes(self.prev_token.uninterpolated_span()) . } else { . Unsafe::No . } 52,568 ( 0.00%) } . . /// Parses constness: `const` or nothing. 120,216 ( 0.00%) fn parse_constness(&mut self) -> Const { . // Avoid const blocks to be parsed as const items 33,610 ( 0.00%) if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace)) . && self.eat_keyword(kw::Const) . { 3,685 ( 0.00%) Const::Yes(self.prev_token.uninterpolated_span()) . } else { . Const::No . } 210,378 ( 0.00%) } . . /// Parses inline const expressions. . fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P> { . if pat { . self.sess.gated_spans.gate(sym::inline_const_pat, span); . } else { . self.sess.gated_spans.gate(sym::inline_const, span); . } -- line 1104 ---------------------------------------- -- line 1110 ---------------------------------------- . }; . let blk_span = anon_const.value.span; . Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::new())) . } . . /// Parses mutability (`mut` or nothing). . fn parse_mutability(&mut self) -> Mutability { . if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not } 12,317 ( 0.00%) } . . /// Possibly parses mutability (`const` or `mut`). 792 ( 0.00%) 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 . } 792 ( 0.00%) } . . fn parse_field_name(&mut self) -> PResult<'a, Ident> { 454 ( 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 { 681 ( 0.00%) self.parse_ident_common(true) . } . } . . fn parse_mac_args(&mut self) -> PResult<'a, P> { 1,712 ( 0.00%) self.parse_mac_args_common(true).map(P) . } . . fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> { 55,617 ( 0.00%) self.parse_mac_args_common(false) . } . 174,249 ( 0.00%) fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> { 154,888 ( 0.00%) Ok( 147,313 ( 0.00%) if self.check(&token::OpenDelim(DelimToken::Paren)) 37,881 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Bracket)) 37,881 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Brace)) . { 26,980 ( 0.00%) match self.parse_token_tree() { 33,725 ( 0.00%) TokenTree::Delimited(dspan, delim, tokens) => . // We've confirmed above that there is a delimiter so unwrapping is OK. . { 13,490 ( 0.00%) MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens) . } . _ => unreachable!(), . } 25,232 ( 0.00%) } else if !delimited_only { . if self.eat(&token::Eq) { 9,194 ( 0.00%) let eq_span = self.prev_token.span; . . // Collect tokens because they are used during lowering to HIR. 9,194 ( 0.00%) let expr = self.parse_expr_force_collect()?; 9,194 ( 0.00%) let span = expr.span; . 45,970 ( 0.00%) let token_kind = token::Interpolated(Lrc::new(token::NtExpr(expr))); 82,746 ( 0.00%) MacArgs::Eq(eq_span, Token::new(token_kind, span)) . } else { . MacArgs::Empty . } . } else { . return self.unexpected(); . }, . ) 135,527 ( 0.00%) } . . fn parse_or_use_outer_attributes( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, AttrWrapper> { 104,802 ( 0.00%) if let Some(attrs) = already_parsed_attrs { . Ok(attrs) . } else { 48,972 ( 0.00%) self.parse_outer_attributes() . } . } . . /// Parses a single token tree from the input. 54,544 ( 0.00%) pub(crate) fn parse_token_tree(&mut self) -> TokenTree { 20,470 ( 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. 197,844 ( 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. 126,242 ( 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; 13,628 ( 0.00%) let stream = frame.tree_cursor.stream.clone(); 13,628 ( 0.00%) let span = frame.span; 6,814 ( 0.00%) let delim = frame.delim; . // Consume close delimiter 13,628 ( 0.00%) self.bump(); 34,070 ( 0.00%) TokenTree::Delimited(span, delim, stream) . } . token::CloseDelim(_) | token::Eof => unreachable!(), . _ => { 8 ( 0.00%) self.bump(); 20 ( 0.00%) TokenTree::Token(self.prev_token.clone()) . } . } 47,726 ( 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 { 43,428 ( 0.00%) let old = self.restrictions; 56,140 ( 0.00%) self.restrictions = res; . let res = f(self); 59,118 ( 0.00%) self.restrictions = old; . res . } . 187,728 ( 0.00%) fn is_crate_vis(&self) -> bool { 117,330 ( 0.00%) self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep) 211,194 ( 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. 154,330 ( 0.00%) pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> { 30,889 ( 0.00%) maybe_whole!(self, NtVis, |x| x); . 15,431 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw::Crate)); 61,724 ( 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". 13,161 ( 0.00%) return Ok(Visibility { 39,483 ( 0.00%) span: self.token.span.shrink_to_lo(), . kind: VisibilityKind::Inherited, . tokens: None, . }); . } 2,270 ( 0.00%) let lo = self.prev_token.span; . 11,350 ( 0.00%) if self.check(&token::OpenDelim(token::Paren)) { . // We don't `self.bump()` the `(` yet because this might be a struct definition where . // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`. . // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so . // by the following tokens. . if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep) . // account for `pub(crate::foo)` . { . // Parse `pub(crate)`. -- line 1303 ---------------------------------------- -- line 1338 ---------------------------------------- . } else if let FollowedByType::No = fbt { . // Provide this diagnostic if a type cannot follow; . // in particular, if this is not a tuple struct. . self.recover_incorrect_vis_restriction()?; . // Emit diagnostic, but continue with public visibility. . } . } . 6,810 ( 0.00%) Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None }) 138,897 ( 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 { 7,498 ( 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. 14,660 ( 0.00%) fn parse_abi(&mut self) -> Option { . match self.parse_str_lit() { 8,796 ( 0.00%) Ok(str_lit) => Some(str_lit), . Err(Some(lit)) => match lit.kind { . ast::LitKind::Err(_) => None, . _ => { . self.struct_span_err(lit.span, "non-string ABI literal") . .span_suggestion( . lit.span, . "specify the ABI with a string literal", . "\"C\"".to_string(), -- line 1392 ---------------------------------------- -- line 1393 ---------------------------------------- . Applicability::MaybeIncorrect, . ) . .emit(); . None . } . }, . Err(None) => None, . } 11,728 ( 0.00%) } . 99,690 ( 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, 10,045 ( 0.00%) |this, _attrs| Ok((f(this)?, TrailingToken::None)), . ) 99,690 ( 0.00%) } . . /// `::{` or `::*` 875,360 ( 0.01%) fn is_import_coupler(&mut self) -> bool { 437,680 ( 0.00%) self.check(&token::ModSep) . && self.look_ahead(1, |t| { 311,688 ( 0.00%) *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star) . }) 822,753 ( 0.00%) } . . pub fn clear_expected_tokens(&mut self) { . self.expected_tokens.clear(); . } . } . . crate fn make_unclosed_delims_error( . unmatched: UnmatchedBrace, -- line 1430 ---------------------------------------- -- line 1450 ---------------------------------------- . err.span_label(sp, "closing delimiter possibly meant for this"); . } . if let Some(sp) = unmatched.unclosed_span { . err.span_label(sp, "unclosed delimiter"); . } . Some(err) . } . 158,656 ( 0.00%) pub fn emit_unclosed_delims(unclosed_delims: &mut Vec, sess: &ParseSess) { 79,328 ( 0.00%) *sess.reached_eof.borrow_mut() |= . unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()); 79,328 ( 0.00%) for unmatched in unclosed_delims.drain(..) { . if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) { . e.emit(); . } . } 158,656 ( 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 ---------------------------------------- 3,107,331 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/map/entry.rs -------------------------------------------------------------------------------- Ir -- line 140 ---------------------------------------- . /// let mut map: BTreeMap<&str, String> = BTreeMap::new(); . /// let s = "hoho".to_string(); . /// . /// map.entry("poneyland").or_insert_with(|| s); . /// . /// assert_eq!(map["poneyland"], "hoho".to_string()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 692,782 ( 0.00%) pub fn or_insert_with V>(self, default: F) -> &'a mut V { 301,503 ( 0.00%) match self { . Occupied(entry) => entry.into_mut(), 2,011,723 ( 0.01%) Vacant(entry) => entry.insert(default()), . } 831,935 ( 0.00%) } . . /// Ensures a value is in the entry by inserting, if empty, the result of the default function. . /// This method allows for generating key-derived values for insertion by providing the default . /// function a reference to the key that was moved during the `.entry(key)` method call. . /// . /// The reference to the moved key is provided so that cloning or copying the key is . /// unnecessary, unlike with `.or_insert_with(|| ... )`. . /// -- line 161 ---------------------------------------- -- line 245 ---------------------------------------- . /// ``` . /// use std::collections::BTreeMap; . /// . /// let mut map: BTreeMap<&str, Option> = BTreeMap::new(); . /// map.entry("poneyland").or_default(); . /// . /// assert_eq!(map["poneyland"], None); . /// ``` 4,149 ( 0.00%) pub fn or_default(self) -> &'a mut V { 2,766 ( 0.00%) match self { . Occupied(entry) => entry.into_mut(), 151 ( 0.00%) Vacant(entry) => entry.insert(Default::default()), . } 6,915 ( 0.00%) } . } . . impl<'a, K: Ord, V> VacantEntry<'a, K, V> { . /// Gets a reference to the key that would be used when inserting a value . /// through the VacantEntry. . /// . /// # Examples . /// -- line 266 ---------------------------------------- -- line 306 ---------------------------------------- . /// let mut map: BTreeMap<&str, u32> = BTreeMap::new(); . /// . /// if let Entry::Vacant(o) = map.entry("poneyland") { . /// o.insert(37); . /// } . /// assert_eq!(map["poneyland"], 37); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 5,519,403 ( 0.03%) pub fn insert(self, value: V) -> &'a mut V { 14,136,365 ( 0.08%) let out_ptr = match self.handle.insert_recursing(self.key, value) { 1,137,725 ( 0.01%) (Fit(_), val_ptr) => { . // SAFETY: We have consumed self.handle and the handle returned. 1,020,324 ( 0.01%) let map = unsafe { self.dormant_map.awaken() }; 4,390,686 ( 0.03%) map.length += 1; . val_ptr . } 70,296 ( 0.00%) (Split(ins), val_ptr) => { . drop(ins.left); . // SAFETY: We have consumed self.handle and the reference returned. 7,681 ( 0.00%) let map = unsafe { self.dormant_map.awaken() }; . let root = map.root.as_mut().unwrap(); 57,429 ( 0.00%) root.push_internal_level().push(ins.kv.0, ins.kv.1, ins.right); 40,255 ( 0.00%) map.length += 1; . val_ptr . } . }; . // Now that we have finished growing the tree using borrowed references, . // dereference the pointer to a part of it, that we picked up along the way. . unsafe { &mut *out_ptr } 5,672,958 ( 0.03%) } . } . . impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> { . /// Gets a reference to the key in the entry. . /// . /// # Examples . /// . /// ``` -- line 343 ---------------------------------------- -- line 368 ---------------------------------------- . /// // We delete the entry from the map. . /// o.remove_entry(); . /// } . /// . /// // If now try to get the value, it will panic: . /// // println!("{}", map["poneyland"]); . /// ``` . #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")] 4,703,325 ( 0.03%) pub fn remove_entry(self) -> (K, V) { 940,849 ( 0.01%) self.remove_kv() 7,132,414 ( 0.04%) } . . /// Gets a reference to the value in the entry. . /// . /// # Examples . /// . /// ``` . /// use std::collections::BTreeMap; . /// use std::collections::btree_map::Entry; -- line 386 ---------------------------------------- -- line 448 ---------------------------------------- . /// if let Entry::Occupied(o) = map.entry("poneyland") { . /// *o.into_mut() += 10; . /// } . /// assert_eq!(map["poneyland"], 22); . /// ``` . #[must_use = "`self` will be dropped if the result is not used"] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn into_mut(self) -> &'a mut V { 3,576 ( 0.00%) self.handle.into_val_mut() . } . . /// Sets the value of the entry with the `OccupiedEntry`'s key, . /// and returns the entry's old value. . /// . /// # Examples . /// . /// ``` -- line 464 ---------------------------------------- -- line 497 ---------------------------------------- . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn remove(self) -> V { . self.remove_kv().1 . } . . // Body of `remove_entry`, probably separate because the name reflects the returned pair. . pub(super) fn remove_kv(self) -> (K, V) { 1,039,954 ( 0.01%) let mut emptied_internal_root = false; 13,796,655 ( 0.08%) let (old_kv, _) = self.handle.remove_kv_tracking(|| emptied_internal_root = true); . // SAFETY: we consumed the intermediate root borrow, `self.handle`. . let map = unsafe { self.dormant_map.awaken() }; 4,158,848 ( 0.02%) map.length -= 1; 2,079,424 ( 0.01%) if emptied_internal_root { . let root = map.root.as_mut().unwrap(); . root.pop_internal_level(); . } . old_kv . } . } 1,969,461 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 84 ---------------------------------------- . pub struct SessionGlobals { . symbol_interner: symbol::Interner, . span_interner: Lock, . hygiene_data: Lock, . source_map: Lock>>, . } . . impl SessionGlobals { 12 ( 0.00%) pub fn new(edition: Edition) -> SessionGlobals { 50 ( 0.00%) SessionGlobals { 2 ( 0.00%) symbol_interner: symbol::Interner::fresh(), . span_interner: Lock::new(span_encoding::SpanInterner::default()), 6 ( 0.00%) hygiene_data: Lock::new(hygiene::HygieneData::new(edition)), . source_map: Lock::new(None), . } 10 ( 0.00%) } . } . . #[inline] . pub fn create_session_globals_then(edition: Edition, f: impl FnOnce() -> R) -> R { 1 ( 0.00%) assert!( . !SESSION_GLOBALS.is_set(), . "SESSION_GLOBALS should never be overwritten! \ . Use another thread if you need another SessionGlobals" . ); 3 ( 0.00%) let session_globals = SessionGlobals::new(edition); 7 ( 0.00%) SESSION_GLOBALS.set(&session_globals, f) 1 ( 0.00%) } . . #[inline] . pub fn set_session_globals_then(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R { . assert!( . !SESSION_GLOBALS.is_set(), . "SESSION_GLOBALS should never be overwritten! \ . Use another thread if you need another SessionGlobals" . ); -- line 119 ---------------------------------------- -- line 120 ---------------------------------------- . SESSION_GLOBALS.set(session_globals, f) . } . . #[inline] . pub fn create_default_session_if_not_set_then(f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 4 ( 0.00%) create_session_if_not_set_then(edition::DEFAULT_EDITION, f) . } . . #[inline] . pub fn create_session_if_not_set_then(edition: Edition, f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 1 ( 0.00%) if !SESSION_GLOBALS.is_set() { 3 ( 0.00%) let session_globals = SessionGlobals::new(edition); 11 ( 0.00%) SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f)) 1 ( 0.00%) } else { . SESSION_GLOBALS.with(f) . } . } . . #[inline] . pub fn with_session_globals(f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 3,858,219 ( 0.02%) 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. 585 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd)] 1,096 ( 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,765 ( 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> { 2 ( 0.00%) encoder.emit_enum(|encoder| match *self { . RealFileName::LocalPath(ref local_path) => { 8 ( 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 213 ---------------------------------------- . } . } . . impl RealFileName { . /// 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. . pub fn local_path(&self) -> Option<&Path> { 2 ( 0.00%) match self { . RealFileName::LocalPath(p) => Some(p), . RealFileName::Remapped { local_path: p, virtual_name: _ } => { . p.as_ref().map(PathBuf::as_path) . } . } . } . . /// Returns the path suitable for reading from the file system on the local host, . /// if this information exists. . /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that. 2 ( 0.00%) pub fn into_local_path(self) -> Option { 2 ( 0.00%) match self { . RealFileName::LocalPath(p) => Some(p), . RealFileName::Remapped { local_path: p, virtual_name: _ } => p, . } 3 ( 0.00%) } . . /// Returns the path suitable for embedding into build artifacts. This would still . /// be a local path if it has not been remapped. A remapped path will not correspond . /// to a valid file system path: see `local_path_if_available()` for something that . /// is more likely to return paths into the local host file system. . pub fn remapped_path_if_available(&self) -> &Path { 4,012 ( 0.00%) match self { . RealFileName::LocalPath(p) . | RealFileName::Remapped { local_path: _, virtual_name: p } => &p, . } 2 ( 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 { 1 ( 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> { 903 ( 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. 331,753 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)] 6,634 ( 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) . MacroExpansion(u64), 8,138 ( 0.00%) ProcMacroSourceCode(u64), . /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`. . CfgSpec(u64), . /// Strings provided as crate attributes in the CLI. . CliCrateAttr(u64), . /// 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 { 7 ( 0.00%) fn from(p: PathBuf) -> Self { 2 ( 0.00%) assert!(!p.to_string_lossy().ends_with('>')); 6 ( 0.00%) FileName::Real(RealFileName::LocalPath(p)) 7 ( 0.00%) } . } . 34 ( 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<'_> { 52 ( 0.00%) fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { . use FileName::*; 78 ( 0.00%) match *self.inner { . Real(ref name) => { 78 ( 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, ""), . } 65 ( 0.00%) } . } . . impl FileNameDisplay<'_> { 3,560 ( 0.00%) pub fn to_string_lossy(&self) -> Cow<'_, str> { 2,670 ( 0.00%) match self.inner { 890 ( 0.00%) FileName::Real(ref inner) => inner.to_string_lossy(self.display_pref), . _ => Cow::from(format!("{}", self)), . } 3,560 ( 0.00%) } . } . . impl FileName { . pub fn is_real(&self) -> bool { . use FileName::*; 1,100 ( 0.00%) match *self { . Real(_) => true, . Anon(_) . | MacroExpansion(_) . | ProcMacroSourceCode(_) . | CfgSpec(_) . | CliCrateAttr(_) . | Custom(_) . | QuoteExpansion(_) . | DocTest(_, _) . | InlineAsm(_) => false, . } . } . 890 ( 0.00%) pub fn prefer_remapped(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Remapped } 1,780 ( 0.00%) } . . // This may include transient local filesystem information. . // Must not be embedded in build outputs. 1 ( 0.00%) pub fn prefer_local(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local } 2 ( 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 377 ---------------------------------------- . } . . pub fn anon_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); . FileName::Anon(hasher.finish()) . } . 40,690 ( 0.00%) pub fn proc_macro_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); 16,276 ( 0.00%) FileName::ProcMacroSourceCode(hasher.finish()) 40,690 ( 0.00%) } . . pub fn cfg_spec_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); . FileName::QuoteExpansion(hasher.finish()) . } . . pub fn cli_crate_attr_source_code(src: &str) -> FileName { -- line 397 ---------------------------------------- -- 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 { 3 ( 0.00%) pub lo: BytePos, 3 ( 0.00%) pub hi: BytePos, . /// Information about where the macro came from, if this piece of . /// code was created by a macro expansion. 9 ( 0.00%) pub ctxt: SyntaxContext, 3 ( 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 { 1,314,543 ( 0.01%) self.lo.0 == 0 && self.hi.0 == 0 . } . /// Returns `true` if `self` fully encloses `other`. . pub fn contains(self, other: Self) -> bool { 1,728 ( 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 { 298,288 ( 0.00%) fn partial_cmp(&self, rhs: &Self) -> Option { 223,716 ( 0.00%) PartialOrd::partial_cmp(&self.data(), &rhs.data()) 298,288 ( 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] 208,242 ( 0.00%) pub fn with_lo(self, lo: BytePos) -> Span { . self.data().with_lo(lo) 138,828 ( 0.00%) } . #[inline] 80,020 ( 0.00%) pub fn hi(self) -> BytePos { . self.data().hi 80,020 ( 0.00%) } . #[inline] 208,791 ( 0.00%) pub fn with_hi(self, hi: BytePos) -> Span { . self.data().with_hi(hi) 139,194 ( 0.00%) } . #[inline] . pub fn ctxt(self) -> SyntaxContext { . self.data_untracked().ctxt . } . #[inline] 52,885 ( 0.00%) pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span { . self.data_untracked().with_ctxt(ctxt) 31,731 ( 0.00%) } . #[inline] . pub fn parent(self) -> Option { . self.data().parent . } . #[inline] 603 ( 0.00%) pub fn with_parent(self, ctxt: Option) -> Span { . self.data().with_parent(ctxt) 402 ( 0.00%) } . . /// Returns `true` if this is a dummy span with any hygienic context. . #[inline] . pub fn is_dummy(self) -> bool { . self.data_untracked().is_dummy() . } . . /// Returns `true` if this span comes from a macro or desugaring. -- line 574 ---------------------------------------- -- 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] 87 ( 0.00%) pub fn shrink_to_hi(self) -> Span { . let span = self.data_untracked(); . span.with_lo(span.hi) 58 ( 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`. 5,184 ( 0.00%) pub fn contains(self, other: Span) -> bool { . let span = self.data(); . let other = other.data(); . span.contains(other) 3,456 ( 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 663 ---------------------------------------- . /// 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`. 2,120 ( 0.00%) pub fn find_ancestor_inside(mut self, outer: Span) -> Option { 1,060 ( 0.00%) while !outer.contains(self) { . self = self.parent_callsite()?; . } . Some(self) 2,332 ( 0.00%) } . . /// Edition of the crate from which this span came. 104,430 ( 0.00%) pub fn edition(self) -> edition::Edition { . self.ctxt().edition() 69,620 ( 0.00%) } . . #[inline] . pub fn rust_2015(self) -> bool { 27,478 ( 0.00%) self.edition() == edition::Edition::Edition2015 . } . . #[inline] . pub fn rust_2018(self) -> bool { 2,666 ( 0.00%) self.edition() >= edition::Edition::Edition2018 . } . . #[inline] . pub fn rust_2021(self) -> bool { 4,573 ( 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]`). 8,185 ( 0.00%) pub fn allows_unstable(self, feature: Symbol) -> bool { 1,637 ( 0.00%) self.ctxt() . .outer_expn_data() . .allow_internal_unstable . .map_or(false, |features| features.iter().any(|&f| f == feature)) 6,548 ( 0.00%) } . . /// Checks if this span arises from a compiler desugaring of kind `kind`. 94,080 ( 0.00%) pub fn is_desugaring(self, kind: DesugaringKind) -> bool { 80,640 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => k == kind, . _ => false, . } 67,200 ( 0.00%) } . . /// Returns the compiler desugaring that created this span, or `None` . /// if this span is not from a desugaring. 65 ( 0.00%) pub fn desugaring_kind(self) -> Option { 78 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => Some(k), . _ => None, . } 52 ( 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]`). 6,804 ( 0.00%) pub fn allows_unsafe(self) -> bool { 1,701 ( 0.00%) self.ctxt().outer_expn_data().allow_internal_unsafe 6,804 ( 0.00%) } . . pub fn macro_backtrace(mut self) -> impl Iterator { . let mut prev_span = DUMMY_SP; . std::iter::from_fn(move || { . loop { . let expn_data = self.ctxt().outer_expn_data(); . if expn_data.is_root() { . return None; -- line 752 ---------------------------------------- -- line 767 ---------------------------------------- . . /// Returns a `Span` that would enclose both `self` and `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^^^^ . /// ``` 3,900,259 ( 0.02%) pub fn to(self, end: Span) -> Span { . let span_data = self.data(); . let end_data = end.data(); . // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480). . // Return the macro span on its own to avoid weird diagnostic output. It is preferable to . // have an incomplete span than a completely nonsensical one. 703,864 ( 0.00%) if span_data.ctxt != end_data.ctxt { 5,274 ( 0.00%) if span_data.ctxt == SyntaxContext::root() { . return end; 3,860 ( 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 }, 2,448,586 ( 0.01%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 3,191,121 ( 0.02%) } . . /// Returns a `Span` between the end of `self` to the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^ . /// ``` 19,349 ( 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 }, 12,313 ( 0.00%) if span.parent == end.parent { span.parent } else { None }, . ) 14,072 ( 0.00%) } . . /// Returns a `Span` from the beginning of `self` until the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^ . /// ``` 60,159 ( 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. 8,239 ( 0.00%) if span_data.ctxt != end_data.ctxt { 2,699 ( 0.00%) if span_data.ctxt == SyntaxContext::root() { . return end; 737 ( 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( . span_data.lo, . end_data.lo, . if end_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt }, 24,549 ( 0.00%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 49,221 ( 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 { 3,264 ( 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 { 1,590 ( 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 { 130 ( 0.00%) 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). 29,904 ( 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)) 17,444 ( 0.00%) } . . #[inline] . pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { . let span = self.data(); 253,566 ( 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] 274,005 ( 0.00%) pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option { 182,670 ( 0.00%) let mut span = self.data(); 148,503 ( 0.00%) let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id); 274,005 ( 0.00%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark 300,728 ( 0.00%) } . . #[inline] . pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option> { 1,932 ( 0.00%) let mut span = self.data(); 2,898 ( 0.00%) let mark = span.ctxt.glob_adjust(expn_id, glob_span); 7,728 ( 0.00%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } . . #[inline] 5,184 ( 0.00%) pub fn reverse_glob_adjust( . &mut self, . expn_id: ExpnId, . glob_span: Span, . ) -> Option> { 15,950 ( 0.00%) let mut span = self.data(); 27,868 ( 0.00%) let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span); 55,160 ( 0.00%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark 5,760 ( 0.00%) } . . #[inline] 336,928 ( 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()) 294,812 ( 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 { 96,145 ( 0.00%) MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] } . } . . pub fn from_spans(mut vec: Vec) -> MultiSpan { . vec.sort(); 280 ( 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() 16,979 ( 0.00%) } . . /// Returns all primary spans. . pub fn primary_spans(&self) -> &[Span] { . &self.primary_spans 208 ( 0.00%) } . . /// Returns `true` if any of the primary spans are displayable. . pub fn has_primary_spans(&self) -> bool { . self.primary_spans.iter().any(|sp| !sp.is_dummy()) . } . . /// Returns `true` if this contains only a dummy primary span with any hygienic context. . pub fn is_dummy(&self) -> bool { -- line 1084 ---------------------------------------- -- 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 { 96,145 ( 0.00%) fn from(span: Span) -> MultiSpan { . MultiSpan::from_span(span) 96,145 ( 0.00%) } . } . . impl From> for MultiSpan { 280 ( 0.00%) fn from(spans: Vec) -> MultiSpan { 224 ( 0.00%) MultiSpan::from_spans(spans) 280 ( 0.00%) } . } . . /// Identifies an offset of a multi-byte character in a `SourceFile`. 341 ( 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`. 312 ( 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 { 540 ( 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; . 156 ( 0.00%) fn sub(self, rhs: BytePos) -> Self { 540 ( 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), . } 468 ( 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, . } . 3 ( 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> { 1,178 ( 0.00%) match self { . ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src), . _ => None, . } . } . } . . #[derive(Debug)] . pub struct OffsetOverflowError; . 1,114 ( 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. 6 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Debug)] 2,228 ( 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 { 1 ( 0.00%) 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 => { 30 ( 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)); . } . } . hash . } . . /// Check if the stored hash matches the hash of the string. . pub fn matches(&self, src: &str) -> bool { 1 ( 0.00%) Self::new(self.kind, src) == *self . } . . /// The bytes of the hash. . pub fn hash_bytes(&self) -> &[u8] { . let len = self.hash_len(); . &self.value[..len] . } . . fn hash_len(&self) -> usize { 29 ( 0.00%) match self.kind { . SourceFileHashAlgorithm::Md5 => 16, . SourceFileHashAlgorithm::Sha1 => 20, . SourceFileHashAlgorithm::Sha256 => 32, . } . } . } . . /// A single source in the [`SourceMap`]. 58 ( 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. 1 ( 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. 1 ( 0.00%) pub name_hash: u128, . /// Indicates which crate this `SourceFile` was imported from. 1 ( 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)?; . 4 ( 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 { 2 ( 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); . 2 ( 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))?; 3 ( 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))?; 11 ( 0.00%) s.emit_struct_field("cnum", false, |s| self.cnum.encode(s)) . }) . } . } . . impl Decodable for SourceFile { 5,013 ( 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); 557 ( 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 { 901,124 ( 0.01%) 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,114 ( 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,127 ( 0.00%) SourceFile { 4,456 ( 0.00%) name, . start_pos, . end_pos, . src: None, 2,228 ( 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,228 ( 0.00%) lines, 2,228 ( 0.00%) multibyte_chars, 2,228 ( 0.00%) non_narrow_chars, 2,228 ( 0.00%) normalized_pos, . name_hash, . cnum, . } . }) 5,013 ( 0.00%) } . } . . impl fmt::Debug for SourceFile { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(fmt, "SourceFile({:?})", self.name) . } . } . . impl SourceFile { 99 ( 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); 27 ( 0.00%) let normalized_pos = normalize_src(&mut src, start_pos); . . let name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 18 ( 0.00%) name.hash(&mut hasher); . hasher.finish::() . }; 18 ( 0.00%) let end_pos = start_pos.to_usize() + src.len(); 27 ( 0.00%) assert!(end_pos <= u32::MAX as usize); . 108 ( 0.00%) let (lines, multibyte_chars, non_narrow_chars) = 18 ( 0.00%) analyze_source_file::analyze_source_file(&src, start_pos); . 153 ( 0.00%) SourceFile { . name, . src: Some(Lrc::new(src)), 99 ( 0.00%) src_hash, . external_src: Lock::new(ExternalSource::Unneeded), . start_pos, . end_pos: Pos::from_usize(end_pos), 36 ( 0.00%) lines, 36 ( 0.00%) multibyte_chars, 36 ( 0.00%) non_narrow_chars, 36 ( 0.00%) normalized_pos, . name_hash, . cnum: LOCAL_CRATE, . } 81 ( 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. 20,118 ( 0.00%) pub fn add_external_src(&self, get_src: F) -> bool . where . F: FnOnce() -> Option, . { 2,876 ( 0.00%) if matches!( 5,748 ( 0.00%) *self.external_src.borrow(), . ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. } . ) { 1 ( 0.00%) 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 3 ( 0.00%) if let ExternalSource::Foreign { . kind: src_kind @ ExternalSourceKind::AbsentOk, .. . } = &mut *external_src . { 5 ( 0.00%) if let Some(mut src) = src { . // The src_hash needs to be computed on the pre-normalized src. 1 ( 0.00%) if self.src_hash.matches(&src) { 3 ( 0.00%) normalize_src(&mut src, BytePos::from_usize(0)); 8 ( 0.00%) *src_kind = ExternalSourceKind::Present(Lrc::new(src)); . return true; . } . } else { . *src_kind = ExternalSourceKind::AbsentErr; . } . . false . } else { . self.src.is_some() || external_src.get_source().is_some() . } . } else { 2,873 ( 0.00%) self.src.is_some() || self.external_src.borrow().get_source().is_some() . } 25,866 ( 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() 550 ( 0.00%) } . . pub fn is_imported(&self) -> bool { . self.src.is_none() 111,007 ( 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 { 30,295 ( 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 { 109,753 ( 0.00%) if self.is_empty() { . return self.start_pos..self.end_pos; . } . 73,181 ( 0.00%) assert!(line_index < self.lines.len()); 106,749 ( 0.00%) if line_index == (self.lines.len() - 1) { 6 ( 0.00%) self.lines[line_index]..self.end_pos . } else { 71,162 ( 0.00%) self.lines[line_index]..self.lines[line_index + 1] . } . } . . /// Returns whether or not the file contains the given `SourceMap` byte . /// position. The position one past the end of the file is considered to be . /// contained by the file. This implies that files for which `is_empty` . /// returns true still contain one byte position according to this function. . #[inline] -- line 1674 ---------------------------------------- -- line 1692 ---------------------------------------- . Err(i) if i == 0 => 0, . Err(i) => self.normalized_pos[i - 1].diff, . }; . . BytePos::from_u32(pos.0 - self.start_pos.0 + diff) . } . . /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`. 2,402 ( 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; . 7,206 ( 0.00%) for mbc in self.multibyte_chars.iter() { . debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos); 114,344 ( 0.00%) if mbc.pos < bpos { . // Every character is at least one byte, so we only . // count the actual extra bytes. 335,772 ( 0.00%) total_extra_bytes += mbc.bytes as u32 - 1; . // We should never see a byte position in the middle of a . // character. 279,810 ( 0.00%) assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32); . } else { . break; . } . } . 14,412 ( 0.00%) assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32()); 12,010 ( 0.00%) CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize) 4,804 ( 0.00%) } . . /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a . /// given `BytePos`. 8,407 ( 0.00%) pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) { 2,402 ( 0.00%) let chpos = self.bytepos_to_file_charpos(pos); 538 ( 0.00%) match self.lookup_line(pos) { . Some(a) => { . let line = a + 1; // Line numbers start at 1 1,201 ( 0.00%) let linebpos = self.lines[a]; 2,402 ( 0.00%) let linechpos = self.bytepos_to_file_charpos(linebpos); . let col = chpos - linechpos; . debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos); . debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos); . debug!("byte is on line: {}", line); 1,201 ( 0.00%) assert!(chpos >= linechpos); . (line, col) . } . None => (0, chpos), . } 9,608 ( 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`. 9,608 ( 0.00%) pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) { 3,603 ( 0.00%) let (line, col_or_chpos) = self.lookup_file_pos(pos); 2,402 ( 0.00%) if line > 0 { . let col = col_or_chpos; 1,201 ( 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); 6 ( 0.00%) let special_chars = end_width_idx - start_width_idx; . let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx] . .iter() . .map(|x| x.width()) . .sum(); 6,005 ( 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) . } 8,407 ( 0.00%) } . } . . /// Normalizes the source code and records the normalizations. 100 ( 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 90 ( 0.00%) } . . /// Removes UTF-8 BOM, if any. . fn remove_bom(src: &mut String, normalized_pos: &mut Vec) { 9 ( 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) { 10 ( 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])* 169,219 ( 0.00%) $vis struct $ident($inner_vis $inner_ty); . . impl Pos for $ident { . #[inline(always)] . fn from_usize(n: usize) -> $ident { 4,577 ( 0.00%) $ident(n as $inner_ty) . } . . #[inline(always)] . fn to_usize(&self) -> usize { 133,739 ( 0.00%) 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 { 3,595,489 ( 0.02%) $ident(self.0 + rhs.0) . } . } . . impl Sub for $ident { . type Output = $ident; . . #[inline(always)] . fn sub(self, rhs: $ident) -> $ident { 4,909,253 ( 0.03%) $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 { 1,945,930 ( 0.01%) BytePos(d.read_u32()) . } . } . . // _____________________________________________________________________________ . // Loc, SourceFileAndLine, SourceFileAndBytePos . // . . /// A source code location used for error reporting. -- line 1962 ---------------------------------------- -- line 2079 ---------------------------------------- . /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column) . /// triple, which stays the same even if the containing `SourceFile` has moved . /// within the `SourceMap`. . /// . /// Also note that we are hashing byte offsets for the column, not unicode . /// codepoint offsets. For the purpose of the hash that's sufficient. . /// Also, hashing filenames is expensive so we avoid doing it twice when the . /// span starts and ends in the same file, which is almost always the case. 2,437,470 ( 0.01%) 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; . 449,015 ( 0.00%) if !ctx.hash_spans() { . return; . } . 1,988,455 ( 0.01%) let span = self.data_untracked(); 742,219 ( 0.00%) span.ctxt.hash_stable(ctx, hasher); 1,044,630 ( 0.01%) span.parent.hash_stable(ctx, hasher); . 699,948 ( 0.00%) if span.is_dummy() { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . 689,364 ( 0.00%) 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. 1,378,728 ( 0.01%) let (file, line_lo, col_lo, line_hi, col_hi) = match ctx.span_data_to_lines_and_cols(&span) . { 689,364 ( 0.00%) 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. . 344,682 ( 0.00%) let col_lo_trunc = (col_lo.0 as u64) & 0xFF; . let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8; . let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32; . let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40; . let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc; 344,682 ( 0.00%) let len = (span.hi - span.lo).0; . Hash::hash(&col_line, hasher); . Hash::hash(&len, hasher); 2,785,680 ( 0.02%) } . } 7,612,711 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/closure.rs -------------------------------------------------------------------------------- Ir -- line 10 ---------------------------------------- . type Env; . } . . impl<'a, A, R> !Sync for Closure<'a, A, R> {} . impl<'a, A, R> !Send for Closure<'a, A, R> {} . . impl<'a, A, R, F: FnMut(A) -> R> From<&'a mut F> for Closure<'a, A, R> { . fn from(f: &'a mut F) -> Self { 7,583,241 ( 0.05%) unsafe extern "C" fn call R>(env: &mut Env, arg: A) -> R { . (*(env as *mut _ as *mut F))(arg) 10,110,988 ( 0.06%) } . Closure { call: call::, env: unsafe { &mut *(f as *mut _ as *mut Env) } } . } . } . . impl<'a, A, R> Closure<'a, A, R> { . pub fn call(&mut self, arg: A) -> R { 40,443,952 ( 0.24%) unsafe { (self.call)(self.env, arg) } . } . } -------------------------------------------------------------------------------- -- 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}; . 356,934 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum CommentKind { . Line, . Block, . } . 4,457 ( 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. 198,029 ( 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, . } . 81,229 ( 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. 573,511 ( 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 { 8,555 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 15,399 ( 0.00%) let Lit { kind, symbol, suffix } = *self; . match kind { . Byte => write!(f, "b'{}'", symbol)?, . Char => write!(f, "'{}'", symbol)?, 2,256 ( 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 . )?, 2,877 ( 0.00%) Integer | Float | Bool | Err => write!(f, "{}", symbol)?, . } . 4,894 ( 0.00%) if let Some(suffix) = suffix { 5,152 ( 0.00%) write!(f, "{}", suffix)?; . } . . Ok(()) 8,555 ( 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 123 ---------------------------------------- . Float => "float", . Str | StrRaw(..) => "string", . ByteStr | ByteStrRaw(..) => "byte string", . Err => "error", . } . } . . crate fn may_have_suffix(self) -> bool { 2,948 ( 0.00%) matches!(self, Integer | Float | Err) . } . } . . impl Lit { . pub fn new(kind: LitKind, symbol: Symbol, suffix: Option) -> Lit { . Lit { kind, symbol, suffix } 43,241 ( 0.00%) } . } . 228 ( 0.00%) pub fn ident_can_begin_expr(name: Symbol, span: Span, is_raw: bool) -> bool { 399 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 167 ( 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) 285 ( 0.00%) } . . fn ident_can_begin_type(name: Symbol, span: Span, is_raw: bool) -> bool { 5,838 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 2,036 ( 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) . } . 50,033,832 ( 0.30%) #[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, 335,742 ( 0.00%) BinOp(BinOpToken), . BinOpEq(BinOpToken), . . /* Structural symbols */ . At, . Dot, . DotDot, . DotDotDot, . DotDotEq, -- line 202 ---------------------------------------- -- line 208 ---------------------------------------- . LArrow, . FatArrow, . Pound, . Dollar, . Question, . /// Used by proc macros for representing lifetimes, not generated by lexer right now. . SingleQuote, . /// An opening delimiter (e.g., `{`). 664,530 ( 0.00%) OpenDelim(DelimToken), . /// A closing delimiter (e.g., `}`). 230,703 ( 0.00%) CloseDelim(DelimToken), . . /* Literals */ 308,271 ( 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. 603,988 ( 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. 4,194 ( 0.00%) Lifetime(Symbol), . 20,805 ( 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. 41,958 ( 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); . 4,120,085 ( 0.02%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Token { 230,679 ( 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)) 14,395 ( 0.00%) } . . // 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`. 31,329 ( 0.00%) pub fn break_two_token_op(&self) -> Option<(TokenKind, TokenKind)> { 125,981 ( 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), 31,254 ( 0.00%) _ => return None, . }) 31,329 ( 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 { 4,246 ( 0.00%) matches!(self, Gt | Ge | BinOp(Shr) | BinOpEq(Shr)) 952 ( 0.00%) } . } . . impl Token { 105,909 ( 0.00%) pub fn new(kind: TokenKind, span: Span) -> Self { 442,834 ( 0.00%) Token { kind, span } 105,909 ( 0.00%) } . . /// Some token that will be thrown away later. 40,329 ( 0.00%) pub fn dummy() -> Self { . Token::new(TokenKind::Question, DUMMY_SP) 40,329 ( 0.00%) } . . /// Recovers a `Token` from an `Ident`. This creates a raw identifier if necessary. . pub fn from_ast_ident(ident: Ident) -> Self { 3,584 ( 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. 28,869 ( 0.00%) pub fn take(&mut self) -> Self { . mem::replace(self, Token::dummy()) 28,869 ( 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 { 6,232 ( 0.00%) match &self.kind { . Interpolated(nt) => nt.span(), 3,116 ( 0.00%) _ => self.span, . } 3,116 ( 0.00%) } . . pub fn is_op(&self) -> bool { 86,607 ( 0.00%) !matches!( 28,869 ( 0.00%) self.kind, . OpenDelim(..) . | CloseDelim(..) . | Literal(..) . | DocComment(..) . | Ident(..) . | Lifetime(..) . | Interpolated(..) . | Eof . ) 28,869 ( 0.00%) } . . pub fn is_like_plus(&self) -> bool { 185,117 ( 0.00%) matches!(self.kind, BinOp(Plus) | BinOpEq(Plus)) 36,991 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of an expression. 786 ( 0.00%) pub fn can_begin_expr(&self) -> bool { 3,930 ( 0.00%) match self.uninterpolate().kind { 513 ( 0.00%) Ident(name, is_raw) => 171 ( 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 . // DotDotDot is no longer supported, but we need some way to display the error . DotDot | DotDotDot | DotDotEq | // range notation . Lt | BinOp(Shl) | // associated path . ModSep | // global path . Lifetime(..) | // labeled loop . Pound => true, // expression attributes 8 ( 0.00%) Interpolated(ref nt) => matches!(**nt, NtLiteral(..) | . NtExpr(..) | . NtBlock(..) | . NtPath(..)), . _ => false, . } 1,572 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a type. 7,164 ( 0.00%) pub fn can_begin_type(&self) -> bool { 12,656 ( 0.00%) match self.uninterpolate().kind { 8,757 ( 0.00%) Ident(name, is_raw) => 973 ( 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 759 ( 0.00%) Interpolated(ref nt) => matches!(**nt, NtTy(..) | NtPath(..)), . _ => false, . } 10,746 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a const param. . pub fn can_begin_const_arg(&self) -> bool { 5,635 ( 0.00%) match self.kind { . OpenDelim(Brace) => true, 848 ( 0.00%) Interpolated(ref nt) => matches!(**nt, NtExpr(..) | NtBlock(..) | NtLiteral(..)), 1,021 ( 0.00%) _ => self.can_begin_literal_maybe_minus(), . } 106 ( 0.00%) } . . /// 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) . || self == &Question . || self == &OpenDelim(Paren) -- line 421 ---------------------------------------- -- 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. 2,509 ( 0.00%) pub fn can_begin_literal_maybe_minus(&self) -> bool { 17,499 ( 0.00%) match self.uninterpolate().kind { . Literal(..) | BinOp(Minus) => true, 3,512 ( 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, . } 5,018 ( 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. 45,137 ( 0.00%) pub fn uninterpolate(&self) -> Cow<'_, Token> { 3,928,392 ( 0.02%) match &self.kind { 136,444 ( 0.00%) Interpolated(nt) => match **nt { 24,963 ( 0.00%) NtIdent(ident, is_raw) => { 62,428 ( 0.00%) 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), . } 45,137 ( 0.00%) } . . /// Returns an identifier if this token is an identifier. 347,012 ( 0.00%) pub fn ident(&self) -> Option<(Ident, /* is_raw */ bool)> { . let token = self.uninterpolate(); 2,644,536 ( 0.02%) match token.kind { 11,363,212 ( 0.07%) Ident(name, is_raw) => Some((Ident::new(name, token.span), is_raw)), . _ => None, . } 2,762,407 ( 0.02%) } . . /// Returns a lifetime identifier if this token is a lifetime. 3,551 ( 0.00%) pub fn lifetime(&self) -> Option { . let token = self.uninterpolate(); 33,816 ( 0.00%) match token.kind { 8,002 ( 0.00%) Lifetime(name) => Some(Ident::new(name, token.span)), . _ => None, . } 24,857 ( 0.00%) } . . /// Returns `true` if the token is an identifier. . pub fn is_ident(&self) -> bool { . self.ident().is_some() 26,129 ( 0.00%) } . . /// Returns `true` if the token is a lifetime. 13,357 ( 0.00%) pub fn is_lifetime(&self) -> bool { . self.lifetime().is_some() 26,714 ( 0.00%) } . . /// Returns `true` if the token is an identifier whose name is the given . /// string slice. 7,951 ( 0.00%) pub fn is_ident_named(&self, name: Symbol) -> bool { . self.ident().map_or(false, |(ident, _)| ident.name == name) 15,902 ( 0.00%) } . . /// Returns `true` if the token is an interpolated path. . fn is_path(&self) -> bool { 164,544 ( 0.00%) if let Interpolated(ref nt) = self.kind { 1,532 ( 0.00%) if let NtPath(..) = **nt { . return true; . } . } . false . } . . /// Would `maybe_whole_expr` in `parser.rs` return `Ok(..)`? . /// That is, is this a pre-parsed expression dropped into the token stream -- line 516 ---------------------------------------- -- line 522 ---------------------------------------- . } . } . . false . } . . // Is the token an interpolated block (`$b:block`)? . pub fn is_whole_block(&self) -> bool { 6,138 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtBlock(..) = **nt { . return true; . } . } . false 3,069 ( 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) . } . 22,312 ( 0.00%) pub fn is_qpath_start(&self) -> bool { 119,822 ( 0.00%) self == &Lt || self == &BinOp(Shl) 9,363 ( 0.00%) } . 195,020 ( 0.00%) pub fn is_path_start(&self) -> bool { 260,150 ( 0.00%) self == &ModSep . || self.is_qpath_start() . || self.is_path() . || self.is_path_segment_keyword() 37,763 ( 0.00%) || self.is_ident() && !self.is_reserved_ident() 243,775 ( 0.00%) } . . /// Returns `true` if the token is a given keyword, `kw`. 777,596 ( 0.00%) pub fn is_keyword(&self, kw: Symbol) -> bool { . self.is_non_raw_ident_where(|id| id.name == kw) 1,555,192 ( 0.01%) } . 7,659 ( 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. 16,771 ( 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. 16,771 ( 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. 16,771 ( 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`. 7,659 ( 0.00%) pub fn is_bool_lit(&self) -> bool { 15,318 ( 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. 9,032 ( 0.00%) pub fn is_non_raw_ident_where(&self, pred: impl FnOnce(Ident) -> bool) -> bool { 5,462,995 ( 0.03%) match self.ident() { 37,218 ( 0.00%) Some((id, false)) => pred(id), . _ => false, . } 11,290 ( 0.00%) } . 380,980 ( 0.00%) pub fn glue(&self, joint: &Token) -> Option { 190,490 ( 0.00%) let kind = match self.kind { 292 ( 0.00%) Eq => match joint.kind { . Eq => EqEq, . Gt => FatArrow, . _ => return None, . }, 145 ( 0.00%) Lt => match joint.kind { . Eq => Le, . Lt => BinOp(Shl), . Le => BinOpEq(Shl), . BinOp(Minus) => LArrow, . _ => return None, . }, 799 ( 0.00%) Gt => match joint.kind { . Eq => Ge, . Gt => BinOp(Shr), . Ge => BinOpEq(Shr), . _ => return None, . }, 110 ( 0.00%) Not => match joint.kind { . Eq => Ne, . _ => return None, . }, 26,449 ( 0.00%) BinOp(op) => match joint.kind { . Eq => BinOpEq(op), 3 ( 0.00%) BinOp(And) if op == And => AndAnd, 2 ( 0.00%) BinOp(Or) if op == Or => OrOr, 4,350 ( 0.00%) Gt if op == Minus => RArrow, . _ => return None, . }, 9 ( 0.00%) Dot => match joint.kind { . Dot => DotDot, . DotDot => DotDotDot, . _ => return None, . }, . DotDot => match joint.kind { . Dot => DotDotDot, . Eq => DotDotEq, . _ => return None, . }, 58,412 ( 0.00%) Colon => match joint.kind { . Colon => ModSep, . _ => return None, . }, 1,100 ( 0.00%) SingleQuote => match joint.kind { 2,475 ( 0.00%) 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, . }; . 441,896 ( 0.00%) Some(Token::new(kind, self.span.to(joint.span))) 342,882 ( 0.00%) } . } . . impl PartialEq for Token { . fn eq(&self, rhs: &TokenKind) -> bool { 2,124,314 ( 0.01%) self.kind == *rhs . } . } . 980 ( 0.00%) #[derive(Clone, Encodable, Decodable)] . /// For interpolation during macro expansion. . pub enum Nonterminal { . NtItem(P), . NtBlock(P), . NtStmt(ast::Stmt), . NtPat(P), 280 ( 0.00%) NtExpr(P), . NtTy(P), . NtIdent(Ident, /* is_raw */ bool), . NtLifetime(Ident), . NtLiteral(P), . /// Stuff inside brackets for attributes . NtMeta(P), . NtPath(ast::Path), . NtVis(ast::Visibility), -- line 686 ---------------------------------------- -- 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. 288 ( 0.00%) pub fn from_symbol( . symbol: Symbol, . edition: impl FnOnce() -> Edition, . ) -> Option { 654 ( 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, . }) 288 ( 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 ---------------------------------------- 15,365,560 ( 0.09%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/server.rs -------------------------------------------------------------------------------- Ir -- line 28 ---------------------------------------- . (type SourceFile: 'static + Clone;); . (type MultiSpan) => . (type MultiSpan: 'static;); . (type Diagnostic) => . (type Diagnostic: 'static;); . (type Span) => . (type Span: 'static + Copy + Eq + Hash;); . (fn drop(&mut self, $arg:ident: $arg_ty:ty)) => 197,970 ( 0.00%) (fn drop(&mut self, $arg: $arg_ty) { mem::drop($arg) }); . (fn clone(&mut self, $arg:ident: $arg_ty:ty) -> $ret_ty:ty) => 29,611 ( 0.00%) (fn clone(&mut self, $arg: $arg_ty) -> $ret_ty { $arg.clone() }); . ($($item:tt)*) => ($($item)*;) . } . . macro_rules! declare_server_traits { . ($($name:ident { . $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)* . }),* $(,)?) => { . pub trait Types { -- line 46 ---------------------------------------- -- line 63 ---------------------------------------- . ($($name:ident { . $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)* . }),* $(,)?) => { . impl Types for MarkedTypes { . $(type $name = Marked;)* . } . . $(impl $name for MarkedTypes { 48,828 ( 0.00%) $(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)? { 9,883,433 ( 0.06%) <_>::mark($name::$method(&mut self.0, $($arg.unmark()),*)) 48,828 ( 0.00%) })* . })* . } . } . with_api!(Self, self_, define_mark_types_impls); . . struct Dispatcher { . handle_store: HandleStore, . server: S, -- line 81 ---------------------------------------- -- line 89 ---------------------------------------- . pub trait DispatcherTrait { . // HACK(eddyb) these are here to allow `Self::$name` to work below. . $(type $name;)* . fn dispatch(&mut self, b: Buffer) -> Buffer; . } . . impl DispatcherTrait for Dispatcher> { . $(type $name = as Types>::$name;)* 25,277,470 ( 0.15%) fn dispatch(&mut self, mut b: Buffer) -> Buffer { . let Dispatcher { handle_store, server } = self; . 7,583,241 ( 0.05%) let mut reader = &b[..]; 17,694,229 ( 0.11%) match api_tags::Method::decode(&mut reader, &mut ()) { 12,238,368 ( 0.07%) $(api_tags::Method::$name(m) => match m { . $(api_tags::$name::$method => { . let mut call_method = || { 8,131,842 ( 0.05%) reverse_decode!(reader, handle_store; $($arg: $arg_ty),*); 24,414 ( 0.00%) $name::$method(server, $($arg),*) . }; . // HACK(eddyb) don't use `panic::catch_unwind` in a panic. . // If client and server happen to use the same `libstd`, . // `catch_unwind` asserts that the panic counter was 0, . // even when the closure passed to it didn't panic. . let r = if thread::panicking() { . Ok(call_method()) . } else { 11,530,340 ( 0.07%) panic::catch_unwind(panic::AssertUnwindSafe(call_method)) . .map_err(PanicMessage::from) . }; . . b.clear(); 27,718,279 ( 0.17%) r.encode(&mut b, handle_store); . })* . }),* . } 15,166,482 ( 0.09%) b 22,749,723 ( 0.14%) } . } . } . } . with_api!(Self, self_, define_dispatcher_impl); . . pub trait ExecutionStrategy { . fn run_bridge_and_client( . &self, -- line 133 ---------------------------------------- -- line 145 ---------------------------------------- . fn run_bridge_and_client( . &self, . dispatcher: &mut impl DispatcherTrait, . input: Buffer, . run_client: extern "C" fn(Bridge<'_>, D) -> Buffer, . client_data: D, . force_show_panics: bool, . ) -> Buffer { 22,749,788 ( 0.14%) let mut dispatch = |b| dispatcher.dispatch(b); . 650 ( 0.00%) run_client( 715 ( 0.00%) Bridge { cached_buffer: input, dispatch: (&mut dispatch).into(), force_show_panics }, . client_data, . ) . } . } . . // NOTE(eddyb) Two implementations are provided, the second one is a bit . // faster but neither is anywhere near as fast as same-thread execution. . -- line 164 ---------------------------------------- -- line 263 ---------------------------------------- . *state.lock().unwrap() = State::Res(b); . join_handle.thread().unpark(); . } . . join_handle.join().unwrap() . } . } . 910 ( 0.00%) fn run_server< . S: Server, . I: Encode>>, . O: for<'a, 's> DecodeMut<'a, 's, HandleStore>>, . D: Copy + Send + 'static, . >( . strategy: &impl ExecutionStrategy, . handle_counters: &'static client::HandleCounters, . server: S, . input: I, . run_client: extern "C" fn(Bridge<'_>, D) -> Buffer, . client_data: D, . force_show_panics: bool, . ) -> Result { . let mut dispatcher = 1,105 ( 0.00%) Dispatcher { handle_store: HandleStore::new(handle_counters), server: MarkedTypes(server) }; . . let mut b = Buffer::new(); 260 ( 0.00%) input.encode(&mut b, &mut dispatcher.handle_store); . 390 ( 0.00%) b = strategy.run_bridge_and_client( . &mut dispatcher, . b, . run_client, . client_data, . force_show_panics, . ); . 325 ( 0.00%) Result::decode(&mut &b[..], &mut dispatcher.handle_store) 650 ( 0.00%) } . . impl client::Client crate::TokenStream> { . pub fn run( . &self, . strategy: &impl ExecutionStrategy, . server: S, . input: S::TokenStream, . force_show_panics: bool, -- line 308 ---------------------------------------- -- line 325 ---------------------------------------- . pub fn run( . &self, . strategy: &impl ExecutionStrategy, . server: S, . input: S::TokenStream, . input2: S::TokenStream, . force_show_panics: bool, . ) -> Result { 130 ( 0.00%) let client::Client { get_handle_counters, run, f } = *self; 845 ( 0.00%) run_server( . strategy, 65 ( 0.00%) get_handle_counters(), 650 ( 0.00%) server, . ( . as Types>::TokenStream::mark(input), . as Types>::TokenStream::mark(input2), . ), . run, . f, . force_show_panics, . ) -- line 345 ---------------------------------------- 5,880,134 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/client.rs -------------------------------------------------------------------------------- Ir -- line 18 ---------------------------------------- . // FIXME(eddyb) use a reference to the `static COUNTERS`, instead of . // a wrapper `fn` pointer, once `const fn` can reference `static`s. . extern "C" fn get() -> &'static Self { . static COUNTERS: HandleCounters = HandleCounters { . $($oty: AtomicUsize::new(1),)* . $($ity: AtomicUsize::new(1),)* . }; . &COUNTERS 130 ( 0.00%) } . } . . // FIXME(eddyb) generate the definition of `HandleStore` in `server.rs`. . #[repr(C)] . #[allow(non_snake_case)] . pub(super) struct HandleStore { . $($oty: handle::OwnedStore,)* . $($ity: handle::InternedStore,)* . } . . impl HandleStore { 390 ( 0.00%) pub(super) fn new(handle_counters: &'static HandleCounters) -> Self { 3,835 ( 0.00%) HandleStore { . $($oty: handle::OwnedStore::new(&handle_counters.$oty),)* . $($ity: handle::InternedStore::new(&handle_counters.$ity),)* . } 520 ( 0.00%) } . } . . $( . #[repr(C)] . pub(crate) struct $oty(handle::Handle); . impl !Send for $oty {} . impl !Sync for $oty {} . . // Forward `Drop::drop` to the inherent `drop` method. . impl Drop for $oty { 33,316 ( 0.00%) fn drop(&mut self) { 239,985 ( 0.00%) $oty(self.0).drop(); 49,974 ( 0.00%) } . } . . impl Encode for $oty { . fn encode(self, w: &mut Writer, s: &mut S) { . let handle = self.0; . mem::forget(self); . handle.encode(w, s); . } . } . . impl DecodeMut<'_, '_, HandleStore>> . for Marked . { 2,232,360 ( 0.01%) fn decode(r: &mut Reader<'_>, s: &mut HandleStore>) -> Self { . s.$oty.take(handle::Handle::decode(r, &mut ())) 2,976,480 ( 0.02%) } . } . . impl Encode for &$oty { . fn encode(self, w: &mut Writer, s: &mut S) { 461,649 ( 0.00%) self.0.encode(w, s); . } . } . . impl<'s, S: server::Types> Decode<'_, 's, HandleStore>> . for &'s Marked . { 153,883 ( 0.00%) fn decode(r: &mut Reader<'_>, s: &'s HandleStore>) -> Self { . &s.$oty[handle::Handle::decode(r, &mut ())] 307,766 ( 0.00%) } . } . . impl Encode for &mut $oty { . fn encode(self, w: &mut Writer, s: &mut S) { 1,729,659 ( 0.01%) self.0.encode(w, s); . } . } . . impl<'s, S: server::Types> DecodeMut<'_, 's, HandleStore>> . for &'s mut Marked . { 576,553 ( 0.00%) fn decode( . r: &mut Reader<'_>, . s: &'s mut HandleStore> . ) -> Self { . &mut s.$oty[handle::Handle::decode(r, &mut ())] 1,153,106 ( 0.01%) } . } . . impl Encode>> . for Marked . { 4,547,105 ( 0.03%) fn encode(self, w: &mut Writer, s: &mut HandleStore>) { 837,766 ( 0.01%) s.$oty.alloc(self).encode(w, s); . } . } . . impl DecodeMut<'_, '_, S> for $oty { . fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { . $oty(handle::Handle::decode(r, s)) . } . } -- line 118 ---------------------------------------- -- line 129 ---------------------------------------- . fn encode(self, w: &mut Writer, s: &mut S) { . self.0.encode(w, s); . } . } . . impl DecodeMut<'_, '_, HandleStore>> . for Marked . { 488,558 ( 0.00%) fn decode(r: &mut Reader<'_>, s: &mut HandleStore>) -> Self { . s.$ity.copy(handle::Handle::decode(r, &mut ())) 977,116 ( 0.01%) } . } . . impl Encode>> . for Marked . { . fn encode(self, w: &mut Writer, s: &mut HandleStore>) { 3,875,909 ( 0.02%) s.$ity.alloc(self).encode(w, s); . } . } . . impl DecodeMut<'_, '_, S> for $ity { . fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { . $ity(handle::Handle::decode(r, s)) . } . } -- line 154 ---------------------------------------- -- line 175 ---------------------------------------- . . // FIXME(eddyb) generate these impls by pattern-matching on the . // names of methods - also could use the presence of `fn drop` . // to distinguish between 'owned and 'interned, above. . // Alternatively, special 'modes" could be listed of types in with_api . // instead of pattern matching on methods, here and in server decl. . . impl Clone for TokenStream { 88,833 ( 0.00%) fn clone(&self) -> Self { . self.clone() 88,833 ( 0.00%) } . } . . impl Clone for TokenStreamIter { . fn clone(&self) -> Self { . self.clone() . } . } . . impl Clone for Group { 37,194 ( 0.00%) fn clone(&self) -> Self { . self.clone() 37,194 ( 0.00%) } . } . . impl Clone for Literal { 9,951 ( 0.00%) fn clone(&self) -> Self { . self.clone() 9,951 ( 0.00%) } . } . . impl fmt::Debug for Literal { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . f.debug_struct("Literal") . // format the kind without quotes, as in `kind: Float` . .field("kind", &format_args!("{}", &self.debug_kind())) . .field("symbol", &self.symbol()) -- line 211 ---------------------------------------- -- line 228 ---------------------------------------- . } . } . . macro_rules! define_client_side { . ($($name:ident { . $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)*;)* . }),* $(,)?) => { . $(impl $name { 2,926,032 ( 0.02%) $(pub(crate) fn $method($($arg: $arg_ty),*) $(-> $ret_ty)* { 1,516,444 ( 0.01%) Bridge::with(|bridge| { . let mut b = bridge.cached_buffer.take(); . . b.clear(); 7,583,241 ( 0.05%) api_tags::Method::$name(api_tags::$name::$method).encode(&mut b, &mut ()); 1,808,575 ( 0.01%) reverse_encode!(b; $($arg),*); . 15,166,482 ( 0.09%) b = bridge.dispatch.call(b); . 10,454,021 ( 0.06%) let r = Result::<_, PanicMessage>::decode(&mut &b[..], &mut ()); . 30,332,964 ( 0.18%) bridge.cached_buffer = b; . 3,680,739 ( 0.02%) r.unwrap_or_else(|e| panic::resume_unwind(e.into())) . }) 2,438,360 ( 0.01%) })* . })* . } . } . with_api!(self, self, define_client_side); . . enum BridgeState<'a> { . /// No server is currently connected to this client. . NotConnected, -- line 260 ---------------------------------------- -- line 281 ---------------------------------------- . impl BridgeState<'_> { . /// Take exclusive control of the thread-local . /// `BridgeState`, and pass it to `f`, mutably. . /// The state will be restored after `f` exits, even . /// by panic, including modifications made to it by `f`. . /// . /// N.B., while `f` is running, the thread-local state . /// is `BridgeState::InUse`. 1,532,485 ( 0.01%) fn with(f: impl FnOnce(&mut BridgeState<'_>) -> R) -> R { 1,343,471 ( 0.01%) BRIDGE_STATE.with(|state| { 13,603,968 ( 0.08%) state.replace(BridgeState::InUse, |mut state| { . // FIXME(#52812) pass `f` directly to `replace` when `RefMutL` is gone . f(&mut *state) . }) . }) 1,325,816 ( 0.01%) } . } . . impl Bridge<'_> { . pub(crate) fn is_available() -> bool { 3 ( 0.00%) BridgeState::with(|state| match state { . BridgeState::Connected(_) | BridgeState::InUse => true, . BridgeState::NotConnected => false, . }) . } . . fn enter(self, f: impl FnOnce() -> R) -> R { . let force_show_panics = self.force_show_panics; . // Hide the default panic output within `proc_macro` expansions. -- line 309 ---------------------------------------- -- line 320 ---------------------------------------- . } . }); . }); . . BRIDGE_STATE.with(|state| state.set(BridgeState::Connected(self), f)) . } . . fn with(f: impl FnOnce(&mut Bridge<'_>) -> R) -> R { 17,900,898 ( 0.11%) BridgeState::with(|state| match state { . BridgeState::NotConnected => { . panic!("procedural macro API is used outside of a procedural macro"); . } . BridgeState::InUse => { . panic!("procedural macro API is used while it's already in use"); . } . BridgeState::Connected(bridge) => f(bridge), . }) -- line 336 ---------------------------------------- -- line 396 ---------------------------------------- . b.clear(); . Err::<(), _>(e).encode(&mut b, &mut ()); . }); . b . } . . impl Client crate::TokenStream> { . #[rustc_allow_const_fn_unstable(const_fn)] 1 ( 0.00%) pub const fn expand1(f: fn(crate::TokenStream) -> crate::TokenStream) -> Self { . extern "C" fn run( . bridge: Bridge<'_>, . f: impl FnOnce(crate::TokenStream) -> crate::TokenStream, . ) -> Buffer { . run_client(bridge, |input| f(crate::TokenStream(input)).0) . } 5 ( 0.00%) Client { get_handle_counters: HandleCounters::get, run, f } 1 ( 0.00%) } . } . . impl Client crate::TokenStream> { . #[rustc_allow_const_fn_unstable(const_fn)] . pub const fn expand2( . f: fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream, . ) -> Self { . extern "C" fn run( -- line 420 ---------------------------------------- 6,781,825 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/search.rs -------------------------------------------------------------------------------- Ir -- line 40 ---------------------------------------- . . impl NodeRef { . /// Looks up a given key in a (sub)tree headed by the node, recursively. . /// Returns a `Found` with the handle of the matching KV, if any. Otherwise, . /// returns a `GoDown` with the handle of the leaf edge where the key belongs. . /// . /// The result is meaningful only if the tree is ordered by key, like the tree . /// in a `BTreeMap` is. 11,133,250 ( 0.07%) pub fn search_tree( . mut self, . key: &Q, . ) -> SearchResult . where . Q: Ord, . K: Borrow, . { . loop { . self = match self.search_node(key) { . Found(handle) => return Found(handle), 4,014,228 ( 0.02%) GoDown(handle) => match handle.force() { . Leaf(leaf) => return GoDown(leaf), . Internal(internal) => internal.descend(), . }, . } . } 4,442,190 ( 0.03%) } . . /// Descends to the nearest node where the edge matching the lower bound . /// of the range is different from the edge matching the upper bound, i.e., . /// the nearest node that has at least one key contained in the range. . /// . /// If found, returns an `Ok` with that node, the strictly ascending pair of . /// edge indices in the node delimiting the range, and the corresponding . /// pair of bounds for continuing the search in the child nodes, in case -- line 73 ---------------------------------------- -- line 202 ---------------------------------------- . unsafe fn find_key_index(&self, key: &Q, start_index: usize) -> IndexResult . where . Q: Ord, . K: Borrow, . { . let node = self.reborrow(); . let keys = node.keys(); . debug_assert!(start_index <= keys.len()); 33,160,889 ( 0.20%) for (offset, k) in unsafe { keys.get_unchecked(start_index..) }.iter().enumerate() { 160,001,267 ( 0.96%) match key.cmp(k.borrow()) { . Ordering::Greater => {} . Ordering::Equal => return IndexResult::KV(start_index + offset), . Ordering::Less => return IndexResult::Edge(start_index + offset), . } . } . IndexResult::Edge(keys.len()) . } . -- line 219 ---------------------------------------- 2,306,525 ( 0.01%) -------------------------------------------------------------------------------- -- 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)] 151,773,562 ( 0.91%) pub unsafe fn drop_in_place(to_drop: *mut T) { . // Code here does not matter - this is replaced by the . // real drop glue by the compiler. . . // SAFETY: see comment above . unsafe { drop_in_place(to_drop) } . } . . /// Creates a null raw pointer. -- line 196 ---------------------------------------- -- line 366 ---------------------------------------- . let mut tmp = MaybeUninit::::uninit(); . . // Perform the swap . // SAFETY: the caller must guarantee that `x` and `y` are . // valid for writes and properly aligned. `tmp` cannot be . // overlapping either `x` or `y` because `tmp` was just allocated . // on the stack as a separate allocated object. . unsafe { 16 ( 0.00%) copy_nonoverlapping(x, tmp.as_mut_ptr(), 1); 16 ( 0.00%) copy(y, x, 1); // `x` and `y` may overlap . copy_nonoverlapping(tmp.as_ptr(), y, 1); . } . } . . /// Swaps `count * size_of::()` bytes between the two regions of memory . /// beginning at `x` and `y`. The two regions must *not* overlap. . /// . /// # Safety -- line 383 ---------------------------------------- -- line 448 ---------------------------------------- . return; . } . } . . // Direct swapping, for the cases not going through the block optimization. . // SAFETY: the caller must guarantee that `x` and `y` are valid . // for writes, properly aligned, and non-overlapping. . unsafe { 330 ( 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 { 13,213,731 ( 0.08%) copy_nonoverlapping(src, tmp.as_mut_ptr(), 1); 77,816,858 ( 0.46%) 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 { 106,198,537 ( 0.63%) 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. 89,300 ( 0.00%) return wrapping_sub( 191,944 ( 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 { 3,145,314 ( 0.02%) 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 ---------------------------------------- 26,367,172 ( 0.16%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/map.rs -------------------------------------------------------------------------------- Ir -- line 165 ---------------------------------------- . #[rustc_insignificant_dtor] . pub struct BTreeMap { . root: Option>, . length: usize, . } . . #[stable(feature = "btree_drop", since = "1.7.0")] . unsafe impl<#[may_dangle] K, #[may_dangle] V> Drop for BTreeMap { 1,189,376 ( 0.01%) fn drop(&mut self) { . drop(unsafe { ptr::read(self) }.into_iter()) 1,249,684 ( 0.01%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for BTreeMap { . fn clone(&self) -> BTreeMap { 42 ( 0.00%) fn clone_subtree<'a, K: Clone, V: Clone>( . node: NodeRef, K, V, marker::LeafOrInternal>, . ) -> BTreeMap . where . K: 'a, . V: 'a, . { 5 ( 0.00%) match node.force() { . Leaf(leaf) => { 15 ( 0.00%) let mut out_tree = BTreeMap { root: Some(Root::new()), length: 0 }; . . { . let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped . let mut out_node = match root.borrow_mut().force() { . Leaf(leaf) => leaf, . Internal(_) => unreachable!(), . }; . . let mut in_edge = leaf.first_edge(); . while let Ok(kv) = in_edge.right_kv() { . let (k, v) = kv.into_kv(); . in_edge = kv.right_edge(); . 16 ( 0.00%) out_node.push(k.clone(), v.clone()); 42 ( 0.00%) out_tree.length += 1; . } . } . 23 ( 0.00%) out_tree . } . Internal(internal) => { . let mut out_tree = clone_subtree(internal.first_edge().descend()); . . { . let out_root = BTreeMap::ensure_is_owned(&mut out_tree.root); . let mut out_node = out_root.push_internal_level(); . let mut in_edge = internal.first_edge(); -- line 217 ---------------------------------------- -- line 235 ---------------------------------------- . out_node.push(k, v, subroot.unwrap_or_else(Root::new)); . out_tree.length += 1 + sublength; . } . } . . out_tree . } . } 40 ( 0.00%) } . 6 ( 0.00%) if self.is_empty() { . BTreeMap::new() . } else { 14 ( 0.00%) clone_subtree(self.root.as_ref().unwrap().reborrow()) // unwrap succeeds because not empty . } . } . } . . impl super::Recover for BTreeMap . where . K: Borrow + Ord, . Q: Ord, -- line 256 ---------------------------------------- -- line 515 ---------------------------------------- . /// . /// // entries can now be inserted into the empty map . /// map.insert(1, "a"); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")] . #[must_use] . pub const fn new() -> BTreeMap { 646,795 ( 0.00%) BTreeMap { root: None, length: 0 } . } . . /// Clears the map, removing all elements. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 531 ---------------------------------------- -- line 560 ---------------------------------------- . /// assert_eq!(map.get(&2), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn get(&self, key: &Q) -> Option<&V> . where . K: Borrow + Ord, . Q: Ord, . { 1,036,052 ( 0.01%) let root_node = self.root.as_ref()?.reborrow(); 4,593,325 ( 0.03%) match root_node.search_tree(key) { 12,512 ( 0.00%) Found(handle) => Some(handle.into_kv().1), . GoDown(_) => None, . } . } . . /// Returns the key-value pair corresponding to the supplied key. . /// . /// The supplied key may be any borrowed form of the map's key type, but the ordering . /// on the borrowed form *must* match the ordering on the key type. -- line 578 ---------------------------------------- -- line 814 ---------------------------------------- . /// ``` . // See `get` for implementation notes, this is basically a copy-paste with mut's added . #[stable(feature = "rust1", since = "1.0.0")] . pub fn get_mut(&mut self, key: &Q) -> Option<&mut V> . where . K: Borrow + Ord, . Q: Ord, . { 576,553 ( 0.00%) let root_node = self.root.as_mut()?.borrow_mut(); 4,035,871 ( 0.02%) match root_node.search_tree(key) { . Found(handle) => Some(handle.into_val_mut()), . GoDown(_) => None, . } . } . . /// Inserts a key-value pair into the map. . /// . /// If the map did not have this key present, `None` is returned. -- line 831 ---------------------------------------- -- line 848 ---------------------------------------- . /// assert_eq!(map.insert(37, "a"), None); . /// assert_eq!(map.is_empty(), false); . /// . /// map.insert(37, "b"); . /// assert_eq!(map.insert(37, "c"), Some("b")); . /// assert_eq!(map[&37], "c"); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 8,524,782 ( 0.05%) pub fn insert(&mut self, key: K, value: V) -> Option . where . K: Ord, . { 456 ( 0.00%) match self.entry(key) { . Occupied(mut entry) => Some(entry.insert(value)), . Vacant(entry) => { 10,708,581 ( 0.06%) entry.insert(value); 293,821 ( 0.00%) None . } . } 7,491,750 ( 0.04%) } . . /// Tries to insert a key-value pair into the map, and returns . /// a mutable reference to the value in the entry. . /// . /// If the map already had this key present, nothing is updated, and . /// an error containing the occupied entry and the value is returned. . /// . /// # Examples -- line 875 ---------------------------------------- -- line 914 ---------------------------------------- . /// use std::collections::BTreeMap; . /// . /// let mut map = BTreeMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.remove(&1), Some("a")); . /// assert_eq!(map.remove(&1), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 1,560,588 ( 0.01%) pub fn remove(&mut self, key: &Q) -> Option . where . K: Borrow + Ord, . Q: Ord, . { 2,178,801 ( 0.01%) self.remove_entry(key).map(|(_, v)| v) 1,850,257 ( 0.01%) } . . /// Removes a key from the map, returning the stored key and value if the key . /// was previously in the map. . /// . /// The key may be any borrowed form of the map's key type, but the ordering . /// on the borrowed form *must* match the ordering on the key type. . /// . /// # Examples -- line 936 ---------------------------------------- -- line 947 ---------------------------------------- . /// ``` . #[stable(feature = "btreemap_remove_entry", since = "1.45.0")] . pub fn remove_entry(&mut self, key: &Q) -> Option<(K, V)> . where . K: Borrow + Ord, . Q: Ord, . { . let (map, dormant_map) = DormantMutRef::new(self); 1,039,712 ( 0.01%) let root_node = map.root.as_mut()?.borrow_mut(); 2,743,718 ( 0.02%) match root_node.search_tree(key) { . Found(handle) => { 8,164,739 ( 0.05%) Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_entry()) 206,924 ( 0.00%) } . GoDown(_) => None, . } . } . . /// Retains only the elements specified by the predicate. . /// . /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`. . /// The elements are visited in ascending key order. -- line 967 ---------------------------------------- -- line 1135 ---------------------------------------- . /// // count the number of occurrences of letters in the vec . /// for x in ["a", "b", "a", "c", "a", "b"] { . /// *count.entry(x).or_insert(0) += 1; . /// } . /// . /// assert_eq!(count["a"], 3); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 10 ( 0.00%) pub fn entry(&mut self, key: K) -> Entry<'_, K, V> . where . K: Ord, . { . // FIXME(@porglezomp) Avoid allocating if we don't insert . let (map, dormant_map) = DormantMutRef::new(self); . let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut(); 403,978 ( 0.00%) match root_node.search_tree(&key) { 8,056 ( 0.00%) Found(handle) => Occupied(OccupiedEntry { handle, dormant_map, _marker: PhantomData }), . GoDown(handle) => { 99,550 ( 0.00%) Vacant(VacantEntry { key, handle, dormant_map, _marker: PhantomData }) . } . } 9 ( 0.00%) } . . /// Splits the collection into two at the given key. Returns everything after the given key, . /// including the key. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 1164 ---------------------------------------- -- line 1307 ---------------------------------------- . } . . /// Makes a `BTreeMap` from a sorted iterator. . pub(crate) fn bulk_build_from_sorted_iter(iter: I) -> Self . where . K: Ord, . I: IntoIterator, . { 2 ( 0.00%) let mut root = Root::new(); 1 ( 0.00%) let mut length = 0; 5 ( 0.00%) root.bulk_push(DedupSortedIter::new(iter.into_iter()), &mut length); 2 ( 0.00%) BTreeMap { root: Some(root), length } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, K, V> IntoIterator for &'a BTreeMap { . type Item = (&'a K, &'a V); . type IntoIter = Iter<'a, K, V>; . -- line 1326 ---------------------------------------- -- line 1328 ---------------------------------------- . self.iter() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> { . type Item = (&'a K, &'a V); . 12 ( 0.00%) fn next(&mut self) -> Option<(&'a K, &'a V)> { 580,432 ( 0.00%) if self.length == 0 { . None . } else { 231,403 ( 0.00%) self.length -= 1; . Some(unsafe { self.range.next_unchecked() }) . } 19 ( 0.00%) } . . fn size_hint(&self) -> (usize, Option) { . (self.length, Some(self.length)) . } . . fn last(mut self) -> Option<(&'a K, &'a V)> { . self.next_back() . } -- line 1351 ---------------------------------------- -- line 1460 ---------------------------------------- . . #[stable(feature = "rust1", since = "1.0.0")] . impl IntoIterator for BTreeMap { . type Item = (K, V); . type IntoIter = IntoIter; . . fn into_iter(self) -> IntoIter { . let mut me = ManuallyDrop::new(self); 494,564 ( 0.00%) if let Some(root) = me.root.take() { . let full_range = root.into_dying().full_range(); . 6 ( 0.00%) IntoIter { range: full_range, length: me.length } . } else { 543,584 ( 0.00%) IntoIter { range: LazyLeafRange::none(), length: 0 } . } . } . } . . #[stable(feature = "btree_drop", since = "1.7.0")] . impl Drop for IntoIter { 30,512 ( 0.00%) fn drop(&mut self) { . struct DropGuard<'a, K, V>(&'a mut IntoIter); . . impl<'a, K, V> Drop for DropGuard<'a, K, V> { . fn drop(&mut self) { . // Continue the same loop we perform below. This only runs when unwinding, so we . // don't have to care about panics this time (they'll abort). . while let Some(kv) = self.0.dying_next() { . // SAFETY: we consume the dying handle immediately. . unsafe { kv.drop_key_val() }; . } . } . } . 676,207 ( 0.00%) while let Some(kv) = self.dying_next() { . let guard = DropGuard(self); . // SAFETY: we don't touch the tree before consuming the dying handle. 33,736 ( 0.00%) unsafe { kv.drop_key_val() }; . mem::forget(guard); . } 30,512 ( 0.00%) } . } . . impl IntoIter { . /// Core of a `next` method returning a dying KV handle, . /// invalidated by further calls to this function and some others. 776,833 ( 0.00%) fn dying_next( . &mut self, . ) -> Option, marker::KV>> { 943,486 ( 0.01%) if self.length == 0 { . self.range.deallocating_end(); 154,334 ( 0.00%) None . } else { 248,794 ( 0.00%) self.length -= 1; 139,115 ( 0.00%) Some(unsafe { self.range.deallocating_next_unchecked() }) . } 776,829 ( 0.00%) } . . /// Core of a `next_back` method returning a dying KV handle, . /// invalidated by further calls to this function and some others. . fn dying_next_back( . &mut self, . ) -> Option, marker::KV>> { . if self.length == 0 { . self.range.deallocating_end(); -- line 1524 ---------------------------------------- -- line 1529 ---------------------------------------- . } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for IntoIter { . type Item = (K, V); . 6,811 ( 0.00%) fn next(&mut self) -> Option<(K, V)> { . // SAFETY: we consume the dying handle immediately. . self.dying_next().map(unsafe { |kv| kv.into_key_val() }) 7,784 ( 0.00%) } . . fn size_hint(&self) -> (usize, Option) { 839 ( 0.00%) (self.length, Some(self.length)) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl DoubleEndedIterator for IntoIter { . fn next_back(&mut self) -> Option<(K, V)> { . // SAFETY: we consume the dying handle immediately. . self.dying_next_back().map(unsafe { |kv| kv.into_key_val() }) -- line 1551 ---------------------------------------- -- line 1562 ---------------------------------------- . #[stable(feature = "fused", since = "1.26.0")] . impl FusedIterator for IntoIter {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, K, V> Iterator for Keys<'a, K, V> { . type Item = &'a K; . . fn next(&mut self) -> Option<&'a K> { 10 ( 0.00%) self.inner.next().map(|(k, _)| k) . } . . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . . fn last(mut self) -> Option<&'a K> { . self.next_back() -- line 1578 ---------------------------------------- -- line 2089 ---------------------------------------- . /// println!("{}: {}", key, value); . /// } . /// . /// let (first_key, first_value) = map.iter().next().unwrap(); . /// assert_eq!((*first_key, *first_value), (1, "a")); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn iter(&self) -> Iter<'_, K, V> { 813,160 ( 0.00%) if let Some(root) = &self.root { . let full_range = root.reborrow().full_range(); . 15 ( 0.00%) Iter { range: full_range, length: self.length } . } else { 6 ( 0.00%) Iter { range: LazyLeafRange::none(), length: 0 } . } . } . . /// Gets a mutable iterator over the entries of the map, sorted by key. . /// . /// # Examples . /// . /// Basic usage: -- line 2110 ---------------------------------------- -- line 2149 ---------------------------------------- . /// a.insert(2, "b"); . /// a.insert(1, "a"); . /// . /// let keys: Vec<_> = a.keys().cloned().collect(); . /// assert_eq!(keys, [1, 2]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn keys(&self) -> Keys<'_, K, V> { 7,719 ( 0.00%) Keys { inner: self.iter() } . } . . /// Gets an iterator over the values of the map, in order by key. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 2165 ---------------------------------------- -- line 2217 ---------------------------------------- . /// assert_eq!(a.len(), 0); . /// a.insert(1, "a"); . /// assert_eq!(a.len(), 1); . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")] . pub const fn len(&self) -> usize { 3 ( 0.00%) self.length . } . . /// Returns `true` if the map contains no elements. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 2233 ---------------------------------------- -- line 2238 ---------------------------------------- . /// assert!(a.is_empty()); . /// a.insert(1, "a"); . /// assert!(!a.is_empty()); . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")] . pub const fn is_empty(&self) -> bool { 76,863 ( 0.00%) self.len() == 0 . } . . /// If the root node is the empty (non-allocated) root node, allocate our . /// own node. Is an associated function to avoid borrowing the entire BTreeMap. . fn ensure_is_owned(root: &mut Option>) -> &mut Root { . root.get_or_insert_with(Root::new) . } . } -- line 2254 ---------------------------------------- 3,421,264 ( 0.02%) -------------------------------------------------------------------------------- -- 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); . 218,403 ( 0.00%) if count == 8 { . ptr::copy_nonoverlapping(src, dst, 8); . return; . } . . let mut i = 0; 231,280 ( 0.00%) if i + 3 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 4); . i += 4; . } . 492,035 ( 0.00%) if i + 1 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 2); 67,364 ( 0.00%) i += 2 . } . 231,280 ( 0.00%) if i < count { 168,677 ( 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::(); 3,190,346 ( 0.02%) let nbuf = self.nbuf; . debug_assert!(size <= 8); . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + size < BUFFER_WITH_SPILL_SIZE); . 21,937,361 ( 0.13%) 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); . } . 6,928,059 ( 0.04%) self.nbuf = nbuf + size; . . return; . } . 1,170,601 ( 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)] 349,179 ( 0.00%) unsafe fn short_write_process_buffer(&mut self, x: T) { . let size = mem::size_of::(); 349,179 ( 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 { 3,491,790 ( 0.02%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 2,793,432 ( 0.02%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 3,142,611 ( 0.02%) 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. 1,662,303 ( 0.01%) self.nbuf = if size == 1 { 0 } else { nbuf + size - BUFFER_SIZE }; 1,396,716 ( 0.01%) self.processed += BUFFER_SIZE; 698,358 ( 0.00%) } . . // A write function for byte slices. . #[inline] . fn slice_write(&mut self, msg: &[u8]) { . let length = msg.len(); 25,016 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(nbuf < BUFFER_SIZE); . 719,210 ( 0.00%) if nbuf + length < BUFFER_SIZE { . unsafe { . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . 263,296 ( 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); . } . } . 132,919 ( 0.00%) self.nbuf = nbuf + length; . . return; . } . 128,232 ( 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)] 77,625 ( 0.00%) unsafe fn slice_write_process_buffer(&mut self, msg: &[u8]) { . let length = msg.len(); 15,525 ( 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. 46,575 ( 0.00%) let valid_in_elem = nbuf % ELEM_SIZE; 15,525 ( 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. 31,050 ( 0.00%) let last = nbuf / ELEM_SIZE + 1; . . for i in 0..last { 105,570 ( 0.00%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 121,095 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 211,140 ( 0.00%) self.state.v0 ^= elem; . } . . // Process the remaining element-sized chunks of input. . let mut processed = needed_in_elem; 31,050 ( 0.00%) let input_left = length - processed; 27,162 ( 0.00%) let elems_left = input_left / ELEM_SIZE; . let extra_bytes_left = input_left % ELEM_SIZE; . . for _ in 0..elems_left { 36,123 ( 0.00%) let elem = (msg.as_ptr().add(processed) as *const u64).read_unaligned().to_le(); 36,123 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 36,123 ( 0.00%) self.state.v0 ^= elem; 72,246 ( 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); . 15,525 ( 0.00%) self.nbuf = extra_bytes_left; 77,625 ( 0.00%) self.processed += nbuf + processed; 93,150 ( 0.00%) } . . #[inline] . pub fn finish128(mut self) -> (u64, u64) { . debug_assert!(self.nbuf < BUFFER_SIZE); . . // Process full elements in buffer. 173,703 ( 0.00%) let last = self.nbuf / ELEM_SIZE; . . // Since we're consuming self, avoid updating members for a potential . // performance gain. 231,604 ( 0.00%) let mut state = self.state; . . for i in 0..last { 143,792 ( 0.00%) let elem = unsafe { self.buf.get_unchecked(i).assume_init().to_le() }; 143,792 ( 0.00%) state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut state); 143,792 ( 0.00%) state.v0 ^= elem; . } . . // Get remaining partial element. 115,802 ( 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); 45,133 ( 0.00%) self.buf.get_unchecked(last).assume_init().to_le() . } . } else { . 0 . }; . . // Finalize the hash. 158,258 ( 0.00%) let length = self.processed + self.nbuf; 110,442 ( 0.00%) let b: u64 = ((length as u64 & 0xff) << 56) | elem; . 55,221 ( 0.00%) state.v3 ^= b; . Sip24Rounds::c_rounds(&mut state); 55,221 ( 0.00%) state.v0 ^= b; . 55,221 ( 0.00%) state.v2 ^= 0xee; . Sip24Rounds::d_rounds(&mut state); 181,616 ( 0.00%) let _0 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; . 71,170 ( 0.00%) state.v1 ^= 0xdd; . Sip24Rounds::d_rounds(&mut state); 71,170 ( 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) { 12,932,306 ( 0.08%) compress!(state); 13,900,799 ( 0.08%) compress!(state); . } . . #[inline] . fn d_rounds(state: &mut State) { 363,224 ( 0.00%) compress!(state); 363,224 ( 0.00%) compress!(state); 363,224 ( 0.00%) compress!(state); 308,005 ( 0.00%) compress!(state); . } . } 2,508,517 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/decoder.rs -------------------------------------------------------------------------------- Ir -- line 176 ---------------------------------------- . } . fn sess(self) -> Option<&'tcx Session> { . None . } . fn tcx(self) -> Option> { . None . } . 17,226 ( 0.00%) fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> { 5,742 ( 0.00%) let tcx = self.tcx(); 824,862 ( 0.00%) DecodeContext { 94,590 ( 0.00%) opaque: opaque::Decoder::new(self.blob(), pos), 5,742 ( 0.00%) cdata: self.cdata(), . blob: self.blob(), 32,450 ( 0.00%) sess: self.sess().or(tcx.map(|tcx| tcx.sess)), . tcx, . last_source_file_index: 0, . lazy_state: LazyState::NoNode, . alloc_decoding_session: self . .cdata() 85,444 ( 0.00%) .map(|cdata| cdata.cdata.alloc_decoding_state.new_decoding_session()), . } 17,226 ( 0.00%) } . } . . impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob { . #[inline] . fn blob(self) -> &'a MetadataBlob { . self . } . } -- line 206 ---------------------------------------- -- line 255 ---------------------------------------- . } . #[inline] . fn tcx(self) -> Option> { . Some(self.1) . } . } . . impl<'a, 'tcx, T: Decodable>> Lazy { 120,539 ( 0.00%) fn decode>(self, metadata: M) -> T { 71,656 ( 0.00%) let mut dcx = metadata.decoder(self.position.get()); 249,517 ( 0.00%) dcx.lazy_state = LazyState::NodeStart(self.position); 80,142 ( 0.00%) T::decode(&mut dcx) 153,772 ( 0.00%) } . } . . impl<'a: 'x, 'tcx: 'x, 'x, T: Decodable>> Lazy<[T]> { . fn decode>( . self, . metadata: M, . ) -> impl ExactSizeIterator + Captures<'a> + Captures<'tcx> + 'x { 203 ( 0.00%) let mut dcx = metadata.decoder(self.position.get()); 58 ( 0.00%) dcx.lazy_state = LazyState::NodeStart(self.position); 568,325 ( 0.00%) (0..self.meta).map(move |_| T::decode(&mut dcx)) . } . } . . impl<'a, 'tcx> DecodeContext<'a, 'tcx> { . #[inline] . fn tcx(&self) -> TyCtxt<'tcx> { . debug_assert!(self.tcx.is_some(), "missing TyCtxt in DecodeContext"); . self.tcx.unwrap() -- line 285 ---------------------------------------- -- line 292 ---------------------------------------- . . #[inline] . pub fn cdata(&self) -> CrateMetadataRef<'a> { . debug_assert!(self.cdata.is_some(), "missing CrateMetadata in DecodeContext"); . self.cdata.unwrap() . } . . fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum { 222,703 ( 0.00%) if cnum == LOCAL_CRATE { self.cdata().cnum } else { self.cdata().cnum_map[cnum] } . } . 64,587 ( 0.00%) fn read_lazy_with_meta(&mut self, meta: T::Meta) -> Lazy { . let distance = self.read_usize(); 61,549 ( 0.00%) let position = match self.lazy_state { . LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"), 14,968 ( 0.00%) LazyState::NodeStart(start) => { . let start = start.get(); 29,936 ( 0.00%) assert!(distance <= start); . start - distance . } 9,987 ( 0.00%) LazyState::Previous(last_pos) => last_pos.get() + distance, . }; 36,594 ( 0.00%) self.lazy_state = LazyState::Previous(NonZeroUsize::new(position).unwrap()); . Lazy::from_position_and_meta(NonZeroUsize::new(position).unwrap(), meta) 64,587 ( 0.00%) } . . #[inline] . pub fn read_raw_bytes(&mut self, len: usize) -> &'a [u8] { . self.opaque.read_raw_bytes(len) . } . } . . impl<'a, 'tcx> TyDecoder<'tcx> for DecodeContext<'a, 'tcx> { -- line 324 ---------------------------------------- -- line 326 ---------------------------------------- . . #[inline] . fn tcx(&self) -> TyCtxt<'tcx> { . self.tcx.expect("missing TyCtxt in DecodeContext") . } . . #[inline] . fn peek_byte(&self) -> u8 { 203,905 ( 0.00%) self.opaque.data[self.opaque.position()] . } . . #[inline] . fn position(&self) -> usize { . self.opaque.position() . } . 160,363 ( 0.00%) fn cached_ty_for_shorthand(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx> . where . F: FnOnce(&mut Self) -> Ty<'tcx>, . { 22,909 ( 0.00%) let tcx = self.tcx(); . 22,909 ( 0.00%) let key = ty::CReaderCacheKey { cnum: Some(self.cdata().cnum), pos: shorthand }; . 69,068 ( 0.00%) if let Some(&ty) = tcx.ty_rcache.borrow().get(&key) { . return ty; . } . 5,642 ( 0.00%) let ty = or_insert_with(self); . tcx.ty_rcache.borrow_mut().insert(key, ty); . ty 206,181 ( 0.00%) } . . fn with_position(&mut self, pos: usize, f: F) -> R . where . F: FnOnce(&mut Self) -> R, . { . let new_opaque = opaque::Decoder::new(self.opaque.data, pos); . let old_opaque = mem::replace(&mut self.opaque, new_opaque); . let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode); . let r = f(self); 31,295 ( 0.00%) self.opaque = old_opaque; 6,259 ( 0.00%) self.lazy_state = old_state; . r . } . . fn decode_alloc_id(&mut self) -> rustc_middle::mir::interpret::AllocId { . if let Some(alloc_decoding_session) = self.alloc_decoding_session { . alloc_decoding_session.decode_alloc_id(self) . } else { . bug!("Attempting to decode interpret::AllocId without CrateMetadata") . } . } . } . . impl<'a, 'tcx> Decodable> for CrateNum { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> CrateNum { 103,370 ( 0.00%) let cnum = CrateNum::from_u32(d.read_u32()); . d.map_encoded_cnum_to_current(cnum) . } . } . . impl<'a, 'tcx> Decodable> for DefIndex { 354 ( 0.00%) fn decode(d: &mut DecodeContext<'a, 'tcx>) -> DefIndex { 190,319 ( 0.00%) DefIndex::from_u32(d.read_u32()) 708 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for ExpnIndex { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> ExpnIndex { . ExpnIndex::from_u32(d.read_u32()) . } . } . . impl<'a, 'tcx> Decodable> for SyntaxContext { 1,315,480 ( 0.01%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> SyntaxContext { 328,870 ( 0.00%) let cdata = decoder.cdata(); 328,870 ( 0.00%) let sess = decoder.sess.unwrap(); 657,740 ( 0.00%) let cname = cdata.root.name; . rustc_span::hygiene::decode_syntax_context(decoder, &cdata.hygiene_context, |_, id| { . debug!("SpecializedDecoder: decoding {}", id); 7,036 ( 0.00%) cdata . .root . .syntax_contexts . .get(cdata, id) . .unwrap_or_else(|| panic!("Missing SyntaxContext {:?} for crate {:?}", id, cname)) . .decode((cdata, sess)) . }) 1,644,350 ( 0.01%) } . } . . impl<'a, 'tcx> Decodable> for ExpnId { 28,007 ( 0.00%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> ExpnId { 4,001 ( 0.00%) let local_cdata = decoder.cdata(); 4,001 ( 0.00%) let sess = decoder.sess.unwrap(); . . let cnum = CrateNum::decode(decoder); . let index = u32::decode(decoder); . . let expn_id = rustc_span::hygiene::decode_expn_id(cnum, index, |expn_id| { . let ExpnId { krate: cnum, local_id: index } = expn_id; . // Lookup local `ExpnData`s in our own crate data. Foreign `ExpnData`s . // are stored in the owning crate, to avoid duplication. . debug_assert_ne!(cnum, LOCAL_CRATE); 1,784 ( 0.00%) let crate_data = if cnum == local_cdata.cnum { . local_cdata . } else { . local_cdata.cstore.get_crate_data(cnum) . }; 8,920 ( 0.00%) let expn_data = crate_data . .root . .expn_data . .get(crate_data, index) . .unwrap() . .decode((crate_data, sess)); 8,920 ( 0.00%) let expn_hash = crate_data . .root . .expn_hashes . .get(crate_data, index) . .unwrap() . .decode((crate_data, sess)); 17,840 ( 0.00%) (expn_data, expn_hash) . }); . expn_id 32,008 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for Span { 2,588,744 ( 0.02%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Span { 323,593 ( 0.00%) let ctxt = SyntaxContext::decode(decoder); . let tag = u8::decode(decoder); . 647,186 ( 0.00%) if tag == TAG_PARTIAL_SPAN { . return DUMMY_SP.with_ctxt(ctxt); . } . . debug_assert!(tag == TAG_VALID_SPAN_LOCAL || tag == TAG_VALID_SPAN_FOREIGN); . . let lo = BytePos::decode(decoder); . let len = BytePos::decode(decoder); . let hi = lo + len; . 970,485 ( 0.01%) let Some(sess) = decoder.sess else { . bug!("Cannot decode Span without Session.") . }; . . // There are two possibilities here: . // 1. This is a 'local span', which is located inside a `SourceFile` . // that came from this crate. In this case, we use the source map data . // encoded in this crate. This branch should be taken nearly all of the time. . // 2. This is a 'foreign span', which is located inside a `SourceFile` -- line 476 ---------------------------------------- -- line 492 ---------------------------------------- . // a transitive dependency. . // . // When we encode a foreign span, we adjust its 'lo' and 'high' values . // to be based on the *foreign* crate (e.g. crate C), not the crate . // we are writing metadata for (e.g. crate B). This allows us to . // treat the 'local' and 'foreign' cases almost identically during deserialization: . // we can call `imported_source_files` for the proper crate, and binary search . // through the returned slice using our span. 661,859 ( 0.00%) let imported_source_files = if tag == TAG_VALID_SPAN_LOCAL { . decoder.cdata().imported_source_files(sess) . } else { . // When we encode a proc-macro crate, all `Span`s should be encoded . // with `TAG_VALID_SPAN_LOCAL` 217 ( 0.00%) if decoder.cdata().root.is_proc_macro_crate() { . // Decode `CrateNum` as u32 - using `CrateNum::decode` will ICE . // since we don't have `cnum_map` populated. . let cnum = u32::decode(decoder); . panic!( . "Decoding of crate {:?} tried to access proc-macro dep {:?}", . decoder.cdata().root.name, . cnum . ); -- line 513 ---------------------------------------- -- line 518 ---------------------------------------- . "SpecializedDecoder::specialized_decode: loading source files from cnum {:?}", . cnum . ); . . // Decoding 'foreign' spans should be rare enough that it's . // not worth it to maintain a per-CrateNum cache for `last_source_file_index`. . // We just set it to 0, to ensure that we don't try to access something out . // of bounds for our initial 'guess' 434 ( 0.00%) decoder.last_source_file_index = 0; . 217 ( 0.00%) let foreign_data = decoder.cdata().cstore.get_crate_data(cnum); . foreign_data.imported_source_files(sess) . }; . . let source_file = { . // Optimize for the case that most spans within a translated item . // originate from the same source_file. 970,485 ( 0.01%) let last_source_file = &imported_source_files[decoder.last_source_file_index]; . 1,292,644 ( 0.01%) if lo >= last_source_file.original_start_pos && lo <= last_source_file.original_end_pos . { . last_source_file . } else { . let index = imported_source_files . .binary_search_by_key(&lo, |source_file| source_file.original_start_pos) 29,726 ( 0.00%) .unwrap_or_else(|index| index - 1); . . // Don't try to cache the index for foreign spans, . // as this would require a map from CrateNums to indices 14,869 ( 0.00%) if tag == TAG_VALID_SPAN_LOCAL { 14,658 ( 0.00%) decoder.last_source_file_index = index; . } 29,738 ( 0.00%) &imported_source_files[index] . } . }; . . // Make sure our binary search above is correct. . debug_assert!( . lo >= source_file.original_start_pos && lo <= source_file.original_end_pos, . "Bad binary search: lo={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}", . lo, -- line 558 ---------------------------------------- -- line 565 ---------------------------------------- . hi >= source_file.original_start_pos && hi <= source_file.original_end_pos, . "Bad binary search: hi={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}", . hi, . source_file.original_start_pos, . source_file.original_end_pos . ); . . let lo = 1,293,980 ( 0.01%) (lo + source_file.translated_source_file.start_pos) - source_file.original_start_pos; . let hi = . (hi + source_file.translated_source_file.start_pos) - source_file.original_start_pos; . . // Do not try to decode parent for foreign spans. . Span::new(lo, hi, ctxt, None) 2,912,337 ( 0.02%) } . } . . impl<'a, 'tcx> Decodable> for &'tcx [thir::abstract_const::Node<'tcx>] { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Self { . ty::codec::RefDecodable::decode(d) . } . } . -- line 587 ---------------------------------------- -- line 590 ---------------------------------------- . ty::codec::RefDecodable::decode(d) . } . } . . impl<'a, 'tcx, T: Decodable>> Decodable> . for Lazy . { . fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self { 27,227 ( 0.00%) decoder.read_lazy_with_meta(()) . } . } . . impl<'a, 'tcx, T: Decodable>> Decodable> . for Lazy<[T]> . { . fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self { . let len = decoder.read_usize(); 18,687 ( 0.00%) if len == 0 { Lazy::empty() } else { decoder.read_lazy_with_meta(len) } . } . } . . impl<'a, 'tcx, I: Idx, T: Decodable>> Decodable> . for Lazy> . where . Option: FixedSizeEncoding, . { . fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self { . let len = decoder.read_usize(); 11,830 ( 0.00%) decoder.read_lazy_with_meta(len) . } . } . . implement_ty_decoder!(DecodeContext<'a, 'tcx>); . . impl<'tcx> MetadataBlob { . crate fn new(metadata_ref: MetadataRef) -> MetadataBlob { . MetadataBlob(Lrc::new(metadata_ref)) -- line 626 ---------------------------------------- -- line 630 ---------------------------------------- . self.blob().starts_with(METADATA_HEADER) . } . . crate fn get_rustc_version(&self) -> String { . Lazy::::from_position(NonZeroUsize::new(METADATA_HEADER.len() + 4).unwrap()) . .decode(self) . } . 210 ( 0.00%) crate fn get_root(&self) -> CrateRoot<'tcx> { 70 ( 0.00%) let slice = &self.blob()[..]; . let offset = METADATA_HEADER.len(); 350 ( 0.00%) let pos = (((slice[offset + 0] as u32) << 24) 140 ( 0.00%) | ((slice[offset + 1] as u32) << 16) 280 ( 0.00%) | ((slice[offset + 2] as u32) << 8) 210 ( 0.00%) | ((slice[offset + 3] as u32) << 0)) as usize; . Lazy::>::from_position(NonZeroUsize::new(pos).unwrap()).decode(self) 350 ( 0.00%) } . . crate fn list_crate_metadata(&self, out: &mut dyn io::Write) -> io::Result<()> { . let root = self.get_root(); . writeln!(out, "Crate info:")?; . writeln!(out, "name {}{}", root.name, root.extra_filename)?; . writeln!(out, "hash {} stable_crate_id {:?}", root.hash, root.stable_crate_id)?; . writeln!(out, "proc_macro {:?}", root.proc_macro_data.is_some())?; . writeln!(out, "=External Dependencies=")?; -- line 654 ---------------------------------------- -- line 666 ---------------------------------------- . } . write!(out, "\n")?; . Ok(()) . } . } . . impl CrateRoot<'_> { . crate fn is_proc_macro_crate(&self) -> bool { 43 ( 0.00%) self.proc_macro_data.is_some() . } . . crate fn name(&self) -> Symbol { 4 ( 0.00%) self.name . } . . crate fn hash(&self) -> Svh { 22 ( 0.00%) self.hash . } . . crate fn stable_crate_id(&self) -> StableCrateId { 47 ( 0.00%) self.stable_crate_id . } . . crate fn triple(&self) -> &TargetTriple { . &self.triple . } . . crate fn decode_crate_deps<'a>( . &self, . metadata: &'a MetadataBlob, . ) -> impl ExactSizeIterator + Captures<'a> { 42 ( 0.00%) self.crate_deps.decode(metadata) . } . } . . impl<'a, 'tcx> CrateMetadataRef<'a> { 7 ( 0.00%) fn raw_proc_macro(self, id: DefIndex) -> &'a ProcMacro { . // DefIndex's in root.proc_macro_data have a one-to-one correspondence . // with items in 'raw_proc_macros'. 2 ( 0.00%) let pos = self . .root . .proc_macro_data . .as_ref() . .unwrap() . .macros . .decode(self) . .position(|i| i == id) . .unwrap(); 4 ( 0.00%) &self.raw_proc_macros.unwrap()[pos] 9 ( 0.00%) } . 37,620 ( 0.00%) fn opt_item_ident(self, item_index: DefIndex, sess: &Session) -> Option { 28,570 ( 0.00%) let name = self.def_key(item_index).disambiguated_data.data.get_opt_name()?; 17,738 ( 0.00%) let span = match self.root.tables.ident_span.get(self, item_index) { . Some(lazy_span) => lazy_span.decode((self, sess)), . None => { . // FIXME: this weird case of a name with no span is specific to `extern crate` . // items, which are supposed to be treated like `use` items and only be encoded . // to metadata as `Export`s, return `None` because that's what all the callers . // expect in this case. 99 ( 0.00%) assert_eq!(self.def_kind(item_index), DefKind::ExternCrate); . return None; . } . }; . Some(Ident::new(name, span)) 48,364 ( 0.00%) } . 314 ( 0.00%) fn item_ident(self, item_index: DefIndex, sess: &Session) -> Ident { 8,243 ( 0.00%) self.opt_item_ident(item_index, sess).expect("no encoded ident for item") 628 ( 0.00%) } . . fn maybe_kind(self, item_id: DefIndex) -> Option { 27,838 ( 0.00%) self.root.tables.kind.get(self, item_id).map(|k| k.decode(self)) . } . 111,352 ( 0.00%) fn kind(self, item_id: DefIndex) -> EntryKind { . self.maybe_kind(item_id).unwrap_or_else(|| { . bug!( . "CrateMetadata::kind({:?}): id not found, in crate {:?} with number {}", . item_id, . self.root.name, . self.cnum, . ) . }) 83,514 ( 0.00%) } . 68,803 ( 0.00%) fn def_kind(self, item_id: DefIndex) -> DefKind { 49,041 ( 0.00%) self.root.tables.def_kind.get(self, item_id).map(|k| k.decode(self)).unwrap_or_else(|| { . bug!( . "CrateMetadata::def_kind({:?}): id not found, in crate {:?} with number {}", . item_id, . self.root.name, . self.cnum, . ) . }) 39,316 ( 0.00%) } . 2,826 ( 0.00%) fn get_span(self, index: DefIndex, sess: &Session) -> Span { 7,376 ( 0.00%) self.root . .tables . .span . .get(self, index) . .unwrap_or_else(|| panic!("Missing span for {:?}", index)) . .decode((self, sess)) 1,570 ( 0.00%) } . . fn load_proc_macro(self, id: DefIndex, sess: &Session) -> SyntaxExtension { 18 ( 0.00%) let (name, kind, helper_attrs) = match *self.raw_proc_macro(id) { . ProcMacro::CustomDerive { trait_name, attributes, client } => { . let helper_attrs = . attributes.iter().cloned().map(Symbol::intern).collect::>(); . ( . trait_name, . SyntaxExtensionKind::Derive(Box::new(ProcMacroDerive { client })), . helper_attrs, . ) . } 4 ( 0.00%) ProcMacro::Attr { name, client } => { 4 ( 0.00%) (name, SyntaxExtensionKind::Attr(Box::new(AttrProcMacro { client })), Vec::new()) . } . ProcMacro::Bang { name, client } => { . (name, SyntaxExtensionKind::Bang(Box::new(BangProcMacro { client })), Vec::new()) . } . }; . 5 ( 0.00%) let attrs: Vec<_> = self.get_item_attrs(id, sess).collect(); 12 ( 0.00%) SyntaxExtension::new( . sess, 5 ( 0.00%) kind, . self.get_span(id, sess), 4 ( 0.00%) helper_attrs, 3 ( 0.00%) self.root.edition, 1 ( 0.00%) Symbol::intern(name), . &attrs, . ) . } . 936 ( 0.00%) fn get_trait_def(self, item_id: DefIndex, sess: &Session) -> ty::TraitDef { 288 ( 0.00%) match self.kind(item_id) { 72 ( 0.00%) EntryKind::Trait(data) => { 432 ( 0.00%) let data = data.decode((self, sess)); 1,152 ( 0.00%) ty::TraitDef::new( . self.local_def_id(item_id), 144 ( 0.00%) data.unsafety, 144 ( 0.00%) data.paren_sugar, 144 ( 0.00%) data.has_auto_impl, 144 ( 0.00%) data.is_marker, 72 ( 0.00%) data.skip_array_during_method_dispatch, 72 ( 0.00%) data.specialization_kind, 288 ( 0.00%) self.def_path_hash(item_id), 72 ( 0.00%) data.must_implement_one_of, . ) . } . EntryKind::TraitAlias => ty::TraitDef::new( . self.local_def_id(item_id), . hir::Unsafety::Normal, . false, . false, . false, . false, . ty::trait_def::TraitSpecializationKind::None, . self.def_path_hash(item_id), . None, . ), . _ => bug!("def-index does not refer to trait or trait alias"), . } 648 ( 0.00%) } . 522 ( 0.00%) fn get_variant( . self, . kind: &EntryKind, . index: DefIndex, . parent_did: DefId, . sess: &Session, . ) -> ty::VariantDef { 232 ( 0.00%) let data = match kind { . EntryKind::Variant(data) | EntryKind::Struct(data, _) | EntryKind::Union(data, _) => { 290 ( 0.00%) data.decode(self) . } . _ => bug!(), . }; . 194 ( 0.00%) let adt_kind = match kind { . EntryKind::Variant(_) => ty::AdtKind::Enum, . EntryKind::Struct(..) => ty::AdtKind::Struct, . EntryKind::Union(..) => ty::AdtKind::Union, . _ => bug!(), . }; . . let variant_did = . if adt_kind == ty::AdtKind::Enum { Some(self.local_def_id(index)) } else { None }; 116 ( 0.00%) let ctor_did = data.ctor.map(|index| self.local_def_id(index)); . 1,276 ( 0.00%) ty::VariantDef::new( . self.item_ident(index, sess).name, . variant_did, . ctor_did, 232 ( 0.00%) data.discr, 348 ( 0.00%) self.root . .tables . .children . .get(self, index) . .unwrap_or_else(Lazy::empty) . .decode(self) . .map(|index| ty::FieldDef { 72 ( 0.00%) did: self.local_def_id(index), 144 ( 0.00%) name: self.item_ident(index, sess).name, 144 ( 0.00%) vis: self.get_visibility(index), . }) . .collect(), . data.ctor_kind, . adt_kind, . parent_did, . false, 58 ( 0.00%) data.is_non_exhaustive, . ) 522 ( 0.00%) } . 720 ( 0.00%) fn get_adt_def(self, item_id: DefIndex, tcx: TyCtxt<'tcx>) -> &'tcx ty::AdtDef { 192 ( 0.00%) let kind = self.kind(item_id); 96 ( 0.00%) let did = self.local_def_id(item_id); . 222 ( 0.00%) let (adt_kind, repr) = match kind { . EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr), . EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr), . EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr), . _ => bug!("get_adt_def called on a non-ADT {:?}", did), . }; . . let variants = if let ty::AdtKind::Enum = adt_kind { 50 ( 0.00%) self.root . .tables . .children . .get(self, item_id) . .unwrap_or_else(Lazy::empty) . .decode(self) 340 ( 0.00%) .map(|index| self.get_variant(&self.kind(index), index, did, tcx.sess)) . .collect() . } else { 304 ( 0.00%) std::iter::once(self.get_variant(&kind, item_id, did, tcx.sess)).collect() . }; . 722 ( 0.00%) tcx.alloc_adt_def(did, adt_kind, variants, repr) 336 ( 0.00%) } . . fn get_explicit_predicates( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> ty::GenericPredicates<'tcx> { 9,070 ( 0.00%) self.root.tables.explicit_predicates.get(self, item_id).unwrap().decode((self, tcx)) . } . . fn get_inferred_outlives( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> &'tcx [(ty::Predicate<'tcx>, Span)] { 9,070 ( 0.00%) self.root . .tables . .inferred_outlives . .get(self, item_id) 12 ( 0.00%) .map(|predicates| tcx.arena.alloc_from_iter(predicates.decode((self, tcx)))) . .unwrap_or_default() . } . . fn get_super_predicates( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> ty::GenericPredicates<'tcx> { 365 ( 0.00%) self.root.tables.super_predicates.get(self, item_id).unwrap().decode((self, tcx)) . } . . fn get_explicit_item_bounds( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> &'tcx [(ty::Predicate<'tcx>, Span)] { 115 ( 0.00%) self.root . .tables . .explicit_item_bounds . .get(self, item_id) 88 ( 0.00%) .map(|bounds| tcx.arena.alloc_from_iter(bounds.decode((self, tcx)))) . .unwrap_or_default() . } . . fn get_generics(self, item_id: DefIndex, sess: &Session) -> ty::Generics { 36,834 ( 0.00%) self.root.tables.generics.get(self, item_id).unwrap().decode((self, sess)) . } . . fn get_type(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 15,075 ( 0.00%) self.root . .tables . .ty . .get(self, id) . .unwrap_or_else(|| panic!("Not a type: {:?}", id)) . .decode((self, tcx)) . } . . fn get_stability(self, id: DefIndex) -> Option { 955 ( 0.00%) self.root.tables.stability.get(self, id).map(|stab| stab.decode(self)) . } . . fn get_const_stability(self, id: DefIndex) -> Option { 15 ( 0.00%) self.root.tables.const_stability.get(self, id).map(|stab| stab.decode(self)) . } . . fn get_deprecation(self, id: DefIndex) -> Option { 1,120 ( 0.00%) self.root.tables.deprecation.get(self, id).map(|depr| depr.decode(self)) . } . 240 ( 0.00%) fn get_visibility(self, id: DefIndex) -> ty::Visibility { 9,467 ( 0.00%) self.root.tables.visibility.get(self, id).unwrap().decode(self) 160 ( 0.00%) } . . fn get_impl_data(self, id: DefIndex) -> ImplData { 65,214 ( 0.00%) match self.kind(id) { 54,345 ( 0.00%) EntryKind::Impl(data) => data.decode(self), . _ => bug!(), . } . } . . fn get_parent_impl(self, id: DefIndex) -> Option { 31,236 ( 0.00%) self.get_impl_data(id).parent_impl . } . . fn get_impl_polarity(self, id: DefIndex) -> ty::ImplPolarity { 300 ( 0.00%) self.get_impl_data(id).polarity . } . . fn get_impl_defaultness(self, id: DefIndex) -> hir::Defaultness { 153 ( 0.00%) self.get_impl_data(id).defaultness . } . . fn get_impl_constness(self, id: DefIndex) -> hir::Constness { 4 ( 0.00%) self.get_impl_data(id).constness . } . . fn get_trait_item_def_id(self, id: DefIndex) -> Option { 7,620 ( 0.00%) self.root.tables.trait_item_def_id.get(self, id).map(|d| d.decode(self)) . } . . fn get_coerce_unsized_info(self, id: DefIndex) -> Option { . self.get_impl_data(id).coerce_unsized_info . } . . fn get_impl_trait(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Option> { 126,011 ( 0.00%) self.root.tables.impl_trait_ref.get(self, id).map(|tr| tr.decode((self, tcx))) . } . . fn get_expn_that_defined(self, id: DefIndex, sess: &Session) -> ExpnId { 2,290 ( 0.00%) self.root.tables.expn_that_defined.get(self, id).unwrap().decode((self, sess)) . } . . fn get_const_param_default( . self, . tcx: TyCtxt<'tcx>, . id: DefIndex, . ) -> rustc_middle::ty::Const<'tcx> { . self.root.tables.const_defaults.get(self, id).unwrap().decode((self, tcx)) -- line 1026 ---------------------------------------- -- line 1028 ---------------------------------------- . . /// Iterates over all the stability attributes in the given crate. . fn get_lib_features(self, tcx: TyCtxt<'tcx>) -> &'tcx [(Symbol, Option)] { . tcx.arena.alloc_from_iter(self.root.lib_features.decode(self)) . } . . /// Iterates over the language items in the given crate. . fn get_lang_items(self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, usize)] { 66 ( 0.00%) tcx.arena.alloc_from_iter( 44 ( 0.00%) self.root . .lang_items . .decode(self) 564 ( 0.00%) .map(|(def_index, index)| (self.local_def_id(def_index), index)), . ) . } . . /// Iterates over the diagnostic items in the given crate. . fn get_diagnostic_items(self) -> DiagnosticItems { . let mut id_to_name = FxHashMap::default(); 44 ( 0.00%) let name_to_id = self . .root . .diagnostic_items . .decode(self) . .map(|(name, def_index)| { 130 ( 0.00%) let id = self.local_def_id(def_index); 130 ( 0.00%) id_to_name.insert(id, name); . (name, id) . }) . .collect(); 198 ( 0.00%) DiagnosticItems { id_to_name, name_to_id } . } . . /// Iterates over all named children of the given module, . /// including both proper items and reexports. . /// Module here is understood in name resolution sense - it can be a `mod` item, . /// or a crate root, or an enum, or a trait. . fn for_each_module_child( . self, . id: DefIndex, . mut callback: impl FnMut(ModChild), . sess: &Session, . ) { 356 ( 0.00%) if let Some(data) = &self.root.proc_macro_data { . // If we are loading as a proc macro, we want to return . // the view of this crate as a proc macro crate. . if id == CRATE_DEF_INDEX { . for def_index in data.macros.decode(self) { . let raw_macro = self.raw_proc_macro(def_index); . let res = Res::Def( . DefKind::Macro(macro_kind(raw_macro)), . self.local_def_id(def_index), -- line 1078 ---------------------------------------- -- line 1085 ---------------------------------------- . span: ident.span, . }); . } . } . return; . } . . // Iterate over all children. 712 ( 0.00%) if let Some(children) = self.root.tables.children.get(self, id) { 1,424 ( 0.00%) for child_index in children.decode((self, sess)) { 10,374 ( 0.00%) if let Some(ident) = self.opt_item_ident(child_index, sess) { 2,133 ( 0.00%) let kind = self.def_kind(child_index); 1,422 ( 0.00%) if matches!(kind, DefKind::Macro(..)) { . // FIXME: Macros are currently encoded twice, once as items and once as . // reexports. We ignore the items here and only use the reexports. . continue; . } . let def_id = self.local_def_id(child_index); . let res = Res::Def(kind, def_id); . let vis = self.get_visibility(child_index); . let span = self.get_span(child_index, sess); . . callback(ModChild { ident, res, vis, span }); . . // For non-re-export structs and variants add their constructors to children. . // Re-export lists automatically contain constructors when necessary. 2,716 ( 0.00%) match kind { . DefKind::Struct => { 37 ( 0.00%) if let Some((ctor_def_id, ctor_kind)) = . self.get_ctor_def_id_and_kind(child_index) . { . let ctor_res = . Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id); . let vis = self.get_visibility(ctor_def_id.index); . callback(ModChild { ident, res: ctor_res, vis, span }); . } . } . DefKind::Variant => { . // Braced variants, unlike structs, generate unusable names in . // value namespace, they are reserved for possible future use. . // It's ok to use the variant's id as a ctor id since an . // error will be reported on any use of such resolution anyway. 24 ( 0.00%) let (ctor_def_id, ctor_kind) = self . .get_ctor_def_id_and_kind(child_index) . .unwrap_or((def_id, CtorKind::Fictive)); . let ctor_res = . Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id); . let mut vis = self.get_visibility(ctor_def_id.index); 8 ( 0.00%) if ctor_def_id == def_id && vis.is_public() { . // For non-exhaustive variants lower the constructor visibility to . // within the crate. We only need this for fictive constructors, . // for other constructors correct visibilities . // were already encoded in metadata. . let mut attrs = self.get_item_attrs(def_id.index, sess); . if attrs.any(|item| item.has_name(sym::non_exhaustive)) { . let crate_def_id = self.local_def_id(CRATE_DEF_INDEX); . vis = ty::Visibility::Restricted(crate_def_id); -- line 1141 ---------------------------------------- -- line 1144 ---------------------------------------- . callback(ModChild { ident, res: ctor_res, vis, span }); . } . _ => {} . } . } . } . } . 911 ( 0.00%) match self.kind(id) { 56 ( 0.00%) EntryKind::Mod(exports) => { 1,950 ( 0.00%) for exp in exports.decode((self, sess)) { . callback(exp); . } . } . EntryKind::Enum(..) | EntryKind::Trait(..) => {} . _ => bug!("`for_each_module_child` is called on a non-module: {:?}", self.def_kind(id)), . } . } . . fn is_ctfe_mir_available(self, id: DefIndex) -> bool { 216 ( 0.00%) self.root.tables.mir_for_ctfe.get(self, id).is_some() . } . . fn is_item_mir_available(self, id: DefIndex) -> bool { 1,184 ( 0.00%) self.root.tables.mir.get(self, id).is_some() . } . . fn module_expansion(self, id: DefIndex, sess: &Session) -> ExpnId { 2,842 ( 0.00%) match self.kind(id) { . EntryKind::Mod(_) | EntryKind::Enum(_) | EntryKind::Trait(_) => { . self.get_expn_that_defined(id, sess) . } . _ => panic!("Expected module, found {:?}", self.local_def_id(id)), . } . } . . fn get_optimized_mir(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> Body<'tcx> { 1,475 ( 0.00%) self.root . .tables . .mir . .get(self, id) . .unwrap_or_else(|| { . bug!("get_optimized_mir: missing MIR for `{:?}`", self.local_def_id(id)) . }) . .decode((self, tcx)) . } . . fn get_mir_for_ctfe(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> Body<'tcx> { 270 ( 0.00%) self.root . .tables . .mir_for_ctfe . .get(self, id) . .unwrap_or_else(|| { . bug!("get_mir_for_ctfe: missing MIR for `{:?}`", self.local_def_id(id)) . }) . .decode((self, tcx)) . } -- line 1200 ---------------------------------------- -- line 1216 ---------------------------------------- . .tables . .unused_generic_params . .get(self, id) . .map(|params| params.decode(self)) . .unwrap_or_default() . } . . fn get_promoted_mir(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> IndexVec> { 25 ( 0.00%) self.root . .tables . .promoted_mir . .get(self, id) . .unwrap_or_else(|| { . bug!("get_promoted_mir: missing MIR for `{:?}`", self.local_def_id(id)) . }) . .decode((self, tcx)) . } . . fn mir_const_qualif(self, id: DefIndex) -> mir::ConstQualifs { 15 ( 0.00%) match self.kind(id) { . EntryKind::AnonConst(qualif, _) . | EntryKind::Const(qualif, _) . | EntryKind::AssocConst( . AssocContainer::ImplDefault . | AssocContainer::ImplFinal . | AssocContainer::TraitWithDefault, 2 ( 0.00%) qualif, . _, . ) => qualif, . _ => bug!("mir_const_qualif: unexpected kind"), . } . } . . fn get_fn_has_self_parameter(self, id: DefIndex) -> bool { 755 ( 0.00%) match self.kind(id) { 604 ( 0.00%) EntryKind::AssocFn(data) => data.decode(self).has_self, . _ => false, . } . } . . fn get_associated_item_def_ids(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> &'tcx [DefId] { 1,778 ( 0.00%) if let Some(children) = self.root.tables.children.get(self, id) { 762 ( 0.00%) tcx.arena.alloc_from_iter( 254 ( 0.00%) children.decode((self, tcx.sess)).map(|child_index| self.local_def_id(child_index)), . ) . } else { . &[] . } . } . 14,808 ( 0.00%) fn get_associated_item(self, id: DefIndex, sess: &Session) -> ty::AssocItem { 8,638 ( 0.00%) let def_key = self.def_key(id); . let parent = self.local_def_id(def_key.parent.unwrap()); . let ident = self.item_ident(id, sess); . 8,938 ( 0.00%) let (kind, container, has_self) = match self.kind(id) { 96 ( 0.00%) EntryKind::AssocConst(container, _, _) => (ty::AssocKind::Const, container, false), 1,108 ( 0.00%) EntryKind::AssocFn(data) => { . let data = data.decode(self); 7,756 ( 0.00%) (ty::AssocKind::Fn, data.container, data.has_self) . } 204 ( 0.00%) EntryKind::AssocType(container) => (ty::AssocKind::Type, container, false), . _ => bug!("cannot get associated-item of `{:?}`", def_key), . }; . 22,212 ( 0.00%) ty::AssocItem { . name: ident.name, . kind, . vis: self.get_visibility(id), . defaultness: container.defaultness(), . def_id: self.local_def_id(id), . trait_item_def_id: self.get_trait_item_def_id(id), . container: container.with_def_id(parent), . fn_has_self_parameter: has_self, . } 11,106 ( 0.00%) } . . fn get_item_variances(self, id: DefIndex) -> impl Iterator + 'a { 140 ( 0.00%) self.root.tables.variances.get(self, id).unwrap_or_else(Lazy::empty).decode(self) . } . . fn get_ctor_def_id_and_kind(self, node_id: DefIndex) -> Option<(DefId, CtorKind)> { 1,701 ( 0.00%) match self.kind(node_id) { . EntryKind::Struct(data, _) | EntryKind::Variant(data) => { 732 ( 0.00%) let vdata = data.decode(self); 485 ( 0.00%) vdata.ctor.map(|index| (self.local_def_id(index), vdata.ctor_kind)) . } . _ => None, . } 968 ( 0.00%) } . 69,720 ( 0.00%) fn get_item_attrs( . self, . id: DefIndex, . sess: &'a Session, . ) -> impl Iterator + 'a { 26,034 ( 0.00%) self.root . .tables . .attributes . .get(self, id) . .unwrap_or_else(|| { . // Structure and variant constructors don't have any attributes encoded for them, . // but we assume that someone passing a constructor ID actually wants to look at . // the attributes on the corresponding struct or variant. . let def_key = self.def_key(id); -- line 1320 ---------------------------------------- -- line 1322 ---------------------------------------- . let parent_id = def_key.parent.expect("no parent for a constructor"); . self.root . .tables . .attributes . .get(self, parent_id) . .expect("no encoded attributes for a structure or variant") . }) . .decode((self, sess)) 52,290 ( 0.00%) } . . fn get_struct_field_names( . self, . id: DefIndex, . sess: &'a Session, . ) -> impl Iterator> + 'a { 930 ( 0.00%) self.root . .tables . .children . .get(self, id) . .unwrap_or_else(Lazy::empty) . .decode(self) 3,140 ( 0.00%) .map(move |index| respan(self.get_span(index, sess), self.item_ident(index, sess).name)) . } . . fn get_struct_field_visibilities(self, id: DefIndex) -> impl Iterator + 'a { 220 ( 0.00%) self.root . .tables . .children . .get(self, id) . .unwrap_or_else(Lazy::empty) . .decode(self) 80 ( 0.00%) .map(move |field_index| self.get_visibility(field_index)) . } . . fn get_inherent_implementations_for_type( . self, . tcx: TyCtxt<'tcx>, . id: DefIndex, . ) -> &'tcx [DefId] { 48 ( 0.00%) tcx.arena.alloc_from_iter( 60 ( 0.00%) self.root . .tables . .inherent_impls . .get(self, id) . .unwrap_or_else(Lazy::empty) . .decode(self) 1,170 ( 0.00%) .map(|index| self.local_def_id(index)), . ) . } . . fn get_traits(self) -> impl Iterator + 'a { . self.root.traits.decode(self).map(move |index| self.local_def_id(index)) . } . . fn get_trait_impls(self) -> impl Iterator)> + 'a { -- line 1376 ---------------------------------------- -- line 1380 ---------------------------------------- . index: *trait_index, . }; . impls.decode(self).map(move |(impl_index, simplified_self_ty)| { . (trait_def_id, self.local_def_id(impl_index), simplified_self_ty) . }) . }) . } . 15,048 ( 0.00%) fn get_implementations_of_trait( . self, . tcx: TyCtxt<'tcx>, . trait_def_id: DefId, . ) -> &'tcx [(DefId, Option)] { 1,672 ( 0.00%) if self.trait_impls.is_empty() { . return &[]; . } . . // Do a reverse lookup beforehand to avoid touching the crate_num . // hash map in the loop below. 2,200 ( 0.00%) let key = match self.reverse_translate_def_id(trait_def_id) { . Some(def_id) => (def_id.krate.as_u32(), def_id.index), . None => return &[], . }; . . if let Some(impls) = self.trait_impls.get(&key) { 1,116 ( 0.00%) tcx.arena.alloc_from_iter( 558 ( 0.00%) impls . .decode(self) 11,485 ( 0.00%) .map(|(idx, simplified_self_ty)| (self.local_def_id(idx), simplified_self_ty)), . ) . } else { . &[] . } 13,376 ( 0.00%) } . . fn get_trait_of_item(self, id: DefIndex) -> Option { 1,472 ( 0.00%) let def_key = self.def_key(id); 1,840 ( 0.00%) match def_key.disambiguated_data.data { . DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (), . // Not an associated item . _ => return None, . } 3,303 ( 0.00%) def_key.parent.and_then(|parent_index| match self.kind(parent_index) { . EntryKind::Trait(_) | EntryKind::TraitAlias => Some(self.local_def_id(parent_index)), . _ => None, . }) . } . . fn get_native_libraries(self, sess: &'a Session) -> impl Iterator + 'a { 44 ( 0.00%) self.root.native_libraries.decode((self, sess)) . } . . fn get_proc_macro_quoted_span(self, index: usize, sess: &Session) -> Span { . self.root . .tables . .proc_macro_quoted_spans . .get(self, index) . .unwrap_or_else(|| panic!("Missing proc macro quoted span: {:?}", index)) -- line 1437 ---------------------------------------- -- line 1450 ---------------------------------------- . self.root.dylib_dependency_formats.decode(self).enumerate().flat_map(|(i, link)| { . let cnum = CrateNum::new(i + 1); . link.map(|link| (self.cnum_map[cnum], link)) . }), . ) . } . . fn get_missing_lang_items(self, tcx: TyCtxt<'tcx>) -> &'tcx [lang_items::LangItem] { 110 ( 0.00%) tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode(self)) . } . . fn get_fn_param_names(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> &'tcx [Ident] { . let param_names = match self.kind(id) { . EntryKind::Fn(data) | EntryKind::ForeignFn(data) => data.decode(self).param_names, . EntryKind::AssocFn(data) => data.decode(self).fn_data.param_names, . _ => Lazy::empty(), . }; . tcx.arena.alloc_from_iter(param_names.decode((self, tcx))) . } . . fn exported_symbols( . self, . tcx: TyCtxt<'tcx>, . ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportLevel)] { 24 ( 0.00%) tcx.arena.alloc_from_iter(self.root.exported_symbols.decode((self, tcx))) . } . . fn get_rendered_const(self, id: DefIndex) -> String { . match self.kind(id) { . EntryKind::AnonConst(_, data) . | EntryKind::Const(_, data) . | EntryKind::AssocConst(_, _, data) => data.decode(self).0, . _ => bug!(), . } . } . . fn get_macro(self, id: DefIndex, sess: &Session) -> MacroDef { 78 ( 0.00%) match self.kind(id) { 13 ( 0.00%) EntryKind::MacroDef(macro_def) => macro_def.decode((self, sess)), . _ => bug!(), . } . } . . // This replicates some of the logic of the crate-local `is_const_fn_raw` query, because we . // don't serialize constness for tuple variant and tuple struct constructors. . fn is_const_fn_raw(self, id: DefIndex) -> bool { 189 ( 0.00%) let constness = match self.kind(id) { 38 ( 0.00%) EntryKind::AssocFn(data) => data.decode(self).fn_data.constness, 12 ( 0.00%) EntryKind::Fn(data) => data.decode(self).constness, . EntryKind::ForeignFn(data) => data.decode(self).constness, . EntryKind::Variant(..) | EntryKind::Struct(..) => hir::Constness::Const, . _ => hir::Constness::NotConst, . }; . constness == hir::Constness::Const . } . . fn asyncness(self, id: DefIndex) -> hir::IsAsync { -- line 1506 ---------------------------------------- -- line 1508 ---------------------------------------- . EntryKind::Fn(data) => data.decode(self).asyncness, . EntryKind::AssocFn(data) => data.decode(self).fn_data.asyncness, . EntryKind::ForeignFn(data) => data.decode(self).asyncness, . _ => bug!("asyncness: expected function kind"), . } . } . . fn is_foreign_item(self, id: DefIndex) -> bool { 3,806 ( 0.00%) match self.kind(id) { . EntryKind::ForeignImmStatic | EntryKind::ForeignMutStatic | EntryKind::ForeignFn(_) => { . true . } . _ => false, . } . } . . fn static_mutability(self, id: DefIndex) -> Option { 583 ( 0.00%) match self.kind(id) { . EntryKind::ImmStatic | EntryKind::ForeignImmStatic => Some(hir::Mutability::Not), . EntryKind::MutStatic | EntryKind::ForeignMutStatic => Some(hir::Mutability::Mut), . _ => None, . } . } . . fn generator_kind(self, id: DefIndex) -> Option { . match self.kind(id) { . EntryKind::Generator(data) => Some(data), . _ => None, . } . } . . fn fn_sig(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> { 2,285 ( 0.00%) self.root.tables.fn_sig.get(self, id).unwrap().decode((self, tcx)) . } . . #[inline] 304,710 ( 0.00%) fn def_key(self, index: DefIndex) -> DefKey { 87,202 ( 0.00%) *self . .def_key_cache . .lock() . .entry(index) 17,565 ( 0.00%) .or_insert_with(|| self.root.tables.def_keys.get(self, index).unwrap().decode(self)) 348,240 ( 0.00%) } . . // Returns the path leading to the thing with this `id`. . fn def_path(self, id: DefIndex) -> DefPath { . debug!("def_path(cnum={:?}, id={:?})", self.cnum, id); 112 ( 0.00%) DefPath::make(self.cnum, id, |parent| self.def_key(parent)) . } . . fn def_path_hash_unlocked( . self, . index: DefIndex, . def_path_hashes: &mut FxHashMap, . ) -> DefPathHash { 126,202 ( 0.00%) *def_path_hashes.entry(index).or_insert_with(|| { 3,640 ( 0.00%) self.root.tables.def_path_hashes.get(self, index).unwrap().decode(self) . }) . } . . #[inline] 441,707 ( 0.00%) fn def_path_hash(self, index: DefIndex) -> DefPathHash { . let mut def_path_hashes = self.def_path_hash_cache.lock(); . self.def_path_hash_unlocked(index, &mut def_path_hashes) 504,808 ( 0.00%) } . . #[inline] . fn def_path_hash_to_def_index(self, hash: DefPathHash) -> DefIndex { . self.def_path_hash_map.def_path_hash_to_def_index(&hash) . } . . fn expn_hash_to_expn_id(self, sess: &Session, index_guess: u32, hash: ExpnHash) -> ExpnId { . debug_assert_eq!(ExpnId::from_hash(hash), None); -- line 1580 ---------------------------------------- -- line 1635 ---------------------------------------- . /// Proc macro crates don't currently export spans, so this function does not have . /// to work for them. . fn imported_source_files(self, sess: &Session) -> &'a [ImportedSourceFile] { . // Translate the virtual `/rustc/$hash` prefix back to a real directory . // that should hold actual sources, where possible. . // . // NOTE: if you update this, you might need to also update bootstrap's code for generating . // the `rust-src` component in `Src::run` in `src/bootstrap/dist.rs`. 646,990 ( 0.00%) let virtual_rust_source_base_dir = option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR") . .map(Path::new) . .filter(|_| { . // Only spend time on further checks if we have what to translate *to*. . sess.opts.real_rust_source_base_dir.is_some() . }) . .filter(|virtual_dir| { . // Don't translate away `/rustc/$hash` if we're still remapping to it, . // since that means we're still building `std`/`rustc` that need it, . // and we don't want the real path to leak into codegen/debuginfo. . !sess.opts.remap_path_prefix.iter().any(|(_from, to)| to == virtual_dir) . }); 646,990 ( 0.00%) let try_to_translate_virtual_to_real = |name: &mut rustc_span::FileName| { . debug!( . "try_to_translate_virtual_to_real(name={:?}): \ . virtual_rust_source_base_dir={:?}, real_rust_source_base_dir={:?}", . name, virtual_rust_source_base_dir, sess.opts.real_rust_source_base_dir, . ); . 2,785 ( 0.00%) if let Some(virtual_dir) = virtual_rust_source_base_dir { . if let Some(real_dir) = &sess.opts.real_rust_source_base_dir { . if let rustc_span::FileName::Real(old_name) = name { . if let rustc_span::RealFileName::Remapped { local_path: _, virtual_name } = . old_name . { . if let Ok(rest) = virtual_name.strip_prefix(virtual_dir) { . let virtual_name = virtual_name.clone(); . -- line 1670 ---------------------------------------- -- line 1709 ---------------------------------------- . *old_name = new_name; . } . } . } . } . } . }; . 646,773 ( 0.00%) self.cdata.source_map_import_info.get_or_init(|| { 33 ( 0.00%) let external_source_map = self.root.source_map.decode(self); . . external_source_map . .map(|source_file_to_import| { . // We can't reuse an existing SourceFile, so allocate a new one . // containing the information we need. . let rustc_span::SourceFile { 11,697 ( 0.00%) mut name, 3,342 ( 0.00%) src_hash, 557 ( 0.00%) start_pos, 1,114 ( 0.00%) end_pos, 2,785 ( 0.00%) mut lines, 2,785 ( 0.00%) mut multibyte_chars, 3,342 ( 0.00%) mut non_narrow_chars, 2,785 ( 0.00%) mut normalized_pos, 3,342 ( 0.00%) name_hash, . .. . } = source_file_to_import; . . // If this file is under $sysroot/lib/rustlib/src/ but has not been remapped . // during rust bootstrapping by `remap-debuginfo = true`, and the user . // wish to simulate that behaviour by -Z simulate-remapped-rust-src-base, . // then we change `name` to a similar state as if the rust was bootstrapped . // with `remap-debuginfo = true`. . // This is useful for testing so that tests about the effects of . // `try_to_translate_virtual_to_real` don't have to worry about how the . // compiler is bootstrapped. 1,114 ( 0.00%) if let Some(virtual_dir) = . &sess.opts.debugging_opts.simulate_remapped_rust_src_base . { . if let Some(real_dir) = &sess.opts.real_rust_source_base_dir { . if let rustc_span::FileName::Real(ref mut old_name) = name { . if let rustc_span::RealFileName::LocalPath(local) = old_name { . if let Ok(rest) = local.strip_prefix(real_dir) { . *old_name = rustc_span::RealFileName::Remapped { . local_path: None, -- line 1753 ---------------------------------------- -- line 1767 ---------------------------------------- . let source_length = (end_pos - start_pos).to_usize(); . . // Translate line-start positions and multibyte character . // position into frame of reference local to file. . // `SourceMap::new_imported_source_file()` will then translate those . // coordinates to their new global frame of reference when the . // offset of the SourceFile is known. . for pos in &mut lines { 741,842 ( 0.00%) *pos = *pos - start_pos; . } . for mbc in &mut multibyte_chars { 1,618 ( 0.00%) mbc.pos = mbc.pos - start_pos; . } . for swc in &mut non_narrow_chars { 936 ( 0.00%) *swc = *swc - start_pos; . } . for np in &mut normalized_pos { . np.pos = np.pos - start_pos; . } . 10,026 ( 0.00%) let local_version = sess.source_map().new_imported_source_file( 7,241 ( 0.00%) name, 3,899 ( 0.00%) src_hash, . name_hash, . source_length, 1,114 ( 0.00%) self.cnum, 2,785 ( 0.00%) lines, 3,342 ( 0.00%) multibyte_chars, 2,785 ( 0.00%) non_narrow_chars, 2,228 ( 0.00%) normalized_pos, . start_pos, . end_pos, . ); . debug!( . "CrateMetaData::imported_source_files alloc \ . source_file {:?} original (start_pos {:?} end_pos {:?}) \ . translated (start_pos {:?} end_pos {:?})", . local_version.name, -- line 1804 ---------------------------------------- -- line 1808 ---------------------------------------- . local_version.end_pos . ); . . ImportedSourceFile { . original_start_pos: start_pos, . original_end_pos: end_pos, . translated_source_file: local_version, . } 1,671 ( 0.00%) }) . .collect() . }) . } . } . . impl CrateMetadata { 264 ( 0.00%) crate fn new( . sess: &Session, . blob: MetadataBlob, . root: CrateRoot<'static>, . raw_proc_macros: Option<&'static [ProcMacro]>, . cnum: CrateNum, . cnum_map: CrateNumMap, . dep_kind: CrateDepKind, . source: CrateSource, . private_dep: bool, . host_hash: Option, . ) -> CrateMetadata { 66 ( 0.00%) let trait_impls = root . .impls . .decode((&blob, sess)) . .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls)) . .collect(); . let alloc_decoding_state = 66 ( 0.00%) AllocDecodingState::new(root.interpret_alloc_index.decode(&blob).collect()); . let dependencies = Lock::new(cnum_map.iter().cloned().collect()); . . // Pre-decode the DefPathHash->DefIndex table. This is a cheap operation . // that does not copy any data. It just does some data verification. 22 ( 0.00%) let def_path_hash_map = root.def_path_hash_map.decode(&blob); . 506 ( 0.00%) CrateMetadata { 22 ( 0.00%) blob, 66 ( 0.00%) root, 88 ( 0.00%) trait_impls, . raw_proc_macros, . source_map_import_info: OnceCell::new(), 88 ( 0.00%) def_path_hash_map, . expn_hash_map: Default::default(), 154 ( 0.00%) alloc_decoding_state, . cnum, 88 ( 0.00%) cnum_map, 110 ( 0.00%) dependencies, . dep_kind: Lock::new(dep_kind), 264 ( 0.00%) source, . private_dep, . host_hash, . extern_crate: Lock::new(None), . hygiene_context: Default::default(), . def_key_cache: Default::default(), . def_path_hash_cache: Default::default(), . } 198 ( 0.00%) } . . crate fn dependencies(&self) -> LockGuard<'_, Vec> { . self.dependencies.borrow() . } . . crate fn add_dependency(&self, cnum: CrateNum) { . self.dependencies.borrow_mut().push(cnum); . } . . crate fn update_extern_crate(&self, new_extern_crate: ExternCrate) -> bool { . let mut extern_crate = self.extern_crate.borrow_mut(); . let update = Some(new_extern_crate.rank()) > extern_crate.as_ref().map(ExternCrate::rank); . if update { 115 ( 0.00%) *extern_crate = Some(new_extern_crate); . } . update . } . . crate fn source(&self) -> &CrateSource { 25,832 ( 0.00%) &self.source . } . . crate fn dep_kind(&self) -> CrateDepKind { . *self.dep_kind.lock() . } . . crate fn update_dep_kind(&self, f: impl FnOnce(CrateDepKind) -> CrateDepKind) { 6,548 ( 0.00%) self.dep_kind.with_lock(|dep_kind| *dep_kind = f(*dep_kind)) . } . . crate fn panic_strategy(&self) -> PanicStrategy { . self.root.panic_strategy . } . . crate fn needs_panic_runtime(&self) -> bool { . self.root.needs_panic_runtime -- line 1905 ---------------------------------------- -- line 1909 ---------------------------------------- . self.root.panic_runtime . } . . crate fn is_profiler_runtime(&self) -> bool { . self.root.profiler_runtime . } . . crate fn needs_allocator(&self) -> bool { 5 ( 0.00%) self.root.needs_allocator . } . . crate fn has_global_allocator(&self) -> bool { . self.root.has_global_allocator . } . . crate fn has_default_lib_allocator(&self) -> bool { . self.root.has_default_lib_allocator . } . . crate fn is_proc_macro_crate(&self) -> bool { . self.root.is_proc_macro_crate() . } . . crate fn name(&self) -> Symbol { 125,439 ( 0.00%) self.root.name . } . . crate fn stable_crate_id(&self) -> StableCrateId { . self.root.stable_crate_id . } . . crate fn hash(&self) -> Svh { . self.root.hash . } . . fn num_def_ids(&self) -> usize { . self.root.tables.def_keys.size() . } . . fn local_def_id(&self, index: DefIndex) -> DefId { 20,722 ( 0.00%) DefId { krate: self.cnum, index } . } . . // Translate a DefId from the current compilation environment to a DefId . // for an external crate. . fn reverse_translate_def_id(&self, did: DefId) -> Option { . for (local, &global) in self.cnum_map.iter_enumerated() { 5,816 ( 0.00%) if global == did.krate { . return Some(DefId { krate: local, index: did.index }); . } . } . . None . } . } . -- line 1964 ---------------------------------------- 4,308,234 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs -------------------------------------------------------------------------------- Ir -- line 357 ---------------------------------------- . /// . /// ``` . /// use std::rc::Rc; . /// . /// let five = Rc::new(5); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 58,104 ( 0.00%) pub fn new(value: T) -> Rc { . // There is an implicit weak pointer owned by all the strong . // pointers, which ensures that the weak destructor never frees . // the allocation while the strong destructor is running, even . // if the weak pointer is stored inside the strong one. . unsafe { . Self::from_inner( 5,568,627 ( 0.03%) Box::leak(box RcBox { strong: Cell::new(1), weak: Cell::new(1), value }).into(), . ) . } 58,104 ( 0.00%) } . . /// Constructs a new `Rc` using a closure `data_fn` that has access to a . /// weak reference to the constructing `Rc`. . /// . /// Generally, a structure circularly referencing itself, either directly or . /// indirectly, should not hold a strong reference to prevent a memory leak. . /// In `data_fn`, initialization of `T` can make use of the weak reference . /// by cloning and storing it inside `T` for use at a later time. -- line 383 ---------------------------------------- -- line 474 ---------------------------------------- . /// . /// let five = unsafe { five.assume_init() }; . /// . /// assert_eq!(*five, 5) . /// ``` . #[cfg(not(no_global_oom_handling))] . #[unstable(feature = "new_uninit", issue = "63291")] . #[must_use] 12,732 ( 0.00%) pub fn new_uninit() -> Rc> { . unsafe { . Rc::from_ptr(Rc::allocate_for_layout( . Layout::new::(), . |layout| Global.allocate(layout), . |mem| mem as *mut RcBox>, . )) . } 25,464 ( 0.00%) } . . /// Constructs a new `Rc` with uninitialized contents, with the memory . /// being filled with `0` bytes. . /// . /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and . /// incorrect usage of this method. . /// . /// # Examples -- line 498 ---------------------------------------- -- line 637 ---------------------------------------- . /// . /// let x = Rc::new(4); . /// let _y = Rc::clone(&x); . /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4); . /// ``` . #[inline] . #[stable(feature = "rc_unique", since = "1.4.0")] . pub fn try_unwrap(this: Self) -> Result { 2 ( 0.00%) if Rc::strong_count(&this) == 1 { . unsafe { . let val = ptr::read(&*this); // copy the contained object . . // Indicate to Weaks that they can't be promoted by decrementing . // the strong count, and then remove the implicit "strong weak" . // pointer while also handling drop logic by just crafting a . // fake Weak. . this.inner().dec_strong(); -- line 653 ---------------------------------------- -- line 931 ---------------------------------------- . /// let five = Rc::new(5); . /// let _weak_five = Rc::downgrade(&five); . /// . /// assert_eq!(1, Rc::weak_count(&five)); . /// ``` . #[inline] . #[stable(feature = "rc_counts", since = "1.15.0")] . pub fn weak_count(this: &Self) -> usize { 493,275 ( 0.00%) this.inner().weak() - 1 . } . . /// Gets the number of strong (`Rc`) pointers to this allocation. . /// . /// # Examples . /// . /// ``` . /// use std::rc::Rc; -- line 947 ---------------------------------------- -- line 1023 ---------------------------------------- . pub unsafe fn decrement_strong_count(ptr: *const T) { . unsafe { mem::drop(Rc::from_raw(ptr)) }; . } . . /// Returns `true` if there are no other `Rc` or [`Weak`] pointers to . /// this allocation. . #[inline] . fn is_unique(this: &Self) -> bool { 2,727 ( 0.00%) Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1 . } . . /// Returns a mutable reference into the given `Rc`, if there are . /// no other `Rc` or [`Weak`] pointers to the same allocation. . /// . /// Returns [`None`] otherwise, because it is not safe to . /// mutate a shared value. . /// -- line 1039 ---------------------------------------- -- line 1053 ---------------------------------------- . /// assert_eq!(*x, 4); . /// . /// let _y = Rc::clone(&x); . /// assert!(Rc::get_mut(&mut x).is_none()); . /// ``` . #[inline] . #[stable(feature = "rc_unique", since = "1.4.0")] . pub fn get_mut(this: &mut Self) -> Option<&mut T> { 909 ( 0.00%) if Rc::is_unique(this) { unsafe { Some(Rc::get_mut_unchecked(this)) } } else { None } . } . . /// Returns a mutable reference into the given `Rc`, . /// without any check. . /// . /// See also [`get_mut`], which is safe and does appropriate checks. . /// . /// [`get_mut`]: Rc::get_mut -- line 1069 ---------------------------------------- -- line 1088 ---------------------------------------- . /// } . /// assert_eq!(*x, "foo"); . /// ``` . #[inline] . #[unstable(feature = "get_mut_unchecked", issue = "63292")] . pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T { . // We are careful to *not* create a reference covering the "count" fields, as . // this would conflict with accesses to the reference counts (e.g. by `Weak`). 240,817 ( 0.00%) unsafe { &mut (*this.ptr.as_ptr()).value } . } . . #[inline] . #[stable(feature = "ptr_eq", since = "1.17.0")] . /// Returns `true` if the two `Rc`s point to the same allocation . /// (in a vein similar to [`ptr::eq`]). . /// . /// # Examples -- line 1104 ---------------------------------------- -- line 1109 ---------------------------------------- . /// let five = Rc::new(5); . /// let same_five = Rc::clone(&five); . /// let other_five = Rc::new(5); . /// . /// assert!(Rc::ptr_eq(&five, &same_five)); . /// assert!(!Rc::ptr_eq(&five, &other_five)); . /// ``` . pub fn ptr_eq(this: &Self, other: &Self) -> bool { 6,809 ( 0.00%) this.ptr.as_ptr() == other.ptr.as_ptr() . } . } . . impl Rc { . /// Makes a mutable reference into the given `Rc`. . /// . /// If there are other `Rc` pointers to the same allocation, then `make_mut` will . /// [`clone`] the inner value to a new allocation to ensure unique ownership. This is also -- line 1125 ---------------------------------------- -- line 1167 ---------------------------------------- . /// *Rc::make_mut(&mut data) += 1; . /// . /// assert!(76 == *data); . /// assert!(weak.upgrade().is_none()); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "rc_unique", since = "1.4.0")] 893,722 ( 0.01%) pub fn make_mut(this: &mut Self) -> &mut T { 523,428 ( 0.00%) if Rc::strong_count(this) != 1 { . // Gotta clone the data, there are other Rcs. . // Pre-allocate memory to allow writing the cloned value directly. 39,429 ( 0.00%) let mut rc = Self::new_uninit(); . unsafe { . let data = Rc::get_mut_unchecked(&mut rc); . (**this).write_clone_into_raw(data.as_mut_ptr()); 2,466 ( 0.00%) *this = rc.assume_init(); . } 327,032 ( 0.00%) } else if Rc::weak_count(this) != 0 { . // Can just steal the data, all that's left is Weaks . let mut rc = Self::new_uninit(); . unsafe { . let data = Rc::get_mut_unchecked(&mut rc); . data.as_mut_ptr().copy_from_nonoverlapping(&**this, 1); . . this.inner().dec_strong(); . // Remove implicit strong-weak ref (no need to craft a fake -- line 1193 ---------------------------------------- -- line 1196 ---------------------------------------- . ptr::write(this, rc.assume_init()); . } . } . // This unsafety is ok because we're guaranteed that the pointer . // returned is the *only* pointer that will ever be returned to T. Our . // reference count is guaranteed to be 1 at this point, and we required . // the `Rc` itself to be `mut`, so we're returning the only possible . // reference to the allocation. 177,481 ( 0.00%) unsafe { &mut this.ptr.as_mut().value } 1,068,198 ( 0.01%) } . } . . impl Rc { . #[inline] . #[stable(feature = "rc_downcast", since = "1.29.0")] . /// Attempt to downcast the `Rc` to a concrete type. . /// . /// # Examples -- line 1213 ---------------------------------------- -- line 1344 ---------------------------------------- . ) . } . } . . /// Copy elements from slice into newly allocated Rc<\[T\]> . /// . /// Unsafe because the caller must either take ownership or bind `T: Copy` . #[cfg(not(no_global_oom_handling))] 42,759 ( 0.00%) unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> { . unsafe { . let ptr = Self::allocate_for_slice(v.len()); 9,138 ( 0.00%) ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).value as *mut [T] as *mut T, v.len()); . Self::from_ptr(ptr) . } 55,098 ( 0.00%) } . . /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size. . /// . /// Behavior is undefined should the size be wrong. . #[cfg(not(no_global_oom_handling))] . unsafe fn from_iter_exact(iter: impl iter::Iterator, len: usize) -> Rc<[T]> { . // Panic guard while cloning T elements. . // In the event of a panic, elements that have been written -- line 1366 ---------------------------------------- -- line 1419 ---------------------------------------- . unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) } . } . } . . #[cfg(not(no_global_oom_handling))] . impl RcFromSlice for Rc<[T]> { . #[inline] . fn from_slice(v: &[T]) -> Self { 13 ( 0.00%) unsafe { Rc::copy_from_slice(v) } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Deref for Rc { . type Target = T; . . #[inline(always)] . fn deref(&self) -> &T { 707,237 ( 0.00%) &self.inner().value . } . } . . #[unstable(feature = "receiver_trait", issue = "none")] . impl Receiver for Rc {} . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc { -- line 1445 ---------------------------------------- -- line 1463 ---------------------------------------- . /// } . /// . /// let foo = Rc::new(Foo); . /// let foo2 = Rc::clone(&foo); . /// . /// drop(foo); // Doesn't print anything . /// drop(foo2); // Prints "dropped!" . /// ``` 9,498,257 ( 0.06%) fn drop(&mut self) { . unsafe { 2,055,362 ( 0.01%) self.inner().dec_strong(); 5,333,074 ( 0.03%) if self.inner().strong() == 0 { . // destroy the contained object 229,598 ( 0.00%) ptr::drop_in_place(Self::get_mut_unchecked(self)); . . // remove the implicit "strong weak" pointer now that we've . // destroyed the contents. 1 ( 0.00%) self.inner().dec_weak(); . 1,979,243 ( 0.01%) if self.inner().weak() == 0 { 6,140 ( 0.00%) Global.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref())); . } . } . } 6,566,786 ( 0.04%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Rc { . /// Makes a clone of the `Rc` pointer. . /// . /// This creates another pointer to the same allocation, increasing the . /// strong reference count. -- line 1495 ---------------------------------------- -- line 1562 ---------------------------------------- . /// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to . /// the same value, than two `&T`s. . /// . /// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive. . #[stable(feature = "rust1", since = "1.0.0")] . impl RcEqIdent for Rc { . #[inline] . fn eq(&self, other: &Rc) -> bool { 6,870 ( 0.00%) Rc::ptr_eq(self, other) || **self == **other . } . . #[inline] . fn ne(&self, other: &Rc) -> bool { . !Rc::ptr_eq(self, other) && **self != **other . } . } . -- line 1578 ---------------------------------------- -- line 1879 ---------------------------------------- . /// # use std::rc::Rc; . /// let original: Box> = Box::new(vec![1, 2, 3]); . /// let shared: Rc> = Rc::from(original); . /// assert_eq!(vec![1, 2, 3], *shared); . /// ``` . #[inline] . fn from(mut v: Vec) -> Rc<[T]> { . unsafe { 12,353 ( 0.00%) let rc = Rc::copy_from_slice(&v); . . // Allow the Vec to free its memory, but not destroy its contents . v.set_len(0); . . rc . } . } . } -- line 1895 ---------------------------------------- -- line 2080 ---------------------------------------- . #[must_use] . pub fn new() -> Weak { . Weak { ptr: NonNull::new(usize::MAX as *mut RcBox).expect("MAX is not 0") } . } . } . . pub(crate) fn is_dangling(ptr: *mut T) -> bool { . let address = ptr as *mut () as usize; 164 ( 0.00%) address == usize::MAX . } . . /// Helper type to allow accessing the reference counts without . /// making any assertions about the data field. . struct WeakInner<'a> { . weak: &'a Cell, . strong: &'a Cell, . } -- line 2096 ---------------------------------------- -- line 2299 ---------------------------------------- . }) . .unwrap_or(0) . } . . /// Returns `None` when the pointer is dangling and there is no allocated `RcBox`, . /// (i.e., when this `Weak` was created by `Weak::new`). . #[inline] . fn inner(&self) -> Option> { 1 ( 0.00%) if is_dangling(self.ptr.as_ptr()) { . None . } else { . // We are careful to *not* create a reference covering the "data" field, as . // the field may be mutated concurrently (for example, if the last `Rc` . // is dropped, the data field will be dropped in-place). . Some(unsafe { . let ptr = self.ptr.as_ptr(); . WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak } -- line 2315 ---------------------------------------- -- line 2391 ---------------------------------------- . /// assert!(other_weak_foo.upgrade().is_none()); . /// ``` . fn drop(&mut self) { . let inner = if let Some(inner) = self.inner() { inner } else { return }; . . inner.dec_weak(); . // the weak count starts at 1, and will only go to zero if all . // the strong pointers have disappeared. 2 ( 0.00%) if inner.weak() == 0 { . unsafe { . Global.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr())); . } . } . } . } . . #[stable(feature = "rc_weak", since = "1.4.0")] -- line 2407 ---------------------------------------- -- line 2469 ---------------------------------------- . . #[inline] . fn strong(&self) -> usize { . self.strong_ref().get() . } . . #[inline] . fn inc_strong(&self) { 1,676,623 ( 0.01%) let strong = self.strong(); . . // We want to abort on overflow instead of dropping the value. . // The reference count will never be zero when this is called; . // nevertheless, we insert an abort here to hint LLVM at . // an otherwise missed optimization. 5,132,097 ( 0.03%) if strong == 0 || strong == usize::MAX { . abort(); . } 25,747 ( 0.00%) self.strong_ref().set(strong + 1); . } . . #[inline] . fn dec_strong(&self) { 8,008,046 ( 0.05%) self.strong_ref().set(self.strong() - 1); . } . . #[inline] . fn weak(&self) -> usize { . self.weak_ref().get() . } . . #[inline] -- line 2499 ---------------------------------------- -- line 2507 ---------------------------------------- . if weak == 0 || weak == usize::MAX { . abort(); . } . self.weak_ref().set(weak + 1); . } . . #[inline] . fn dec_weak(&self) { 2,926,008 ( 0.02%) self.weak_ref().set(self.weak() - 1); . } . } . . impl RcInnerPtr for RcBox { . #[inline(always)] . fn weak_ref(&self) -> &Cell { . &self.weak . } -- line 2523 ---------------------------------------- 1,383,444 ( 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")] 4,860 ( 0.00%) pub fn from_str_radix(src: &str, radix: u32) -> Result { 2,430 ( 0.00%) from_str_radix(src, radix) 7,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 { 1,337,160 ( 0.01%) 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 { 1,671,906 ( 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,333,069 ( 0.01%) 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 { 75,807,224 ( 0.45%) intrinsics::rotate_left(self, n as $SelfT) . } . . /// Shifts the bits to the right by a specified amount, `n`, . /// wrapping the truncated bits to the beginning of the resulting . /// integer. . /// . /// Please note this isn't the same operation as the `>>` shifting operator! . /// -- line 220 ---------------------------------------- -- line 430 ---------------------------------------- . #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] . pub const fn checked_add(self, rhs: Self) -> Option { 4 ( 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`. 3,045,987 ( 0.02%) 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`. 459,543 ( 0.00%) unsafe { intrinsics::unchecked_sub(self, rhs) } . } . . /// Checked integer multiplication. Computes `self * rhs`, returning . /// `None` if overflow occurred. . /// . /// # Examples . /// . /// Basic usage: -- line 541 ---------------------------------------- -- line 596 ---------------------------------------- . without modifying the original"] . #[inline] . pub const fn checked_div(self, rhs: Self) -> Option { . if unlikely!(rhs == 0) { . None . } else { . // SAFETY: div by zero has been checked above and unsigned types have no other . // failure modes for division 640 ( 0.00%) Some(unsafe { intrinsics::unchecked_div(self, rhs) }) . } . } . . /// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None` . /// if `rhs == 0`. . /// . /// # Examples . /// -- line 612 ---------------------------------------- -- line 1035 ---------------------------------------- . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")] . #[inline(always)] . pub const fn saturating_add(self, rhs: Self) -> Self { 950,039 ( 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 { 43,994 ( 0.00%) intrinsics::saturating_sub(self, rhs) . } . . /// Saturating integer multiplication. Computes `self * rhs`, . /// saturating at the numeric bounds instead of overflowing. . /// . /// # Examples . /// . /// Basic usage: -- line 1100 ---------------------------------------- -- line 1104 ---------------------------------------- . #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),"::MAX);")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] . pub const fn saturating_mul(self, rhs: Self) -> Self { 6 ( 0.00%) match self.checked_mul(rhs) { . Some(x) => x, . None => Self::MAX, . } . } . . /// Saturating integer division. Computes `self / rhs`, saturating at the . /// numeric bounds instead of overflowing. . /// -- line 1120 ---------------------------------------- -- line 1175 ---------------------------------------- . #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_add(self, rhs: Self) -> Self { 43,552,912 ( 0.26%) 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 { 9,279,445 ( 0.06%) 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 { 23,531,518 ( 0.14%) 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 { 4 ( 0.00%) intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT) . } . } . . /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, . /// where `mask` removes any high-order bits of `rhs` that . /// would cause the shift to exceed the bitwidth of the type. . /// . /// Note that this is *not* the same as a rotate-right; the -- line 1413 ---------------------------------------- -- line 1491 ---------------------------------------- . #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")] . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] 53 ( 0.00%) pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) { 3,660,874 ( 0.02%) let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) 106 ( 0.00%) } . . /// Calculates `self + rhs + carry` without the ability to overflow. . /// . /// Performs "ternary addition" which takes in an extra bit to add, and may return an . /// additional bit of overflow. This allows for chaining together multiple additions . /// to create "big integers" which represent larger values. . /// . #[doc = concat!("This can be thought of as a ", stringify!($BITS), "-bit \"full adder\", in the electronics sense.")] -- line 1510 ---------------------------------------- -- line 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) { 631,469 ( 0.00%) 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) { 7,877,376 ( 0.05%) let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// Calculates the divisor when `self` is divided by `rhs`. . /// . /// Returns a tuple of the divisor along with a boolean indicating . /// whether an arithmetic overflow would occur. Note that for unsigned . /// integers overflow never occurs, so the second value is always -- line 1690 ---------------------------------------- -- line 2132 ---------------------------------------- . #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")] . #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")] . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")] . #[inline(always)] . pub const fn is_power_of_two(self) -> bool { 198 ( 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 { 175,152 ( 0.00%) if self <= 1 { return 0; } . 252,618 ( 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. 757,644 ( 0.00%) let z = unsafe { intrinsics::ctlz_nonzero(p) }; 252,588 ( 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 { 329,964 ( 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 ---------------------------------------- 592,233 ( 0.00%) -------------------------------------------------------------------------------- The following files chosen for auto-annotation could not be found: -------------------------------------------------------------------------------- ./elf/../sysdeps/x86_64/tls_get_addr.S ./elf/dl-lookup.c ./malloc/malloc.c ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S ./string/../sysdeps/x86_64/multiarch/strcmp-avx2.S /tmp/gcc-build/x86_64-unknown-linux-gnu/libstdc++-v3/libsupc++/../../../../gcc-5.5.0/libstdc++-v3/libsupc++/new_op.cc -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 3,664,317,257 (21.89%) events annotated