-------------------------------------------------------------------------------- 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 wasmparser --edition=2018 src/lib.rs --error-format=json --json=diagnostic-rendered-ansi,artifacts,future-incompat --crate-type lib --emit=dep-info,metadata,link -C embed-bitcode=no -C debuginfo=2 -C metadata=2d147051a8f46099 -C extra-filename=-2d147051a8f46099 --out-dir /usr/home/liquid/tmp/.tmpDZFXZp/target/debug/deps -L dependency=/usr/home/liquid/tmp/.tmpDZFXZp/target/debug/deps -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-wasmparser-0.82.0-Debug-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 17,642,037,404 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 566,943,264 ( 3.21%) ???:llvm::FPPassManager::runOnFunction(llvm::Function&) 469,837,996 ( 2.66%) ???:llvm::SelectionDAG::Combine(llvm::CombineLevel, llvm::AAResults*, llvm::CodeGenOpt::Level) 439,757,047 ( 2.49%) ./malloc/malloc.c:_int_malloc 422,383,239 ( 2.39%) ./malloc/malloc.c:_int_free 259,505,047 ( 1.47%) ./malloc/malloc.c:malloc 211,780,380 ( 1.20%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 195,881,925 ( 1.11%) ???:(anonymous namespace)::Verifier::visitInstruction(llvm::Instruction&) 176,507,419 ( 1.00%) ???:llvm::AttributeList::addAttributes(llvm::LLVMContext&, unsigned int, llvm::AttrBuilder const&) const 164,104,652 ( 0.93%) ???:llvm::MachineInstr::addOperand(llvm::MachineFunction&, llvm::MachineOperand const&) 154,575,561 ( 0.88%) ???:(anonymous namespace)::RegAllocFast::allocateBasicBlock(llvm::MachineBasicBlock&) 147,069,112 ( 0.83%) ???:llvm::raw_svector_ostream::write_impl(char const*, unsigned long) 141,251,177 ( 0.80%) ???:(anonymous namespace)::Verifier::visitMDNode(llvm::MDNode const&, (anonymous namespace)::Verifier::AreDebugLocsAllowed) 140,367,895 ( 0.80%) ???:llvm::SelectionDAGISel::SelectCodeCommon(llvm::SDNode*, unsigned char const*, unsigned int) 131,578,115 ( 0.75%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/fulfill.rs:>::process_obligations::> 120,919,552 ( 0.69%) ./malloc/malloc.c:free 120,565,694 ( 0.68%) ???:llvm::PMDataManager::verifyPreservedAnalysis(llvm::Pass*) 114,813,063 ( 0.65%) ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S:__memset_avx2_erms 109,938,172 ( 0.62%) ???:llvm::MCExpr::evaluateAsRelocatableImpl(llvm::MCValue&, llvm::MCAssembler const*, llvm::MCAsmLayout const*, llvm::MCFixup const*, llvm::DenseMap, llvm::detail::DenseMapPair > const*, bool) const 97,164,099 ( 0.55%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/obligation_forest/mod.rs:>::process_obligations::> 84,198,456 ( 0.48%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:>::process_obligations::> 83,376,731 ( 0.47%) ???:llvm::ScheduleDAGSDNodes::BuildSchedUnits() 81,346,243 ( 0.46%) ???:(anonymous namespace)::VarLocBasedLDV::process(llvm::MachineInstr&, (anonymous namespace)::VarLocBasedLDV::OpenRangesSet&, (anonymous namespace)::VarLocBasedLDV::VarLocMap&, llvm::SmallVector<(anonymous namespace)::VarLocBasedLDV::TransferDebugPair, 4u>&) 72,976,814 ( 0.41%) ???:llvm::TargetLoweringBase::getTypeConversion(llvm::LLVMContext&, llvm::EVT) const 69,158,125 ( 0.39%) ???:llvm::MCAsmLayout::getSymbolOffset(llvm::MCSymbol const&) const 68,687,065 ( 0.39%) ???:(anonymous namespace)::Verifier::visitCallBase(llvm::CallBase&) 68,597,553 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>::process_obligations::> 65,545,020 ( 0.37%) ./malloc/malloc.c:malloc_consolidate 62,456,792 ( 0.35%) ???:llvm::TargetRegisterInfo::shouldRealignStack(llvm::MachineFunction const&) const 60,905,305 ( 0.35%) ???:(anonymous namespace)::TwoAddressInstructionPass::runOnMachineFunction(llvm::MachineFunction&) 56,096,754 ( 0.32%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs:>::process_obligations::> 56,038,953 ( 0.32%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/type_variable.rs:>::process_obligations::> 55,880,829 ( 0.32%) ???:(anonymous namespace)::X86MCCodeEmitter::emitPrefixImpl(unsigned int&, llvm::MCInst const&, llvm::MCSubtargetInfo const&, llvm::raw_ostream&) const 55,840,990 ( 0.32%) ???:llvm::SmallSet >::insert(llvm::Register const&) 55,697,621 ( 0.32%) ???:llvm::MCAsmLayout::getFragmentOffset(llvm::MCFragment const*) const 54,565,812 ( 0.31%) ???:llvm::MetadataTracking::track(void*, llvm::Metadata&, llvm::PointerUnion) 54,386,259 ( 0.31%) ???:llvm::SelectionDAG::MorphNodeTo(llvm::SDNode*, unsigned int, llvm::SDVTList, llvm::ArrayRef) 54,371,609 ( 0.31%) ???:(anonymous namespace)::Verifier::verify(llvm::Function const&) [clone .llvm.4153962086227604281] 54,229,243 ( 0.31%) ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S:__memcmp_avx2_movbe 53,378,359 ( 0.30%) ???:llvm::StringMapImpl::LookupBucketFor(llvm::StringRef) 52,939,173 ( 0.30%) ???:llvm::InstrEmitter::EmitMachineNode(llvm::SDNode*, bool, bool, llvm::DenseMap, llvm::detail::DenseMapPair >&) 52,584,813 ( 0.30%) ???:llvm::DAGTypeLegalizer::run() 52,252,593 ( 0.30%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 52,214,089 ( 0.30%) ???:llvm::MCObjectStreamer::emitBytes(llvm::StringRef) 51,375,653 ( 0.29%) ./malloc/malloc.c:unlink_chunk.constprop.0 50,055,406 ( 0.28%) ???:llvm::DomTreeBuilder::SemiNCAInfo >::CalculateFromScratch(llvm::DominatorTreeBase&, llvm::DomTreeBuilder::SemiNCAInfo >::BatchUpdateInfo*) 50,053,520 ( 0.28%) ???:(anonymous namespace)::SelectionDAGLegalize::LegalizeOp(llvm::SDNode*) [clone .llvm.8386621111310650999] 49,678,792 ( 0.28%) ???:(anonymous namespace)::DAGCombiner::combine(llvm::SDNode*) 49,605,582 ( 0.28%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_sse2_unaligned_erms 48,996,698 ( 0.28%) ???:llvm::SelectionDAG::getConstant(llvm::ConstantInt const&, llvm::SDLoc const&, llvm::EVT, bool, bool) 47,840,046 ( 0.27%) ???:(anonymous namespace)::Verifier::verifyFunctionAttrs(llvm::FunctionType*, llvm::AttributeList, llvm::Value const*, bool) 47,372,991 ( 0.27%) ???:llvm::coro::declaresIntrinsics(llvm::Module const&, std::initializer_list) 47,160,712 ( 0.27%) ???:llvm::TargetRegisterInfo::checkAllSuperRegsMarked(llvm::BitVector const&, llvm::ArrayRef) const 46,747,295 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/select/mod.rs:>::process_obligations::> 46,707,036 ( 0.26%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/ena-0.14.0/src/snapshot_vec.rs:>::process_obligations::> 45,942,322 ( 0.26%) ???:llvm::FoldingSetNodeID::AddInteger(unsigned int) 44,129,878 ( 0.25%) ???:llvm::SelectionDAG::Legalize() 43,449,512 ( 0.25%) ???:llvm::FoldingSetBase::FindNodeOrInsertPos(llvm::FoldingSetNodeID const&, void*&, llvm::FoldingSetBase::FoldingSetInfo const&) 42,784,948 ( 0.24%) ???:llvm::SmallPtrSetImplBase::insert_imp_big(void const*) 42,783,337 ( 0.24%) ./string/../sysdeps/x86_64/multiarch/strcmp-avx2.S:__strncmp_avx2 42,331,197 ( 0.24%) ???:(anonymous namespace)::VarLocBasedLDV::ExtendRanges(llvm::MachineFunction&, llvm::TargetPassConfig*) [clone .llvm.4451506318407214204] 40,720,159 ( 0.23%) ???:llvm::MCContext::getOrCreateSymbol(llvm::Twine const&) 40,626,056 ( 0.23%) ???:(anonymous namespace)::PEI::runOnMachineFunction(llvm::MachineFunction&) 40,446,003 ( 0.23%) ???:llvm::calculateDbgEntityHistory(llvm::MachineFunction const*, llvm::TargetRegisterInfo const*, llvm::DbgValueHistoryMap&, llvm::DbgLabelInstrMap&) 38,229,038 ( 0.22%) ???:multikeySort(llvm::MutableArrayRef*>, int) 37,285,695 ( 0.21%) ./stdlib/msort.c:msort_with_tmp.part.0 36,560,379 ( 0.21%) ???:(anonymous namespace)::X86MCInstLower::Lower(llvm::MachineInstr const*, llvm::MCInst&) const 34,586,185 ( 0.20%) ???:llvm::FunctionLoweringInfo::set(llvm::Function const&, llvm::MachineFunction&, llvm::SelectionDAG*) 34,496,806 ( 0.20%) ???:(anonymous namespace)::ScheduleDAGRRList::Schedule() [clone .llvm.6953762222372402862] 34,019,973 ( 0.19%) ???:(anonymous namespace)::ELFObjectWriter::recordRelocation(llvm::MCAssembler&, llvm::MCAsmLayout const&, llvm::MCFragment const*, llvm::MCFixup const&, llvm::MCValue, unsigned long&) [clone .llvm.14145361893594770252] 33,817,494 ( 0.19%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:>::try_reserve 32,528,818 ( 0.18%) ???:llvm::MachineFunction::CreateMachineInstr(llvm::MCInstrDesc const&, llvm::DebugLoc const&, bool) 32,009,926 ( 0.18%) ???:llvm::X86FrameLowering::hasFP(llvm::MachineFunction const&) const 31,979,927 ( 0.18%) ???:(anonymous namespace)::X86MCCodeEmitter::encodeInstruction(llvm::MCInst const&, llvm::raw_ostream&, llvm::SmallVectorImpl&, llvm::MCSubtargetInfo const&) const 30,766,057 ( 0.17%) ???:llvm::DataLayout::getAlignment(llvm::Type*, bool) const 30,479,467 ( 0.17%) ???:llvm::DwarfDebug::beginInstruction(llvm::MachineInstr const*) 29,324,555 ( 0.17%) ???:(anonymous namespace)::Verifier::visitFunction(llvm::Function const&)::$_3::operator()(llvm::Instruction const&, llvm::MDNode const*) const 28,783,583 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs:::lookup_source_file_idx 28,664,039 ( 0.16%) ???:llvm::InstrEmitter::EmitCopyFromReg(llvm::SDNode*, unsigned int, bool, bool, llvm::Register, llvm::DenseMap, llvm::detail::DenseMapPair >&) 28,402,047 ( 0.16%) ???:llvm::SelectionDAGISel::SelectAllBasicBlocks(llvm::Function const&) 28,388,682 ( 0.16%) ???:(anonymous namespace)::CFIInstrInserter::runOnMachineFunction(llvm::MachineFunction&) 27,621,311 ( 0.16%) ???:(anonymous namespace)::RegAllocFast::markRegUsedInInstr(unsigned short) 27,446,017 ( 0.16%) ???:llvm::AttributeSetNode::get(llvm::LLVMContext&, llvm::AttrBuilder const&) 27,150,368 ( 0.15%) ???:llvm::ScheduleDAGSDNodes::AddSchedEdges() 25,978,037 ( 0.15%) ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S:__memset_avx2_unaligned_erms 25,872,351 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:::eq 25,820,990 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_index/src/bit_set.rs:>::union::> 25,768,318 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs:::attrs 25,712,345 ( 0.15%) ???:llvm::MDNode::MDNode(llvm::LLVMContext&, unsigned int, llvm::Metadata::StorageType, llvm::ArrayRef, llvm::ArrayRef) 25,626,019 ( 0.15%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::iter::traits::collect::Extend<&rustc_mir_build::thir::pattern::deconstruct_pat::DeconstructedPat>>::extend::> 25,615,397 ( 0.15%) ???:llvm::FoldingSet::NodeEquals(llvm::FoldingSetBase const*, llvm::FoldingSetBase::Node*, llvm::FoldingSetNodeID const&, unsigned int, llvm::FoldingSetNodeID&) 25,433,631 ( 0.14%) ???:llvm::DomTreeBuilder::SemiNCAInfo >::runSemiNCA(llvm::DominatorTreeBase&, unsigned int) 25,237,644 ( 0.14%) ./malloc/malloc.c:realloc 25,197,533 ( 0.14%) ???:llvm::MCAssembler::layout(llvm::MCAsmLayout&) 25,133,006 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:>::insert_from_slice 25,096,089 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs:rustc_mir_dataflow::drop_flag_effects::on_all_children_bits::is_terminal_path 25,067,609 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/pattern/deconstruct_pat.rs:rustc_mir_build::thir::pattern::usefulness::is_useful 24,986,384 ( 0.14%) ???:llvm::Twine::printOneChild(llvm::raw_ostream&, llvm::Twine::Child, llvm::Twine::NodeKind) const 24,948,848 ( 0.14%) ???:llvm::SelectionDAG::AssignTopologicalOrder() 24,825,852 ( 0.14%) ???:(anonymous namespace)::ELFWriter::writeObject(llvm::MCAssembler&, llvm::MCAsmLayout const&) 24,695,235 ( 0.14%) ???:(anonymous namespace)::X86MCCodeEmitter::emitMemModRMByte(llvm::MCInst const&, unsigned int, unsigned int, unsigned long, bool, unsigned long, llvm::raw_ostream&, llvm::SmallVectorImpl&, llvm::MCSubtargetInfo const&, bool) const 24,681,139 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 24,475,779 ( 0.14%) ???:llvm::raw_ostream::write(char const*, unsigned long) 24,302,164 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:rustc_mir_build::thir::pattern::usefulness::is_useful 24,138,050 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 23,707,382 ( 0.13%) ???:llvm::PMDataManager::removeNotPreservedAnalysis(llvm::Pass*) 23,616,289 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/obligation_forest/mod.rs:>::compress::<>::process_obligations>::{closure#0}> 23,394,129 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::intern_ty 23,110,229 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:::hash:: 22,831,725 ( 0.13%) ???:llvm::X86RegisterInfo::eliminateFrameIndex(llvm::MachineInstrBundleIterator, int, unsigned int, llvm::RegScavenger*) const 22,744,468 ( 0.13%) ???:llvm::TargetLowering::SimplifyDemandedBits(llvm::SDValue, llvm::APInt const&, llvm::APInt const&, llvm::KnownBits&, llvm::TargetLowering::TargetLoweringOpt&, unsigned int, bool) const 22,742,548 ( 0.13%) ???:llvm::X86TargetMachine::getTargetTransformInfo(llvm::Function const&) 22,692,912 ( 0.13%) /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) 22,652,396 ( 0.13%) ???:llvm::MCELFStreamer::emitInstToData(llvm::MCInst const&, llvm::MCSubtargetInfo const&) 22,462,805 ( 0.13%) ???:llvm::AsmPrinter::emitFunctionBody() 22,285,972 ( 0.13%) ???:llvm::SelectionDAG::getRegister(unsigned int, llvm::EVT) 22,110,284 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::shallow_resolve_ty 21,960,989 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/search.rs:>::search_tree:: 21,850,862 ( 0.12%) ???:llvm::SelectionDAG::getNode(unsigned int, llvm::SDLoc const&, llvm::EVT, llvm::SDValue, llvm::SDValue, llvm::SDNodeFlags) 21,816,581 ( 0.12%) ???:(anonymous namespace)::VarLocBasedLDV::collectIDsForRegs(llvm::SmallSet >&, llvm::SmallSet > const&, llvm::CoalescingBitVector const&, (anonymous namespace)::VarLocBasedLDV::VarLocMap const&) 21,796,960 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:>::process_obligations::> 21,735,244 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/pattern/usefulness.rs:rustc_mir_build::thir::pattern::usefulness::is_useful 21,590,088 ( 0.12%) ???:llvm::MCObjectStreamer::emitInstruction(llvm::MCInst const&, llvm::MCSubtargetInfo const&) 21,581,954 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::apply_rewrites 21,547,987 ( 0.12%) ???:llvm::FoldingSet::NodeEquals(llvm::FoldingSetBase const*, llvm::FoldingSetBase::Node*, llvm::FoldingSetNodeID const&, unsigned int, llvm::FoldingSetNodeID&) 21,014,446 ( 0.12%) ???:llvm::MCDwarfLineAddr::Encode(llvm::MCContext&, llvm::MCDwarfLineTableParams, long, unsigned long, llvm::raw_ostream&) 20,768,236 ( 0.12%) ???:llvm::MCELFStreamer::emitLabel(llvm::MCSymbol*, llvm::SMLoc) 20,766,816 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/intrinsics.rs:>::compress::<>::process_obligations>::{closure#0}> 20,345,062 ( 0.12%) ???:llvm::LLVMContextImpl::~LLVMContextImpl() 20,210,562 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/obligation_forest/mod.rs:>::apply_rewrites 20,143,582 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs:::line_begin_pos 20,143,582 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs:::lookup_line 19,462,451 ( 0.11%) ???:llvm::SelectionDAG::computeKnownBits(llvm::SDValue, llvm::APInt const&, unsigned int) const 19,435,942 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 19,347,641 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 19,296,942 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_transform/src/simplify.rs:::simplify 19,136,959 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:>::process_obligations::> 19,044,514 ( 0.11%) ???:llvm::MDString::get(llvm::LLVMContext&, llvm::StringRef) 19,003,205 ( 0.11%) ???:llvm::ScheduleDAGSDNodes::EmitSchedule(llvm::MachineInstrBundleIterator&) 18,764,718 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/ena-0.14.0/src/unify/mod.rs:>::process_obligations::> 18,643,809 ( 0.11%) ???:(anonymous namespace)::RegAllocFast::setPhysReg(llvm::MachineInstr&, llvm::MachineOperand&, unsigned short) 18,627,303 ( 0.11%) ???:llvm::LazyCallGraph::Node::populateSlow() 18,486,354 ( 0.10%) ???:??? 18,413,009 ( 0.10%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:memcpy@GLIBC_2.2.5 18,212,431 ( 0.10%) ???:(anonymous namespace)::X86AsmBackend::applyFixup(llvm::MCAssembler const&, llvm::MCFixup const&, llvm::MCValue const&, llvm::MutableArrayRef, unsigned long, bool, llvm::MCSubtargetInfo const*) const 18,074,535 ( 0.10%) ???:llvm::SelectionDAG::getNode(unsigned int, llvm::SDLoc const&, llvm::SDVTList, llvm::ArrayRef) 17,967,012 ( 0.10%) ???:llvm::Function::dropAllReferences() 17,784,625 ( 0.10%) ???:llvm::MCAssembler::layoutSectionOnce(llvm::MCAsmLayout&, llvm::MCSection&) 17,784,540 ( 0.10%) ???:(anonymous namespace)::DAGCombiner::recursivelyDeleteUnusedNodes(llvm::SDNode*) 17,772,420 ( 0.10%) ???:llvm::CoalescingBitVector::find(unsigned long) const 17,760,631 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/traversal.rs:::traverse_successor 17,713,207 ( 0.10%) ./malloc/malloc.c:_int_realloc 17,654,402 ( 0.10%) ???:llvm::TargetLoweringBase::ArgListEntry::setAttributes(llvm::CallBase const*, unsigned int) 17,649,609 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>, (), core::hash::BuildHasherDefault>>::from_hash::>>::{closure#0}> -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs -------------------------------------------------------------------------------- Ir -- line 141 ---------------------------------------- . /// ``` . /// let a = [1, 2, 3]; . /// assert!(!a.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.39.0")] . #[inline] . pub const fn is_empty(&self) -> bool { 2,466,321 ( 0.01%) self.len() == 0 . } . . /// Returns the first element of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; -- line 157 ---------------------------------------- -- line 159 ---------------------------------------- . /// . /// let w: &[i32] = &[]; . /// assert_eq!(None, w.first()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn first(&self) -> Option<&T> { 12,218 ( 0.00%) if let [first, ..] = self { Some(first) } else { None } . } . . /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 175 ---------------------------------------- -- line 178 ---------------------------------------- . /// *first = 5; . /// } . /// assert_eq!(x, &[5, 1, 2]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")] . #[inline] . pub const fn first_mut(&mut self) -> Option<&mut T> { 20,020 ( 0.00%) if let [first, ..] = self { Some(first) } else { None } . } . . /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &[0, 1, 2]; -- line 194 ---------------------------------------- -- line 197 ---------------------------------------- . /// assert_eq!(first, &0); . /// assert_eq!(elements, &[1, 2]); . /// } . /// ``` . #[stable(feature = "slice_splits", since = "1.5.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn split_first(&self) -> Option<(&T, &[T])> { 18 ( 0.00%) if let [first, tail @ ..] = self { Some((first, tail)) } else { None } . } . . /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 213 ---------------------------------------- -- line 237 ---------------------------------------- . /// assert_eq!(last, &2); . /// assert_eq!(elements, &[0, 1]); . /// } . /// ``` . #[stable(feature = "slice_splits", since = "1.5.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn split_last(&self) -> Option<(&T, &[T])> { 80,229 ( 0.00%) if let [init @ .., last] = self { Some((last, init)) } else { None } . } . . /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 253 ---------------------------------------- -- line 276 ---------------------------------------- . /// . /// let w: &[i32] = &[]; . /// assert_eq!(None, w.last()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn last(&self) -> Option<&T> { 1,122,367 ( 0.01%) if let [.., last] = self { Some(last) } else { None } . } . . /// Returns a mutable pointer to the last item in the slice. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 292 ---------------------------------------- -- line 295 ---------------------------------------- . /// *last = 10; . /// } . /// assert_eq!(x, &[0, 1, 10]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")] . #[inline] . pub const fn last_mut(&mut self) -> Option<&mut T> { 3,226,813 ( 0.02%) if let [.., last] = self { Some(last) } else { None } . } . . /// Returns a reference to an element or subslice depending on the type of . /// index. . /// . /// - If given a position, returns a reference to the element at that . /// position or `None` if out of bounds. . /// - If given a range, returns the subslice corresponding to that range, -- line 311 ---------------------------------------- -- line 448 ---------------------------------------- . /// } . /// ``` . /// . /// [`as_mut_ptr`]: slice::as_mut_ptr . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")] . #[inline] . pub const fn as_ptr(&self) -> *const T { 3,184,680 ( 0.02%) self as *const [T] as *const T . } . . /// Returns an unsafe mutable pointer to the slice's buffer. . /// . /// The caller must ensure that the slice outlives the pointer this . /// function returns, or else it will end up pointing to garbage. . /// . /// Modifying the container referenced by this slice may cause its buffer -- line 464 ---------------------------------------- -- line 476 ---------------------------------------- . /// } . /// } . /// assert_eq!(x, &[3, 4, 6]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline] . pub const fn as_mut_ptr(&mut self) -> *mut T { 31 ( 0.00%) self as *mut [T] as *mut T . } . . /// Returns the two raw pointers spanning the slice. . /// . /// The returned range is half-open, which means that the end pointer . /// points *one past* the last element of the slice. This way, an empty . /// slice is represented by two equal pointers, and the difference between . /// the two pointers represents the size of the slice. -- line 492 ---------------------------------------- -- line 582 ---------------------------------------- . /// v.swap(2, 4); . /// assert!(v == ["a", "b", "e", "d", "c"]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] . #[inline] . #[track_caller] . pub const fn swap(&mut self, a: usize, b: usize) { 192,154 ( 0.00%) let _ = &self[a]; 1,207,228 ( 0.01%) let _ = &self[b]; . . // SAFETY: we just checked that both `a` and `b` are in bounds . unsafe { self.swap_unchecked(a, b) } . } . . /// Swaps two elements in the slice, without doing bounds checking. . /// . /// For a safe alternative see [`swap`]. -- line 599 ---------------------------------------- -- line 677 ---------------------------------------- . . // Because this function is first compiled in isolation, . // this check tells LLVM that the indexing below is . // in-bounds. Then after inlining -- once the actual . // lengths of the slices are known -- it's removed. . let (a, b) = (&mut a[..n], &mut b[..n]); . . for i in 0..n { 15,146 ( 0.00%) mem::swap(&mut a[i], &mut b[n - 1 - i]); . } . } . } . . /// Returns an iterator over the slice. . /// . /// # Examples . /// -- line 693 ---------------------------------------- -- line 1499 ---------------------------------------- . /// assert_eq!(left, [1, 2, 3, 4, 5, 6]); . /// assert_eq!(right, []); . /// } . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] . pub fn split_at(&self, mid: usize) -> (&[T], &[T]) { 312 ( 0.00%) assert!(mid <= self.len()); . // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which . // fulfills the requirements of `from_raw_parts_mut`. . unsafe { self.split_at_unchecked(mid) } . } . . /// Divides one mutable slice into two at an index. . /// . /// The first will contain all indices from `[0, mid)` (excluding -- line 1515 ---------------------------------------- -- line 1530 ---------------------------------------- . /// left[1] = 2; . /// right[1] = 4; . /// assert_eq!(v, [1, 2, 3, 4, 5, 6]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] . pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) { 192,430 ( 0.00%) assert!(mid <= self.len()); . // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which . // fulfills the requirements of `from_raw_parts_mut`. . unsafe { self.split_at_mut_unchecked(mid) } . } . . /// Divides one slice into two at an index, without doing bounds checking. . /// . /// The first will contain all indices from `[0, mid)` (excluding -- line 1546 ---------------------------------------- -- line 1628 ---------------------------------------- . pub unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut [T], &mut [T]) { . let len = self.len(); . let ptr = self.as_mut_ptr(); . . // SAFETY: Caller has to check that `0 <= mid <= self.len()`. . // . // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference . // is fine. 21,014 ( 0.00%) unsafe { (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid)) } . } . . /// Divides one slice into an array and a remainder slice at an index. . /// . /// The array will contain all indices from `[0, N)` (excluding . /// the index `N` itself) and the slice will contain all . /// indices from `[N, len)` (excluding the index `len` itself). . /// -- line 1644 ---------------------------------------- -- line 2113 ---------------------------------------- . /// assert!(!v.iter().any(|e| e == "hi")); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn contains(&self, x: &T) -> bool . where . T: PartialEq, . { 2,456 ( 0.00%) cmp::SliceContains::slice_contains(x, self) . } . . /// Returns `true` if `needle` is a prefix of the slice. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; -- line 2129 ---------------------------------------- -- line 2142 ---------------------------------------- . /// assert!(v.starts_with(&[])); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn starts_with(&self, needle: &[T]) -> bool . where . T: PartialEq, . { . let n = needle.len(); 4,440 ( 0.00%) self.len() >= n && needle == &self[..n] . } . . /// Returns `true` if `needle` is a suffix of the slice. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; -- line 2158 ---------------------------------------- -- line 2171 ---------------------------------------- . /// assert!(v.ends_with(&[])); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn ends_with(&self, needle: &[T]) -> bool . where . T: PartialEq, . { . let (m, n) = (self.len(), needle.len()); 82,596 ( 0.00%) m >= n && needle == &self[m - n..] . } . . /// Returns a subslice with the prefix removed. . /// . /// If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. . /// If `prefix` is empty, simply returns the original slice. . /// . /// If the slice does not start with `prefix`, returns `None`. -- line 2187 ---------------------------------------- -- line 2293 ---------------------------------------- . /// s.insert(idx, num); . /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn binary_search(&self, x: &T) -> Result . where . T: Ord, . { 3 ( 0.00%) self.binary_search_by(|p| p.cmp(x)) . } . . /// Binary searches this sorted slice with a comparator function. . /// . /// The comparator function should implement an order consistent . /// with the sort order of the underlying slice, returning an . /// order code that indicates whether its argument is `Less`, . /// `Equal` or `Greater` the desired target. -- line 2309 ---------------------------------------- -- line 2345 ---------------------------------------- . #[inline] . pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result . where . F: FnMut(&'a T) -> Ordering, . { . let mut size = self.len(); . let mut left = 0; . let mut right = size; 17,662,168 ( 0.10%) while left < right { 27,668,441 ( 0.16%) let mid = left + size / 2; . . // SAFETY: the call is made safe by the following invariants: . // - `mid >= 0` . // - `mid < size`: `mid` is limited by `[left; right)` bound. 2,140,630 ( 0.01%) let cmp = f(unsafe { self.get_unchecked(mid) }); . . // The reason why we use if/else control flow rather than match . // is because match reorders comparison operations, which is perf sensitive. . // This is x86 asm for u8: https://rust.godbolt.org/z/8Y8Pra. 7,507,325 ( 0.04%) if cmp == Less { 13,599,786 ( 0.08%) left = mid + 1; 3,855,679 ( 0.02%) } else if cmp == Greater { . right = mid; . } else { . // SAFETY: same as the `get_unchecked` above . unsafe { crate::intrinsics::assume(mid < self.len()) }; . return Ok(mid); . } . 22,526,118 ( 0.13%) size = right - left; . } . Err(left) . } . . /// Binary searches this sorted slice with a key extraction function. . /// . /// Assumes that the slice is sorted by the key, for instance with . /// [`sort_by_key`] using the same key extraction function. -- line 2382 ---------------------------------------- -- line 3203 ---------------------------------------- . #[track_caller] . fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! { . panic!( . "source slice length ({}) does not match destination slice length ({})", . src_len, dst_len, . ); . } . 706,838 ( 0.00%) if self.len() != src.len() { . len_mismatch_fail(self.len(), src.len()); . } . . // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was . // checked to have the same length. The slices cannot overlap because . // mutable references are exclusive. . unsafe { . ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len()); -- line 3219 ---------------------------------------- -- line 3382 ---------------------------------------- . } . let gcd: usize = gcd(mem::size_of::(), mem::size_of::()); . let ts: usize = mem::size_of::() / gcd; . let us: usize = mem::size_of::() / gcd; . . // Armed with this knowledge, we can find how many `U`s we can fit! . let us_len = self.len() / ts * us; . // And how many `T`s will be in the trailing slice! 49,466 ( 0.00%) let ts_len = self.len() % ts; . (us_len, ts_len) . } . . /// Transmute the slice to a slice of another type, ensuring alignment of the types is . /// maintained. . /// . /// This method splits the slice into three distinct slices: prefix, correctly aligned middle . /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest -- line 3398 ---------------------------------------- -- line 3429 ---------------------------------------- . return (self, &[], &[]); . } . . // First, find at what point do we split between the first and 2nd slice. Easy with . // ptr.align_offset. . let ptr = self.as_ptr(); . // SAFETY: See the `align_to_mut` method for the detailed safety comment. . let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::()) }; 49,466 ( 0.00%) if offset > self.len() { . (self, &[], &[]) . } else { . let (left, rest) = self.split_at(offset); . let (us_len, ts_len) = rest.align_to_offsets::(); . // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay, . // since the caller guarantees that we can transmute `T` to `U` safely. . unsafe { . ( . left, . from_raw_parts(rest.as_ptr() as *const U, us_len), 49,466 ( 0.00%) from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len), . ) . } . } . } . . /// Transmute the slice to a slice of another type, ensuring alignment of the types is . /// maintained. . /// -- line 3456 ---------------------------------------- -- line 3731 ---------------------------------------- . /// let v = [1, 2, 3, 3, 5, 6, 7]; . /// let i = v.partition_point(|&x| x < 5); . /// . /// assert_eq!(i, 4); . /// assert!(v[..i].iter().all(|&x| x < 5)); . /// assert!(v[i..].iter().all(|&x| !(x < 5))); . /// ``` . #[stable(feature = "partition_point", since = "1.52.0")] 26 ( 0.00%) pub fn partition_point

(&self, mut pred: P) -> usize . where . P: FnMut(&T) -> bool, . { . self.binary_search_by(|x| if pred(x) { Less } else { Greater }).unwrap_or_else(|i| i) 52 ( 0.00%) } . . /// Removes the subslice corresponding to the given range . /// and returns a reference to it. . /// . /// Returns `None` and does not modify the slice if the given . /// range is out of bounds. . /// . /// Note that this method only accepts one-sided ranges such as -- line 3752 ---------------------------------------- 13,393,257 ( 0.08%) -------------------------------------------------------------------------------- -- 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. 128,404 ( 0.00%) unsafe { from_raw_parts(self.ptr.as_ptr(), len!(self)) } . } . . // Helper function for moving the start of the iterator forwards by `offset` elements, . // returning the old start. . // Unsafe because the offset must not exceed `self.len()`. . #[inline(always)] . unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T { . if mem::size_of::() == 0 { . zst_shrink!(self, offset); . self.ptr.as_ptr() . } else { . let old = self.ptr.as_ptr(); . // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`, . // so this new pointer is inside `self` and thus guaranteed to be non-null. 1,295,804 ( 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`. 11,961 ( 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 { 394,716 ( 0.00%) len!(self) . } . . #[inline(always)] . fn is_empty(&self) -> bool { . is_empty!(self) . } . } . -- line 128 ---------------------------------------- -- line 134 ---------------------------------------- . fn next(&mut self) -> Option<$elem> { . // could be implemented with slices, but this avoids bounds checks . . // SAFETY: `assume` calls are safe since a slice's start pointer . // must be non-null, and slices over non-ZSTs must also have a . // non-null end pointer. The call to `next_unchecked!` is safe . // since we check if the iterator is empty first. . unsafe { 833,987 ( 0.00%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 150,795 ( 0.00%) assume(!self.end.is_null()); . } 165,927,670 ( 0.94%) if is_empty!(self) { . None . } else { . Some(next_unchecked!(self)) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 8,366,203 ( 0.05%) let exact = len!(self); . (exact, Some(exact)) . } . . #[inline] . fn count(self) -> usize { . len!(self) . } . . #[inline] . fn nth(&mut self, n: usize) -> Option<$elem> { 69,760 ( 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() { 14,423 ( 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,823 ( 0.00%) while let Some(x) = self.next() { 90,964 ( 0.00%) if !f(x) { . return false; . } . } . true . } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] 8 ( 0.00%) fn any(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 1,335,139 ( 0.01%) while let Some(x) = self.next() { 1,425,469 ( 0.01%) if f(x) { . return true; . } . } . false 8 ( 0.00%) } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn find

(&mut self, mut predicate: P) -> Option . where . Self: Sized, . P: FnMut(&Self::Item) -> bool, . { 509,329 ( 0.00%) while let Some(x) = self.next() { 1,670,523 ( 0.01%) if predicate(&x) { . return Some(x); . } . } . None 398 ( 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, . { 51,637 ( 0.00%) while let Some(x) = self.next() { 466,910 ( 0.00%) if let Some(y) = f(x) { 51,477 ( 0.00%) return Some(y); . } . } . None 13,473 ( 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() { 1,627,636 ( 0.01%) if predicate(x) { . // SAFETY: we are guaranteed to be in bounds by the loop invariant: . // when `i >= n`, `self.next()` returns `None` and the loop breaks. . unsafe { assume(i < n) }; . return Some(i); . } . i += 1; . } . None -- line 303 ---------------------------------------- -- line 308 ---------------------------------------- . // faster to compile. Also, the `assume` avoids a bounds check. . #[inline] . fn rposition

(&mut self, mut predicate: P) -> Option where . P: FnMut(Self::Item) -> bool, . Self: Sized + ExactSizeIterator + DoubleEndedIterator . { . let n = len!(self); . let mut i = n; 76,070 ( 0.00%) while let Some(x) = self.next_back() { 1,076,805 ( 0.01%) i -= 1; 836,235 ( 0.00%) if predicate(x) { . // SAFETY: `i` must be lower than `n` since it starts at `n` . // and is only decreasing. . unsafe { assume(i < n) }; . return Some(i); . } . } . None . } -- line 326 ---------------------------------------- -- line 332 ---------------------------------------- . // the returned references is guaranteed to refer to an element . // of the slice and thus guaranteed to be valid. . // . // Also note that the caller also guarantees that we're never . // called with the same index again, and that no other methods . // that will access this subslice are called, so it is valid . // for the returned reference to be mutable in the case of . // `IterMut` 284,338 ( 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 { 18,118 ( 0.00%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 18,138 ( 0.00%) assume(!self.end.is_null()); . } 3,392,164 ( 0.02%) if is_empty!(self) { . None . } else { . Some(next_back_unchecked!(self)) . } . } . } . . #[inline] -- line 369 ---------------------------------------- 29,542,728 ( 0.17%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/traversal.rs -------------------------------------------------------------------------------- Ir -- line 23 ---------------------------------------- . pub struct Preorder<'a, 'tcx> { . body: &'a Body<'tcx>, . visited: BitSet, . worklist: Vec, . root_is_start_block: bool, . } . . impl<'a, 'tcx> Preorder<'a, 'tcx> { 167,740 ( 0.00%) pub fn new(body: &'a Body<'tcx>, root: BasicBlock) -> Preorder<'a, 'tcx> { 16,774 ( 0.00%) let worklist = vec![root]; . 50,322 ( 0.00%) Preorder { . body, . visited: BitSet::new_empty(body.basic_blocks().len()), 67,096 ( 0.00%) worklist, . root_is_start_block: root == START_BLOCK, . } 150,966 ( 0.00%) } . } . 19,458 ( 0.00%) pub fn preorder<'a, 'tcx>(body: &'a Body<'tcx>) -> Preorder<'a, 'tcx> { 61,728 ( 0.00%) Preorder::new(body, START_BLOCK) 29,187 ( 0.00%) } . . impl<'a, 'tcx> Iterator for Preorder<'a, 'tcx> { . type Item = (BasicBlock, &'a BasicBlockData<'tcx>); . 4,458,058 ( 0.03%) fn next(&mut self) -> Option<(BasicBlock, &'a BasicBlockData<'tcx>)> { 552,116 ( 0.00%) while let Some(idx) = self.worklist.pop() { 552,116 ( 0.00%) if !self.visited.insert(idx) { . continue; . } . 388,504 ( 0.00%) let data = &self.body[idx]; . 1,942,520 ( 0.01%) if let Some(ref term) = data.terminator { . self.worklist.extend(term.successors()); . } . . return Some((idx, data)); . } . . None 3,647,502 ( 0.02%) } . . fn size_hint(&self) -> (usize, Option) { . // All the blocks, minus the number of blocks we've visited. . let upper = self.body.basic_blocks().len() - self.visited.count(); . . let lower = if self.root_is_start_block { . // We will visit all remaining blocks exactly once. . upper -- line 74 ---------------------------------------- -- line 101 ---------------------------------------- . pub struct Postorder<'a, 'tcx> { . body: &'a Body<'tcx>, . visited: BitSet, . visit_stack: Vec<(BasicBlock, Successors<'a>)>, . root_is_start_block: bool, . } . . impl<'a, 'tcx> Postorder<'a, 'tcx> { 130,228 ( 0.00%) pub fn new(body: &'a Body<'tcx>, root: BasicBlock) -> Postorder<'a, 'tcx> { . let mut po = Postorder { . body, . visited: BitSet::new_empty(body.basic_blocks().len()), . visit_stack: Vec::new(), . root_is_start_block: root == START_BLOCK, . }; . . let data = &po.body[root]; . 130,228 ( 0.00%) if let Some(ref term) = data.terminator { . po.visited.insert(root); 74,416 ( 0.00%) po.visit_stack.push((root, term.successors())); 37,208 ( 0.00%) po.traverse_successor(); . } . . po 167,436 ( 0.00%) } . 2,818,081 ( 0.02%) fn traverse_successor(&mut self) { . // This is quite a complex loop due to 1. the borrow checker not liking it much . // and 2. what exactly is going on is not clear . // . // It does the actual traversal of the graph, while the `next` method on the iterator . // just pops off of the stack. `visit_stack` is a stack containing pairs of nodes and . // iterators over the successors of those nodes. Each iteration attempts to get the next . // node from the top of the stack, then pushes that node and an iterator over the . // successors to the top of the stack. This loop only grows `visit_stack`, stopping when -- line 136 ---------------------------------------- -- line 169 ---------------------------------------- . // . // Now that the top of the stack has no successors we can traverse, each item will . // be popped off during iteration until we get back to `A`. This yields [E, D, B]. . // . // When we yield `B` and call `traverse_successor`, we push `C` to the stack, but . // since we've already visited `E`, that child isn't added to the stack. The last . // two iterations yield `C` and finally `A` for a final traversal of [E, D, B, C, A] . loop { 2,826,100 ( 0.02%) let bb = if let Some(&mut (_, ref mut iter)) = self.visit_stack.last_mut() { 1,655,559 ( 0.01%) if let Some(&bb) = iter.next() { . bb . } else { . break; . } . } else { . break; . }; . 551,853 ( 0.00%) if self.visited.insert(bb) { 2,557,625 ( 0.01%) if let Some(term) = &self.body[bb].terminator { 1,461,500 ( 0.01%) self.visit_stack.push((bb, term.successors())); . } . } . } 3,220,664 ( 0.02%) } . } . 3,684 ( 0.00%) pub fn postorder<'a, 'tcx>(body: &'a Body<'tcx>) -> Postorder<'a, 'tcx> { 3,684 ( 0.00%) Postorder::new(body, START_BLOCK) 5,526 ( 0.00%) } . . impl<'a, 'tcx> Iterator for Postorder<'a, 'tcx> { . type Item = (BasicBlock, &'a BasicBlockData<'tcx>); . 140,763 ( 0.00%) fn next(&mut self) -> Option<(BasicBlock, &'a BasicBlockData<'tcx>)> { . let next = self.visit_stack.pop(); 383,979 ( 0.00%) if next.is_some() { 751,196 ( 0.00%) self.traverse_successor(); . } . 383,979 ( 0.00%) next.map(|(bb, _)| (bb, &self.body[bb])) 234,605 ( 0.00%) } . 13,695 ( 0.00%) fn size_hint(&self) -> (usize, Option) { . // All the blocks, minus the number of blocks we've visited. 56,055 ( 0.00%) let upper = self.body.basic_blocks().len() - self.visited.count(); . 56,055 ( 0.00%) let lower = if self.root_is_start_block { . // We will visit all remaining blocks exactly once. . upper . } else { . self.visit_stack.len() . }; . 8,217 ( 0.00%) (lower, Some(upper)) 19,173 ( 0.00%) } . } . . /// Reverse postorder traversal of a graph . /// . /// Reverse postorder is the reverse order of a postorder traversal. . /// This is different to a preorder traversal and represents a natural . /// linearization of control-flow. . /// -- line 232 ---------------------------------------- -- line 253 ---------------------------------------- . pub struct ReversePostorder<'a, 'tcx> { . body: &'a Body<'tcx>, . blocks: Vec, . idx: usize, . } . . impl<'a, 'tcx> ReversePostorder<'a, 'tcx> { . pub fn new(body: &'a Body<'tcx>, root: BasicBlock) -> ReversePostorder<'a, 'tcx> { 33,524 ( 0.00%) let blocks: Vec<_> = Postorder::new(body, root).map(|(bb, _)| bb).collect(); . 16,762 ( 0.00%) let len = blocks.len(); . 83,810 ( 0.00%) ReversePostorder { body, blocks, idx: len } . } . } . 100,572 ( 0.00%) pub fn reverse_postorder<'a, 'tcx>(body: &'a Body<'tcx>) -> ReversePostorder<'a, 'tcx> { . ReversePostorder::new(body, START_BLOCK) 83,810 ( 0.00%) } . . impl<'a, 'tcx> Iterator for ReversePostorder<'a, 'tcx> { . type Item = (BasicBlock, &'a BasicBlockData<'tcx>); . 355,662 ( 0.00%) fn next(&mut self) -> Option<(BasicBlock, &'a BasicBlockData<'tcx>)> { 1,422,648 ( 0.01%) if self.idx == 0 { . return None; . } 677,800 ( 0.00%) self.idx -= 1; . . self.blocks.get(self.idx).map(|&bb| (bb, &self.body[bb])) 711,324 ( 0.00%) } . . fn size_hint(&self) -> (usize, Option) { . (self.idx, Some(self.idx)) . } . } . . impl<'a, 'tcx> ExactSizeIterator for ReversePostorder<'a, 'tcx> {} . -- line 291 ---------------------------------------- -- line 295 ---------------------------------------- . /// This is clearer than writing `preorder` in cases where the order doesn't matter. . pub fn reachable<'a, 'tcx>( . body: &'a Body<'tcx>, . ) -> impl 'a + Iterator)> { . preorder(body) . } . . /// Returns a `BitSet` containing all basic blocks reachable from the `START_BLOCK`. 42,270 ( 0.00%) pub fn reachable_as_bitset<'tcx>(body: &Body<'tcx>) -> BitSet { . let mut iter = preorder(body); . (&mut iter).for_each(drop); 28,180 ( 0.00%) iter.visited 42,270 ( 0.00%) } 3,820,364 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/ena-0.14.0/src/unify/mod.rs -------------------------------------------------------------------------------- Ir -- line 154 ---------------------------------------- . /// Value of a unification key. We implement Tarjan's union-find . /// algorithm: when two keys are unified, one of them is converted . /// into a "redirect" pointing at the other. These redirects form a . /// DAG: the roots of the DAG (nodes that are not redirected) are each . /// associated with a value of type `V` and a rank. The rank is used . /// to keep the DAG relatively balanced, which helps keep the running . /// time of the algorithm under control. For more information, see . /// . 45,989 ( 0.00%) #[derive(PartialEq, Clone, Debug)] . pub struct VarValue { 77,573 ( 0.00%) parent: K, // if equal to self, this is a root 12,112 ( 0.00%) value: K::Value, // value assigned (only relevant to root) 71,561 ( 0.00%) rank: u32, // max depth (only relevant to root) . } . . /// Table of unification keys and their values. You must define a key type K . /// that implements the `UnifyKey` trait. Unification tables can be used in two-modes: . /// . /// - in-place (`UnificationTable>` or `InPlaceUnificationTable`): . /// - This is the standard mutable mode, where the array is modified . /// in place. . /// - To do backtracking, you can employ the `snapshot` and `rollback_to` . /// methods. . /// - persistent (`UnificationTable>` or `PersistentUnificationTable`): . /// - In this mode, we use a persistent vector to store the data, so that . /// cloning the table is an O(1) operation. . /// - This implies that ordinary operations are quite a bit slower though. . /// - Requires the `persistent` feature be selected in your Cargo.toml file. 155,005 ( 0.00%) #[derive(Clone, Debug, Default)] . pub struct UnificationTable { . /// Indicates the current value of each key. . values: S, . } . . pub type UnificationStorage = Vec>; . pub type UnificationTableStorage = UnificationTable, ()>>; . -- line 190 ---------------------------------------- -- line 215 ---------------------------------------- . } . . fn new(parent: K, value: K::Value, rank: u32) -> VarValue { . VarValue { . parent: parent, // this is a root . value: value, . rank: rank, . } 238,782 ( 0.00%) } . . fn redirect(&mut self, to: K) { 33,728 ( 0.00%) self.parent = to; . } . . fn root(&mut self, rank: u32, value: K::Value) { 32,107 ( 0.00%) self.rank = rank; 15,391 ( 0.00%) self.value = value; . } . . fn parent(&self, self_key: K) -> Option { 2,624,647 ( 0.01%) self.if_not_self(self.parent, self_key) . } . . fn if_not_self(&self, key: K, self_key: K) -> Option { . if key == self_key { . None . } else { . Some(key) . } -- line 243 ---------------------------------------- -- line 253 ---------------------------------------- . &'a mut self, . undo_log: L, . ) -> UnificationTable, L>> . where . L: UndoLogs>>, . { . UnificationTable { . values: InPlace { 6 ( 0.00%) values: self.values.values.with_log(undo_log), . }, . } . } . } . . // We can't use V:LatticeValue, much as I would like to, . // because frequently the pattern is that V=Option for some . // other type parameter U, and we have no way to say -- line 269 ---------------------------------------- -- line 311 ---------------------------------------- . pub fn len(&self) -> usize { . self.values.len() . } . } . . impl UnificationTable { . /// Starts a new snapshot. Each snapshot must be either . /// Creates a fresh key with the given value. 437,894 ( 0.00%) pub fn new_key(&mut self, value: S::Value) -> S::Key { . let len = self.values.len(); 641,884 ( 0.00%) let key: S::Key = UnifyKey::from_index(len as u32); . self.values.push(VarValue::new_var(key, value)); 261,706 ( 0.00%) debug!("{}: created new key: {:?}", S::tag(), key); . key 651,952 ( 0.00%) } . . /// Reserve memory for `num_new_keys` to be created. Does not . /// actually create the new keys; you must then invoke `new_key`. . pub fn reserve(&mut self, num_new_keys: usize) { . self.values.reserve(num_new_keys); . } . . /// Clears all unifications that have been performed, resetting to . /// the initial state. The values of each variable are given by . /// the closure. . pub fn reset_unifications(&mut self, mut value: impl FnMut(S::Key) -> S::Value) { . self.values.reset_unifications(|i| { 75 ( 0.00%) let key = UnifyKey::from_index(i as u32); . let value = value(key); . VarValue::new_var(key, value) . }); . } . . /// Obtains the current value for a particular key. . /// Not for end-users; they can use `probe_value`. . fn value(&self, key: S::Key) -> &VarValue { 1,643,572 ( 0.01%) &self.values[key.index() as usize] . } . . /// Find the root node for `vid`. This uses the standard . /// union-find algorithm with path compression: . /// . . /// . /// NB. This is a building-block operation and you would probably . /// prefer to call `probe` below. . /// . /// This is an always-inlined version of this function for the hot . /// callsites. `uninlined_get_root_key` is the never-inlined version. . #[inline(always)] . fn inlined_get_root_key(&mut self, vid: S::Key) -> S::Key { . let redirect = { 20,073,455 ( 0.11%) match self.value(vid).parent(vid) { . None => return vid, . Some(redirect) => redirect, . } . }; . 85,020 ( 0.00%) let root_key: S::Key = self.uninlined_get_root_key(redirect); 11,723 ( 0.00%) if root_key != redirect { . // Path compression 1,461 ( 0.00%) self.update_value(vid, |value| value.parent = root_key); . } . . root_key . } . . // This is a never-inlined version of this function for cold callsites. . // 'inlined_get_root_key` is the always-inlined version. . #[inline(never)] 3,190,231 ( 0.02%) fn uninlined_get_root_key(&mut self, vid: S::Key) -> S::Key { . self.inlined_get_root_key(vid) 2,997,813 ( 0.02%) } . 3,896 ( 0.00%) fn update_value(&mut self, key: S::Key, op: OP) . where . OP: FnOnce(&mut VarValue), . { 160,109 ( 0.00%) self.values.update(key.index() as usize, op); 115,740 ( 0.00%) debug!("Updated variable {:?} to {:?}", key, self.value(key)); 2,435 ( 0.00%) } . . /// Either redirects `node_a` to `node_b` or vice versa, depending . /// on the relative rank. The value associated with the new root . /// will be `new_value`. . /// . /// NB: This is the "union" operation of "union-find". It is . /// really more of a building block. If the values associated with . /// your key are non-trivial, you would probably prefer to call . /// `unify_var_var` below. . fn unify_roots(&mut self, key_a: S::Key, key_b: S::Key, new_value: S::Value) { 18,054 ( 0.00%) debug!("unify(key_a={:?}, key_b={:?})", key_a, key_b); . 31,372 ( 0.00%) let rank_a = self.value(key_a).rank; 85,490 ( 0.00%) let rank_b = self.value(key_b).rank; . if let Some((new_root, redirected)) = S::Key::order_roots( 52,089 ( 0.00%) key_a, . &self.value(key_a).value, 52,089 ( 0.00%) key_b, . &self.value(key_b).value, . ) { . // compute the new rank for the new root that they chose; . // this may not be the optimal choice. . let new_rank = if new_root == key_a { . debug_assert!(redirected == key_b); . if rank_a > rank_b { . rank_a -- line 416 ---------------------------------------- -- line 422 ---------------------------------------- . debug_assert!(redirected == key_a); . if rank_b > rank_a { . rank_b . } else { . rank_a + 1 . } . }; . self.redirect_root(new_rank, redirected, new_root, new_value); 36,108 ( 0.00%) } else if rank_a > rank_b { . // a has greater rank, so a should become b's parent, . // i.e., b should redirect to a. 3,867 ( 0.00%) self.redirect_root(rank_a, key_b, key_a, new_value); 16,794 ( 0.00%) } else if rank_a < rank_b { . // b has greater rank, so a should redirect to b. 9,310 ( 0.00%) self.redirect_root(rank_b, key_a, key_b, new_value); . } else { . // If equal, redirect one to the other and increment the . // other's rank. 59,130 ( 0.00%) self.redirect_root(rank_a + 1, key_a, key_b, new_value); . } . } . . /// Internal method to redirect `old_root_key` (which is currently . /// a root) to a child of `new_root_key` (which will remain a . /// root). The rank and value of `new_root_key` will be updated to . /// `new_rank` and `new_value` respectively. 228,685 ( 0.00%) fn redirect_root( . &mut self, . new_rank: u32, . old_root_key: S::Key, . new_root_key: S::Key, . new_value: S::Value, . ) { . self.update_value(old_root_key, |old_root_value| { . old_root_value.redirect(new_root_key); . }); 110 ( 0.00%) self.update_value(new_root_key, |new_root_value| { 691 ( 0.00%) new_root_value.root(new_rank, new_value); . }); 123,715 ( 0.00%) } . } . . /// //////////////////////////////////////////////////////////////////////// . /// Public API . . impl UnificationTable . where . S: UnificationStoreMut, . K: UnifyKey, . V: UnifyValue, . { . /// Unions two keys without the possibility of failure; only . /// applicable when unify values use `NoError` as their error . /// type. 178,168 ( 0.00%) pub fn union(&mut self, a_id: K1, b_id: K2) . where . K1: Into, . K2: Into, . V: UnifyValue, . { . self.unify_var_var(a_id, b_id).unwrap(); 157,736 ( 0.00%) } . . /// Unions a key and a value without the possibility of failure; . /// only applicable when unify values use `NoError` as their error . /// type. 673,422 ( 0.00%) pub fn union_value(&mut self, id: K1, value: V) . where . K1: Into, . V: UnifyValue, . { . self.unify_var_value(id, value).unwrap(); 526,861 ( 0.00%) } . . /// Given two keys, indicates whether they have been unioned together. . pub fn unioned(&mut self, a_id: K1, b_id: K2) -> bool . where . K1: Into, . K2: Into, . { . self.find(a_id) == self.find(b_id) -- line 502 ---------------------------------------- -- line 503 ---------------------------------------- . } . . /// Given a key, returns the (current) root key. . pub fn find(&mut self, id: K1) -> K . where . K1: Into, . { . let id = id.into(); 365,394 ( 0.00%) self.uninlined_get_root_key(id) . } . . /// Unions together two variables, merging their values. If . /// merging the values fails, the error is propagated and this . /// method has no effect. 207 ( 0.00%) pub fn unify_var_var(&mut self, a_id: K1, b_id: K2) -> Result<(), V::Error> . where . K1: Into, . K2: Into, . { . let a_id = a_id.into(); . let b_id = b_id.into(); . 68,996 ( 0.00%) let root_a = self.uninlined_get_root_key(a_id); 61,411 ( 0.00%) let root_b = self.uninlined_get_root_key(b_id); . 5,743 ( 0.00%) if root_a == root_b { . return Ok(()); . } . 110,801 ( 0.00%) let combined = V::unify_values(&self.value(root_a).value, &self.value(root_b).value)?; . . Ok(self.unify_roots(root_a, root_b, combined)) 230 ( 0.00%) } . . /// Sets the value of the key `a_id` to `b`, attempting to merge . /// with the previous value. 30,749 ( 0.00%) pub fn unify_var_value(&mut self, a_id: K1, b: V) -> Result<(), V::Error> . where . K1: Into, . { . let a_id = a_id.into(); 107,243 ( 0.00%) let root_a = self.uninlined_get_root_key(a_id); 239,964 ( 0.00%) let value = V::unify_values(&self.value(root_a).value, &b)?; 164,662 ( 0.00%) self.update_value(root_a, |node| node.value = value); . Ok(()) 27,866 ( 0.00%) } . . /// Returns the current value for the given key. If the key has . /// been union'd, this will give the value from the current root. 66,599 ( 0.00%) pub fn probe_value(&mut self, id: K1) -> V . where . K1: Into, . { . self.inlined_probe_value(id) 64,616 ( 0.00%) } . . // An always-inlined version of `probe_value`, for hot callsites. . #[inline(always)] . pub fn inlined_probe_value(&mut self, id: K1) -> V . where . K1: Into, . { . let id = id.into(); . let id = self.inlined_get_root_key(id); 38,002 ( 0.00%) self.value(id).value.clone() . } . } . . /////////////////////////////////////////////////////////////////////////// . . impl UnifyValue for () { . type Error = NoError; . . fn unify_values(_: &(), _: &()) -> Result<(), NoError> { . Ok(()) 6,708 ( 0.00%) } . } . . impl UnifyValue for Option { . type Error = V::Error; . . fn unify_values(a: &Option, b: &Option) -> Result { 18,080 ( 0.00%) match (a, b) { . (&None, &None) => Ok(None), . (&Some(ref v), &None) | (&None, &Some(ref v)) => Ok(Some(v.clone())), . (&Some(ref a), &Some(ref b)) => match V::unify_values(a, b) { . Ok(v) => Ok(Some(v)), . Err(err) => Err(err), . }, . } . } -- line 593 ---------------------------------------- 347,550 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/ena-0.14.0/src/snapshot_vec.rs -------------------------------------------------------------------------------- Ir -- line 42 ---------------------------------------- . . impl Rollback> for SnapshotVecStorage { . fn reverse(&mut self, undo: UndoLog) { . self.values.reverse(undo) . } . } . impl Rollback> for Vec { . fn reverse(&mut self, undo: UndoLog) { 625,588 ( 0.00%) match undo { . NewElem(i) => { . self.pop(); 235,445 ( 0.00%) assert!(Vec::len(self) == i); . } . . SetElem(i, v) => { 200,418 ( 0.00%) self[i] = v; . } . . Other(u) => { . D::reverse(self, u); . } . } . } . } -- line 65 ---------------------------------------- -- line 76 ---------------------------------------- . impl VecLike for Vec . where . D: SnapshotVecDelegate, . { . fn push(&mut self, item: D::Value) { . Vec::push(self, item) . } . fn len(&self) -> usize { 268,025 ( 0.00%) Vec::len(self) . } . fn reserve(&mut self, size: usize) { . Vec::reserve(self, size) . } . } . . impl VecLike for &'_ mut Vec . where . D: SnapshotVecDelegate, . { . fn push(&mut self, item: D::Value) { . Vec::push(self, item) . } . fn len(&self) -> usize { 1,456,978 ( 0.01%) Vec::len(self) . } . fn reserve(&mut self, size: usize) { . Vec::reserve(self, size) . } . } . . #[allow(type_alias_bounds)] . pub type SnapshotVecStorage = -- line 107 ---------------------------------------- -- line 191 ---------------------------------------- . } . . impl, D: SnapshotVecDelegate, U> SnapshotVec { . pub fn len(&self) -> usize { . self.values.len() . } . . pub fn get(&self, index: usize) -> &D::Value { 51,941,696 ( 0.29%) &self.values.as_ref()[index] . } . . /// Returns a mutable pointer into the vec; whatever changes you make here cannot be undone . /// automatically, so you should be sure call `record()` with some sort of suitable undo . /// action. . pub fn get_mut(&mut self, index: usize) -> &mut D::Value { 182,740 ( 0.00%) &mut self.values.as_mut()[index] . } . . /// Reserve space for new values, just like an ordinary vec. . pub fn reserve(&mut self, additional: usize) { . // This is not affected by snapshots or anything. . self.values.reserve(additional); . } . } -- line 214 ---------------------------------------- -- line 219 ---------------------------------------- . } . . pub fn record(&mut self, action: D::Undo) { . if self.in_snapshot() { . self.undo_log.push(Other(action)); . } . } . 3,161,275 ( 0.02%) pub fn push(&mut self, elem: D::Value) -> usize { . let len = self.values.len(); . self.values.push(elem); . 430,234 ( 0.00%) if self.in_snapshot() { . self.undo_log.push(NewElem(len)); . } . . len 2,920,268 ( 0.02%) } . . /// Updates the element at the given index. The old value will saved (and perhaps restored) if . /// a snapshot is active. . pub fn set(&mut self, index: usize, new_elem: D::Value) { . let old_elem = mem::replace(&mut self.values.as_mut()[index], new_elem); . if self.undo_log.in_snapshot() { . self.undo_log.push(SetElem(index, old_elem)); . } . } . . /// Updates all elements. Potentially more efficient -- but . /// otherwise equivalent to -- invoking `set` for each element. 21 ( 0.00%) pub fn set_all(&mut self, mut new_elems: impl FnMut(usize) -> D::Value) { 3 ( 0.00%) if !self.undo_log.in_snapshot() { . for (index, slot) in self.values.as_mut().iter_mut().enumerate() { 300 ( 0.00%) *slot = new_elems(index); . } . } else { . for i in 0..self.values.len() { . self.set(i, new_elems(i)); . } . } 24 ( 0.00%) } . 953,519 ( 0.01%) pub fn update(&mut self, index: usize, op: OP) . where . OP: FnOnce(&mut D::Value), . D::Value: Clone, . { 115,740 ( 0.00%) if self.undo_log.in_snapshot() { 416,937 ( 0.00%) let old_elem = self.values.as_mut()[index].clone(); 606 ( 0.00%) self.undo_log.push(SetElem(index, old_elem)); . } 338,756 ( 0.00%) op(&mut self.values.as_mut()[index]); 925,920 ( 0.01%) } . } . . impl SnapshotVec . where . D: SnapshotVecDelegate, . V: VecLike + Rollback>, . L: Snapshots>, . { -- line 279 ---------------------------------------- 348,560 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/pattern/deconstruct_pat.rs -------------------------------------------------------------------------------- Ir -- line 65 ---------------------------------------- . use std::cell::Cell; . use std::cmp::{self, max, min, Ordering}; . use std::fmt; . use std::iter::{once, IntoIterator}; . use std::ops::RangeInclusive; . . /// Recursively expand this pattern into its subpatterns. Only useful for or-patterns. . fn expand_or_pat<'p, 'tcx>(pat: &'p Pat<'tcx>) -> Vec<&'p Pat<'tcx>> { 2,236 ( 0.00%) fn expand<'p, 'tcx>(pat: &'p Pat<'tcx>, vec: &mut Vec<&'p Pat<'tcx>>) { 1,118 ( 0.00%) if let PatKind::Or { pats } = pat.kind.as_ref() { . for pat in pats { 1,455 ( 0.00%) expand(pat, vec); . } . } else { . vec.push(pat) . } 2,236 ( 0.00%) } . . let mut pats = Vec::new(); 148 ( 0.00%) expand(pat, &mut pats); . pats . } . . /// An inclusive interval, used for precise integer exhaustiveness checking. . /// `IntRange`s always store a contiguous range. This means that values are . /// encoded such that `0` encodes the minimum value for the integer, . /// regardless of the signedness. . /// For example, the pattern `-128..=127i8` is encoded as `0..=255`. . /// This makes comparisons and arithmetic on interval endpoints much more . /// straightforward. See `signed_bias` for details. . /// . /// `IntRange` is never used to encode an empty range or a "range" that wraps . /// around the (offset) space: i.e., `range.lo <= range.hi`. . #[derive(Clone, PartialEq, Eq)] . pub(super) struct IntRange { 11,312 ( 0.00%) range: RangeInclusive, . /// Keeps the bias used for encoding the range. It depends on the type of the range and . /// possibly the pointer size of the current architecture. The algorithm ensures we never . /// compare `IntRange`s with different types/architectures. 10,371 ( 0.00%) bias: u128, . } . . impl IntRange { . #[inline] . fn is_integral(ty: Ty<'_>) -> bool { 18,295 ( 0.00%) matches!(ty.kind(), ty::Char | ty::Int(_) | ty::Uint(_) | ty::Bool) . } . . fn is_singleton(&self) -> bool { 10,550 ( 0.00%) self.range.start() == self.range.end() . } . . fn boundaries(&self) -> (u128, u128) { 109,286 ( 0.00%) (*self.range.start(), *self.range.end()) . } . . #[inline] . fn integral_size_and_signed_bias(tcx: TyCtxt<'_>, ty: Ty<'_>) -> Option<(Size, u128)> { 1,857 ( 0.00%) match *ty.kind() { . ty::Bool => Some((Size::from_bytes(1), 0)), . ty::Char => Some((Size::from_bytes(4), 0)), 60 ( 0.00%) ty::Int(ity) => { . let size = Integer::from_int_ty(&tcx, ity).size(); 130 ( 0.00%) Some((size, 1u128 << (size.bits() as u128 - 1))) . } 3,654 ( 0.00%) ty::Uint(uty) => Some((Integer::from_uint_ty(&tcx, uty).size(), 0)), . _ => None, . } . } . . #[inline] . fn from_const<'tcx>( . tcx: TyCtxt<'tcx>, . param_env: ty::ParamEnv<'tcx>, . value: &Const<'tcx>, . ) -> Option { 619 ( 0.00%) if let Some((target_size, bias)) = Self::integral_size_and_signed_bias(tcx, value.ty) { . let ty = value.ty; . let val = (|| { 4,952 ( 0.00%) if let ty::ConstKind::Value(ConstValue::Scalar(scalar)) = value.val { . // For this specific pattern we can skip a lot of effort and go . // straight to the result, after doing a bit of checking. (We . // could remove this branch and just fall through, which . // is more general but much slower.) . if let Ok(bits) = scalar.to_bits_or_ptr_internal(target_size) { . return Some(bits); . } . } . // This is a more general form of the previous case. . value.try_eval_bits(tcx, param_env, ty) . })()?; 8,047 ( 0.00%) let val = val ^ bias; . Some(IntRange { range: val..=val, bias }) . } else { . None . } . } . . #[inline] 11,963 ( 0.00%) fn from_range<'tcx>( . tcx: TyCtxt<'tcx>, . lo: u128, . hi: u128, . ty: Ty<'tcx>, . end: &RangeEnd, . ) -> Option { 1,709 ( 0.00%) if Self::is_integral(ty) { . // Perform a shift if the underlying types are signed, . // which makes the interval arithmetic simpler. . let bias = IntRange::signed_bias(tcx, ty); 17,090 ( 0.00%) let (lo, hi) = (lo ^ bias, hi ^ bias); . let offset = (*end == RangeEnd::Excluded) as u128; 17,090 ( 0.00%) if lo > hi || (lo == hi && *end == RangeEnd::Excluded) { . // This should have been caught earlier by E0030. . bug!("malformed range pattern: {}..={}", lo, (hi - offset)); . } 17,090 ( 0.00%) Some(IntRange { range: lo..=(hi - offset), bias }) . } else { . None . } 10,254 ( 0.00%) } . . // The return value of `signed_bias` should be XORed with an endpoint to encode/decode it. . fn signed_bias(tcx: TyCtxt<'_>, ty: Ty<'_>) -> u128 { 3,418 ( 0.00%) match *ty.kind() { 348 ( 0.00%) ty::Int(ity) => { . let bits = Integer::from_int_ty(&tcx, ity).size().bits() as u128; 754 ( 0.00%) 1u128 << (bits - 1) . } . _ => 0, . } . } . . fn is_subrange(&self, other: &Self) -> bool { . other.range.start() <= self.range.start() && self.range.end() <= other.range.end() . } . . fn intersection(&self, other: &Self) -> Option { . let (lo, hi) = self.boundaries(); . let (other_lo, other_hi) = other.boundaries(); 334,652 ( 0.00%) if lo <= other_hi && other_lo <= hi { 1,237 ( 0.00%) Some(IntRange { range: max(lo, other_lo)..=min(hi, other_hi), bias: self.bias }) . } else { . None . } . } . . fn suspicious_intersection(&self, other: &Self) -> bool { . // `false` in the following cases: . // 1 ---- // 1 ---------- // 1 ---- // 1 ---- -- line 214 ---------------------------------------- -- line 242 ---------------------------------------- . } else { . PatKind::Range(PatRange { lo: lo_const, hi: hi_const, end: RangeEnd::Included }) . }; . . Pat { ty, span: DUMMY_SP, kind: Box::new(kind) } . } . . /// Lint on likely incorrect range patterns (#63987) 2,476 ( 0.00%) pub(super) fn lint_overlapping_range_endpoints<'a, 'p: 'a, 'tcx: 'a>( . &self, . pcx: PatCtxt<'_, 'p, 'tcx>, . pats: impl Iterator>, . column_count: usize, . hir_id: HirId, . ) { 619 ( 0.00%) if self.is_singleton() { . return; . } . . if column_count != 1 { . // FIXME: for now, only check for overlapping ranges on simple range . // patterns. Otherwise with the current logic the following is detected . // as overlapping: . // ``` -- line 265 ---------------------------------------- -- line 295 ---------------------------------------- . ); . } . err.span_label(pcx.span, "... with this range"); . err.note("you likely meant to write mutually exclusive ranges"); . err.emit(); . }, . ); . } 3,095 ( 0.00%) } . . /// See `Constructor::is_covered_by` . fn is_covered_by(&self, other: &Self) -> bool { 106,812 ( 0.00%) if self.intersection(other).is_some() { . // Constructor splitting should ensure that all intersections we encounter are actually . // inclusions. 2,052 ( 0.00%) assert!(self.is_subrange(other)); . true . } else { . false . } . } . } . . /// Note: this is often not what we want: e.g. `false` is converted into the range `0..=0` and -- line 318 ---------------------------------------- -- line 325 ---------------------------------------- . write!(f, "{}", lo)?; . write!(f, "{}", RangeEnd::Included)?; . write!(f, "{}", hi) . } . } . . /// Represents a border between 2 integers. Because the intervals spanning borders must be able to . /// cover every integer, we need to be able to represent 2^128 + 1 such borders. 44,111 ( 0.00%) #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] . enum IntBorder { . JustBefore(u128), . AfterMax, . } . . /// A range of integers that is partitioned into disjoint subranges. This does constructor . /// splitting for integer ranges as explained at the top of the file. . /// -- line 341 ---------------------------------------- -- line 359 ---------------------------------------- . range: IntRange, . /// The borders of ranges we have seen. They are all contained within `range`. This is kept . /// sorted. . borders: Vec, . } . . impl SplitIntRange { . fn new(range: IntRange) -> Self { 13,672 ( 0.00%) SplitIntRange { range, borders: Vec::new() } . } . . /// Internal use . fn to_borders(r: IntRange) -> [IntBorder; 2] { . use IntBorder::*; . let (lo, hi) = r.boundaries(); . let lo = JustBefore(lo); . let hi = match hi.checked_add(1) { -- line 375 ---------------------------------------- -- line 400 ---------------------------------------- . let mut prev_border = self_range[0]; . self.borders . .iter() . .copied() . // End with the end of the range. . .chain(once(self_range[1])) . // List pairs of adjacent borders. . .map(move |border| { 6,365 ( 0.00%) let ret = (prev_border, border); 3,819 ( 0.00%) prev_border = border; . ret . }) . // Skip duplicates. . .filter(|(prev_border, border)| prev_border != border) . // Finally, convert to ranges. . .map(move |(prev_border, border)| { 17,868 ( 0.00%) let range = match (prev_border, border) { 17,868 ( 0.00%) (JustBefore(n), JustBefore(m)) if n < m => n..=(m - 1), . (JustBefore(n), AfterMax) => n..=u128::MAX, . _ => unreachable!(), // Ruled out by the sorting and filtering we did . }; 7,225 ( 0.00%) IntRange { range, bias: self.range.bias } . }) . } . } . . #[derive(Copy, Clone, Debug, PartialEq, Eq)] . enum SliceKind { . /// Patterns of length `n` (`[x, y]`). . FixedLen(usize), -- line 429 ---------------------------------------- -- line 434 ---------------------------------------- . /// and everything in between is a wildcard `_`. . VarLen(usize, usize), . } . . impl SliceKind { . fn arity(self) -> usize { . match self { . FixedLen(length) => length, 44 ( 0.00%) VarLen(prefix, suffix) => prefix + suffix, . } . } . . /// Whether this pattern includes patterns of length `other_len`. . fn covers_length(self, other_len: usize) -> bool { . match self { . FixedLen(len) => len == other_len, . VarLen(prefix, suffix) => prefix + suffix <= other_len, -- line 450 ---------------------------------------- -- line 458 ---------------------------------------- . /// `None` if the matched value is a slice, `Some(n)` if it is an array of size `n`. . array_len: Option, . /// The kind of pattern it is: fixed-length `[x, y]` or variable length `[x, .., y]`. . kind: SliceKind, . } . . impl Slice { . fn new(array_len: Option, kind: SliceKind) -> Self { 88 ( 0.00%) let kind = match (array_len, kind) { . // If the middle `..` is empty, we effectively have a fixed-length pattern. 176 ( 0.00%) (Some(len), VarLen(prefix, suffix)) if prefix + suffix >= len => FixedLen(len), . _ => kind, . }; . Slice { array_len, kind } . } . . fn arity(self) -> usize { . self.kind.arity() . } -- line 476 ---------------------------------------- -- line 550 ---------------------------------------- . arity: usize, . /// The smallest slice bigger than any slice seen. `max_slice.arity()` is the length `L` . /// described above. . max_slice: SliceKind, . } . . impl SplitVarLenSlice { . fn new(prefix: usize, suffix: usize, array_len: Option) -> Self { 220 ( 0.00%) SplitVarLenSlice { array_len, arity: prefix + suffix, max_slice: VarLen(prefix, suffix) } . } . . /// Pass a set of slices relative to which to split this one. . fn split(&mut self, slices: impl Iterator) { . let (max_prefix_len, max_suffix_len) = match &mut self.max_slice { . VarLen(prefix, suffix) => (prefix, suffix), . FixedLen(_) => return, // No need to split . }; -- line 566 ---------------------------------------- -- line 576 ---------------------------------------- . VarLen(prefix, suffix) => { . *max_prefix_len = cmp::max(*max_prefix_len, prefix); . *max_suffix_len = cmp::max(*max_suffix_len, suffix); . } . } . } . // We want `L = max(L, max_fixed_len + 1)`, modulo the fact that we keep prefix and . // suffix separate. 154 ( 0.00%) if max_fixed_len + 1 >= *max_prefix_len + *max_suffix_len { . // The subtraction can't overflow thanks to the above check. . // The new `max_prefix_len` is larger than its previous value. 88 ( 0.00%) *max_prefix_len = max_fixed_len + 1 - *max_suffix_len; . } . . // We cap the arity of `max_slice` at the array size. 44 ( 0.00%) match self.array_len { 44 ( 0.00%) Some(len) if self.max_slice.arity() >= len => self.max_slice = FixedLen(len), . _ => {} . } . } . . /// Iterate over the partition of this slice. . fn iter<'a>(&'a self) -> impl Iterator + Captures<'a> { . let smaller_lengths = match self.array_len { . // The only admissible fixed-length slice is one of the array size. Whether `max_slice` -- line 600 ---------------------------------------- -- line 604 ---------------------------------------- . // We cover all arities in the range `(self.arity..infinity)`. We split that range into . // two: lengths smaller than `max_slice.arity()` are treated independently as . // fixed-lengths slices, and lengths above are captured by `max_slice`. . None => self.arity..self.max_slice.arity(), . }; . smaller_lengths . .map(FixedLen) . .chain(once(self.max_slice)) 44 ( 0.00%) .map(move |kind| Slice::new(self.array_len, kind)) . } . } . . /// A value can be decomposed into a constructor applied to some fields. This struct represents . /// the constructor. See also `Fields`. . /// . /// `pat_constructor` retrieves the constructor corresponding to a pattern. . /// `specialize_constructor` returns the list of fields corresponding to a pattern, given a . /// constructor. `Constructor::apply` reconstructs the pattern from a pair of `Constructor` and . /// `Fields`. 55,671 ( 0.00%) #[derive(Clone, Debug, PartialEq)] . pub(super) enum Constructor<'tcx> { . /// The constructor for patterns that have a single constructor, like tuples, struct patterns . /// and fixed-length arrays. . Single, . /// Enum variants. 110,851 ( 0.00%) Variant(VariantIdx), . /// Ranges of integer literal values (`2`, `2..=5` or `2..5`). . IntRange(IntRange), . /// Ranges of floating-point literal values (`2.0..=5.2`). . FloatRange(&'tcx ty::Const<'tcx>, &'tcx ty::Const<'tcx>, RangeEnd), . /// String literals. Strings are not quite the same as `&[u8]` so we treat them separately. . Str(&'tcx ty::Const<'tcx>), . /// Array and slice patterns. . Slice(Slice), -- line 637 ---------------------------------------- -- line 649 ---------------------------------------- . /// Wildcard pattern. . Wildcard, . /// Or-pattern. . Or, . } . . impl<'tcx> Constructor<'tcx> { . pub(super) fn is_wildcard(&self) -> bool { 14,379 ( 0.00%) matches!(self, Wildcard) . } . . pub(super) fn is_non_exhaustive(&self) -> bool { . matches!(self, NonExhaustive) . } . . fn as_int_range(&self) -> Option<&IntRange> { 32,763 ( 0.00%) match self { . IntRange(range) => Some(range), . _ => None, . } . } . . fn as_slice(&self) -> Option { 22 ( 0.00%) match self { . Slice(slice) => Some(*slice), . _ => None, . } . } . . /// Checks if the `Constructor` is a variant and `TyCtxt::eval_stability` returns . /// `EvalResult::Deny { .. }`. . /// . /// This means that the variant has a stdlib unstable feature marking it. 1,094 ( 0.00%) pub(super) fn is_unstable_variant(&self, pcx: PatCtxt<'_, '_, 'tcx>) -> bool { 1,094 ( 0.00%) if let Constructor::Variant(idx) = self { 1,641 ( 0.00%) if let ty::Adt(adt, _) = pcx.ty.kind() { 2,735 ( 0.00%) let variant_def_id = adt.variants[*idx].def_id; . // Filter variants that depend on a disabled unstable feature. 1,094 ( 0.00%) return matches!( 4,376 ( 0.00%) pcx.cx.tcx.eval_stability(variant_def_id, None, DUMMY_SP, None), . EvalResult::Deny { .. } . ); . } . } . false 2,188 ( 0.00%) } . . /// Checks if the `Constructor` is a `Constructor::Variant` with a `#[doc(hidden)]` . /// attribute. . pub(super) fn is_doc_hidden_variant(&self, pcx: PatCtxt<'_, '_, 'tcx>) -> bool { 1,641 ( 0.00%) if let Constructor::Variant(idx) = self { 1,094 ( 0.00%) if let ty::Adt(adt, _) = pcx.ty.kind() { 2,735 ( 0.00%) let variant_def_id = adt.variants[*idx].def_id; 1,094 ( 0.00%) return pcx.cx.tcx.is_doc_hidden(variant_def_id); . } . } . false . } . . fn variant_index_for_adt(&self, adt: &'tcx ty::AdtDef) -> VariantIdx { 19,516 ( 0.00%) match *self { 9,648 ( 0.00%) Variant(idx) => idx, . Single => { 220 ( 0.00%) assert!(!adt.is_enum()); . VariantIdx::new(0) . } . _ => bug!("bad constructor {:?} for adt {:?}", self, adt), . } . } . . /// The number of fields for this constructor. This must be kept in sync with . /// `Fields::wildcards`. 14 ( 0.00%) pub(super) fn arity(&self, pcx: PatCtxt<'_, '_, 'tcx>) -> usize { 12 ( 0.00%) match self { 9 ( 0.00%) Single | Variant(_) => match pcx.ty.kind() { 1 ( 0.00%) ty::Tuple(fs) => fs.len(), . ty::Ref(..) => 1, . ty::Adt(adt, ..) => { . if adt.is_box() { . // The only legal patterns of type `Box` (outside `std`) are `_` and box . // patterns. If we're here we can assume this is a box pattern. . 1 . } else { . let variant = &adt.variants[self.variant_index_for_adt(adt)]; -- line 732 ---------------------------------------- -- line 740 ---------------------------------------- . | FloatRange(..) . | IntRange(..) . | NonExhaustive . | Opaque . | Missing { .. } . | Wildcard => 0, . Or => bug!("The `Or` constructor doesn't have a fixed arity"), . } 16 ( 0.00%) } . . /// Some constructors (namely `Wildcard`, `IntRange` and `Slice`) actually stand for a set of actual . /// constructors (like variants, integers or fixed-sized slices). When specializing for these . /// constructors, we want to be specialising for the actual underlying constructors. . /// Naively, we would simply return the list of constructors they correspond to. We instead are . /// more clever: if there are constructors that we know will behave the same wrt the current . /// matrix, we keep them grouped. For example, all slices of a sufficiently large length . /// will either be all useful or all non-useful with a given matrix. . /// . /// See the branches for details on how the splitting is done. . /// . /// This function may discard some irrelevant constructors if this preserves behavior and . /// diagnostics. Eg. for the `_` case, we ignore the constructors already present in the . /// matrix, unless all of them are. 569,550 ( 0.00%) pub(super) fn split<'a>( . &self, . pcx: PatCtxt<'_, '_, 'tcx>, . ctors: impl Iterator> + Clone, . ) -> SmallVec<[Self; 1]> . where . 'tcx: 'a, . { 345,413 ( 0.00%) match self { . Wildcard => { 106,544 ( 0.00%) let mut split_wildcard = SplitWildcard::new(pcx); 119,862 ( 0.00%) split_wildcard.split(pcx, ctors); 253,042 ( 0.00%) split_wildcard.into_ctors(pcx) . } . // Fast-track if the range is trivial. In particular, we don't do the overlapping . // ranges check. 2,328 ( 0.00%) IntRange(ctor_range) if !ctor_range.is_singleton() => { . let mut split_range = SplitIntRange::new(ctor_range.clone()); . let int_ranges = ctors.filter_map(|ctor| ctor.as_int_range()); . split_range.split(int_ranges.cloned()); . split_range.iter().map(IntRange).collect() . } 44 ( 0.00%) &Slice(Slice { kind: VarLen(self_prefix, self_suffix), array_len }) => { . let mut split_self = SplitVarLenSlice::new(self_prefix, self_suffix, array_len); . let slices = ctors.filter_map(|c| c.as_slice()).map(|s| s.kind); . split_self.split(slices); . split_self.iter().map(Slice).collect() . } . // Any other constructor can be used unchanged. 670,496 ( 0.00%) _ => smallvec![self.clone()], . } 512,595 ( 0.00%) } . . /// Returns whether `self` is covered by `other`, i.e. whether `self` is a subset of `other`. . /// For the simple cases, this is simply checking for equality. For the "grouped" constructors, . /// this checks for inclusion. . // We inline because this has a single call site in `Matrix::specialize_constructor`. . #[inline] . pub(super) fn is_covered_by<'p>(&self, pcx: PatCtxt<'_, 'p, 'tcx>, other: &Self) -> bool { . // This must be kept in sync with `is_covered_by_any`. 15,674,821 ( 0.09%) match (self, other) { . // Wildcards cover anything . (_, Wildcard) => true, . // The missing ctors are not covered by anything in the matrix except wildcards. . (Missing { .. } | Wildcard, _) => false, . . (Single, Single) => true, 1,269,110 ( 0.01%) (Variant(self_id), Variant(other_id)) => self_id == other_id, . . (IntRange(self_range), IntRange(other_range)) => self_range.is_covered_by(other_range), . ( . FloatRange(self_from, self_to, self_end), . FloatRange(other_from, other_to, other_end), . ) => { . match ( . compare_const_vals(pcx.cx.tcx, self_to, other_to, pcx.cx.param_env, pcx.ty), -- line 818 ---------------------------------------- -- line 848 ---------------------------------------- . other . ), . } . } . . /// Faster version of `is_covered_by` when applied to many constructors. `used_ctors` is . /// assumed to be built from `matrix.head_ctors()` with wildcards filtered out, and `self` is . /// assumed to have been split from a wildcard. 87,405 ( 0.00%) fn is_covered_by_any<'p>( . &self, . pcx: PatCtxt<'_, 'p, 'tcx>, . used_ctors: &[Constructor<'tcx>], . ) -> bool { 17,481 ( 0.00%) if used_ctors.is_empty() { . return false; . } . . // This must be kept in sync with `is_covered_by`. 35,022 ( 0.00%) match self { . // If `self` is `Single`, `used_ctors` cannot contain anything else than `Single`s. . Single => !used_ctors.is_empty(), 853,532 ( 0.00%) Variant(vid) => used_ctors.iter().any(|c| matches!(c, Variant(i) if i == vid)), . IntRange(range) => used_ctors . .iter() . .filter_map(|c| c.as_int_range()) . .any(|other| range.is_covered_by(other)), . Slice(slice) => used_ctors . .iter() . .filter_map(|c| c.as_slice()) . .any(|other| slice.is_covered_by(other)), . // This constructor is never covered by anything else . NonExhaustive => false, . Str(..) | FloatRange(..) | Opaque | Missing { .. } | Wildcard | Or => { . span_bug!(pcx.span, "found unexpected ctor in all_ctors: {:?}", self) . } . } 87,405 ( 0.00%) } . } . . /// A wildcard constructor that we split relative to the constructors in the matrix, as explained . /// at the top of the file. . /// . /// A constructor that is not present in the matrix rows will only be covered by the rows that have . /// wildcards. Thus we can group all of those constructors together; we call them "missing . /// constructors". Splitting a wildcard would therefore list all present constructors individually -- line 892 ---------------------------------------- -- line 903 ---------------------------------------- . pub(super) struct SplitWildcard<'tcx> { . /// Constructors seen in the matrix. . matrix_ctors: Vec>, . /// All the constructors for this type . all_ctors: SmallVec<[Constructor<'tcx>; 1]>, . } . . impl<'tcx> SplitWildcard<'tcx> { 106,648 ( 0.00%) pub(super) fn new<'p>(pcx: PatCtxt<'_, 'p, 'tcx>) -> Self { . debug!("SplitWildcard::new({:?})", pcx.ty); 13,331 ( 0.00%) let cx = pcx.cx; 13,331 ( 0.00%) let make_range = |start, end| { . IntRange( . // `unwrap()` is ok because we know the type is an integer. 13,894 ( 0.00%) IntRange::from_range(cx.tcx, start, end, pcx.ty, &RangeEnd::Included).unwrap(), . ) . }; . // This determines the set of all possible constructors for the type `pcx.ty`. For numbers, . // arrays and slices we use ranges and variable-length slices when appropriate. . // . // If the `exhaustive_patterns` feature is enabled, we make sure to omit constructors that . // are statically impossible. E.g., for `Option`, we do not include `Some(_)` in the . // returned list of constructors. . // Invariant: this is empty if and only if the type is uninhabited (as determined by . // `cx.is_uninhabited()`). 71,978 ( 0.00%) let all_ctors = match pcx.ty.kind() { . ty::Bool => smallvec![make_range(0, 1)], 110 ( 0.00%) ty::Array(sub_ty, len) if len.try_eval_usize(cx.tcx, cx.param_env).is_some() => { 88 ( 0.00%) let len = len.eval_usize(cx.tcx, cx.param_env) as usize; 154 ( 0.00%) if len != 0 && cx.is_uninhabited(sub_ty) { . smallvec![] . } else { . smallvec![Slice(Slice::new(Some(len), VarLen(0, 0)))] . } . } . // Treat arrays of a constant but unknown length like slices. . ty::Array(sub_ty, _) | ty::Slice(sub_ty) => { . let kind = if cx.is_uninhabited(sub_ty) { FixedLen(0) } else { VarLen(0, 0) }; . smallvec![Slice(Slice::new(None, kind))] . } 20,490 ( 0.00%) ty::Adt(def, substs) if def.is_enum() => { . // If the enum is declared as `#[non_exhaustive]`, we treat it as if it had an . // additional "unknown" constructor. . // There is no point in enumerating all possible variants, because the user can't . // actually match against them all themselves. So we always return only the fictitious . // constructor. . // E.g., in an example like: . // . // ``` -- line 951 ---------------------------------------- -- line 954 ---------------------------------------- . // io::ErrorKind::NotFound => {}, . // } . // ``` . // . // we don't want to show every possible IO error, but instead have only `_` as the . // witness. . let is_declared_nonexhaustive = cx.is_foreign_non_exhaustive_enum(pcx.ty); . 18,808 ( 0.00%) let is_exhaustive_pat_feature = cx.tcx.features().exhaustive_patterns; . . // If `exhaustive_patterns` is disabled and our scrutinee is an empty enum, we treat it . // as though it had an "unknown" constructor to avoid exposing its emptiness. The . // exception is if the pattern is at the top level, because we want empty matches to be . // considered exhaustive. . let is_secretly_empty = 18,808 ( 0.00%) def.variants.is_empty() && !is_exhaustive_pat_feature && !pcx.is_top_level; . . let mut ctors: SmallVec<[_; 1]> = def . .variants . .iter_enumerated() 4,702 ( 0.00%) .filter(|(_, v)| { . // If `exhaustive_patterns` is enabled, we exclude variants known to be . // uninhabited. 82,008 ( 0.00%) let is_uninhabited = is_exhaustive_pat_feature . && v.uninhabited_from(cx.tcx, substs, def.adt_kind(), cx.param_env) . .contains(cx.tcx, cx.module); . !is_uninhabited . }) . .map(|(idx, _)| Variant(idx)) . .collect(); . 9,404 ( 0.00%) if is_secretly_empty || is_declared_nonexhaustive { . ctors.push(NonExhaustive); . } . ctors . } . ty::Char => { . smallvec![ . // The valid Unicode Scalar Value ranges. . make_range('\u{0000}' as u128, '\u{D7FF}' as u128), . make_range('\u{E000}' as u128, '\u{10FFFF}' as u128), . ] . } . ty::Int(_) | ty::Uint(_) . if pcx.ty.is_ptr_sized_integral() 2,004 ( 0.00%) && !cx.tcx.features().precise_pointer_size_matching => . { . // `usize`/`isize` are not allowed to be matched exhaustively unless the . // `precise_pointer_size_matching` feature is enabled. So we treat those types like . // `#[non_exhaustive]` enums by returning a special unmatcheable constructor. . smallvec![NonExhaustive] . } . &ty::Int(ity) => { . let bits = Integer::from_int_ty(&cx.tcx, ity).size().bits() as u128; 754 ( 0.00%) let min = 1u128 << (bits - 1); 232 ( 0.00%) let max = min - 1; . smallvec![make_range(min, max)] . } . &ty::Uint(uty) => { . let size = Integer::from_uint_ty(&cx.tcx, uty).size(); . let max = size.truncate(u128::MAX); . smallvec![make_range(0, max)] . } . // If `exhaustive_patterns` is disabled and our scrutinee is the never type, we cannot -- line 1017 ---------------------------------------- -- line 1022 ---------------------------------------- . } . ty::Never => smallvec![], . _ if cx.is_uninhabited(pcx.ty) => smallvec![], . ty::Adt(..) | ty::Tuple(..) | ty::Ref(..) => smallvec![Single], . // This type is one for which we cannot list constructors, like `str` or `f64`. . _ => smallvec![NonExhaustive], . }; . 146,641 ( 0.00%) SplitWildcard { matrix_ctors: Vec::new(), all_ctors } 119,979 ( 0.00%) } . . /// Pass a set of constructors relative to which to split this one. Don't call twice, it won't . /// do what you want. 93,317 ( 0.00%) pub(super) fn split<'a>( . &mut self, . pcx: PatCtxt<'_, '_, 'tcx>, . ctors: impl Iterator> + Clone, . ) where . 'tcx: 'a, . { . // Since `all_ctors` never contains wildcards, this won't recurse further. 133,310 ( 0.00%) self.all_ctors = 323,685 ( 0.00%) self.all_ctors.iter().flat_map(|ctor| ctor.split(pcx, ctors.clone())).collect(); 93,317 ( 0.00%) self.matrix_ctors = ctors.filter(|c| !c.is_wildcard()).cloned().collect(); 66,655 ( 0.00%) } . . /// Whether there are any value constructors for this type that are not present in the matrix. . fn any_missing(&self, pcx: PatCtxt<'_, '_, 'tcx>) -> bool { . self.iter_missing(pcx).next().is_some() . } . . /// Iterate over the constructors for this type that are not present in the matrix. . pub(super) fn iter_missing<'a, 'p>( . &'a self, . pcx: PatCtxt<'a, 'p, 'tcx>, . ) -> impl Iterator> + Captures<'p> { 189,517 ( 0.00%) self.all_ctors.iter().filter(move |ctor| !ctor.is_covered_by_any(pcx, &self.matrix_ctors)) . } . . /// Return the set of constructors resulting from splitting the wildcard. As explained at the . /// top of the file, if any constructors are missing we can ignore the present ones. . fn into_ctors(self, pcx: PatCtxt<'_, '_, 'tcx>) -> SmallVec<[Constructor<'tcx>; 1]> { 26,636 ( 0.00%) if self.any_missing(pcx) { . // Some constructors are missing, thus we can specialize with the special `Missing` . // constructor, which stands for those constructors that are not seen in the matrix, . // and matches the same rows as any of them (namely the wildcard rows). See the top of . // the file for details. . // However, when all constructors are missing we can also specialize with the full . // `Wildcard` constructor. The difference will depend on what we want in diagnostics. . . // If some constructors are missing, we typically want to report those constructors, -- line 1072 ---------------------------------------- -- line 1084 ---------------------------------------- . // let (_, _, false) = x; . // ``` . // we don't want to show all 16 possible witnesses `(, , . // true)` - we are satisfied with `(_, _, true)`. So if all constructors are missing we . // prefer to report just a wildcard `_`. . // . // The exception is: if we are at the top-level, for example in an empty match, we . // sometimes prefer reporting the list of constructors instead of just `_`. 23,620 ( 0.00%) let report_when_all_missing = pcx.is_top_level && !IntRange::is_integral(pcx.ty); 35,351 ( 0.00%) let ctor = if !self.matrix_ctors.is_empty() || report_when_all_missing { 8,408 ( 0.00%) if pcx.is_non_exhaustive { . Missing { . nonexhaustive_enum_missing_real_variants: self . .iter_missing(pcx) . .any(|c| !(c.is_non_exhaustive() || c.is_unstable_variant(pcx))), . } . } else { . Missing { nonexhaustive_enum_missing_real_variants: false } . } . } else { . Wildcard . }; 35,430 ( 0.00%) return smallvec![ctor]; . } . . // All the constructors are present in the matrix, so we just go through them all. 15,080 ( 0.00%) self.all_ctors . } . } . . /// A value can be decomposed into a constructor applied to some fields. This struct represents . /// those fields, generalized to allow patterns in each field. See also `Constructor`. . /// . /// This is constructed for a constructor using [`Fields::wildcards()`]. The idea is that . /// [`Fields::wildcards()`] constructs a list of fields where all entries are wildcards, and then -- line 1118 ---------------------------------------- -- line 1142 ---------------------------------------- . Fields { fields: &[] } . } . . fn singleton(cx: &MatchCheckCtxt<'p, 'tcx>, field: DeconstructedPat<'p, 'tcx>) -> Self { . let field: &_ = cx.pattern_arena.alloc(field); . Fields { fields: std::slice::from_ref(field) } . } . 46,104 ( 0.00%) pub(super) fn from_iter( . cx: &MatchCheckCtxt<'p, 'tcx>, . fields: impl IntoIterator>, . ) -> Self { 2 ( 0.00%) let fields: &[_] = cx.pattern_arena.alloc_from_iter(fields); . Fields { fields } 51,830 ( 0.00%) } . . fn wildcards_from_tys( . cx: &MatchCheckCtxt<'p, 'tcx>, . tys: impl IntoIterator>, . ) -> Self { . Fields::from_iter(cx, tys.into_iter().map(DeconstructedPat::wildcard)) . } . -- line 1164 ---------------------------------------- -- line 1165 ---------------------------------------- . // In the cases of either a `#[non_exhaustive]` field list or a non-public field, we hide . // uninhabited fields in order not to reveal the uninhabitedness of the whole variant. . // This lists the fields we keep along with their types. . fn list_variant_nonhidden_fields<'a>( . cx: &'a MatchCheckCtxt<'p, 'tcx>, . ty: Ty<'tcx>, . variant: &'a VariantDef, . ) -> impl Iterator)> + Captures<'a> + Captures<'p> { 18,862 ( 0.00%) let (adt, substs) = match ty.kind() { 13,928 ( 0.00%) ty::Adt(adt, substs) => (adt, substs), . _ => bug!(), . }; . // Whether we must not match the fields of this variant exhaustively. 14,365 ( 0.00%) let is_non_exhaustive = variant.is_field_list_non_exhaustive() && !adt.did.is_local(); . . variant.fields.iter().enumerate().filter_map(move |(i, field)| { 48,524 ( 0.00%) let ty = field.ty(cx.tcx, substs); . // `field.ty()` doesn't normalize after substituting. 13,864 ( 0.00%) let ty = cx.tcx.normalize_erasing_regions(cx.param_env, ty); 28,244 ( 0.00%) let is_visible = adt.is_enum() || field.vis.is_accessible_from(cx.module, cx.tcx); . let is_uninhabited = cx.is_uninhabited(ty); . . if is_uninhabited && (!is_visible || is_non_exhaustive) { . None . } else { . Some((Field::new(i), ty)) . } . }) . } . . /// Creates a new list of wildcard fields for a given constructor. The result must have a . /// length of `constructor.arity()`. 114,105 ( 0.00%) pub(super) fn wildcards( . cx: &MatchCheckCtxt<'p, 'tcx>, . ty: Ty<'tcx>, . constructor: &Constructor<'tcx>, . ) -> Self { 159,747 ( 0.00%) let ret = match constructor { 15,930 ( 0.00%) Single | Variant(_) => match ty.kind() { 249 ( 0.00%) ty::Tuple(fs) => Fields::wildcards_from_tys(cx, fs.iter().map(|ty| ty.expect_ty())), 258 ( 0.00%) ty::Ref(_, rty, _) => Fields::wildcards_from_tys(cx, once(*rty)), . ty::Adt(adt, substs) => { 9,868 ( 0.00%) if adt.is_box() { . // The only legal patterns of type `Box` (outside `std`) are `_` and box . // patterns. If we're here we can assume this is a box pattern. . Fields::wildcards_from_tys(cx, once(substs.type_at(0))) . } else { . let variant = &adt.variants[constructor.variant_index_for_adt(adt)]; . let tys = Fields::list_variant_nonhidden_fields(cx, ty, variant) . .map(|(_, ty)| ty); 4,934 ( 0.00%) Fields::wildcards_from_tys(cx, tys) . } . } . _ => bug!("Unexpected type for `Single` constructor: {:?}", ty), . }, . Slice(slice) => match *ty.kind() { . ty::Slice(ty) | ty::Array(ty, _) => { . let arity = slice.arity(); . Fields::wildcards_from_tys(cx, (0..arity).map(|_| ty)) -- line 1223 ---------------------------------------- -- line 1232 ---------------------------------------- . | Missing { .. } . | Wildcard => Fields::empty(), . Or => { . bug!("called `Fields::wildcards` on an `Or` ctor") . } . }; . debug!("Fields::wildcards({:?}, {:?}) = {:#?}", constructor, ty, ret); . ret 114,105 ( 0.00%) } . . /// Returns the list of patterns. . pub(super) fn iter_patterns<'a>( . &'a self, . ) -> impl Iterator> + Captures<'a> { 591,875 ( 0.00%) self.fields.iter() . } . } . . /// Values and patterns can be represented as a constructor applied to some fields. This represents . /// a pattern in this form. . /// This also keeps track of whether the pattern has been found reachable during analysis. For this . /// reason we should be careful not to clone patterns for which we care about that. Use . /// `clone_and_forget_reachability` if you're sure. -- line 1254 ---------------------------------------- -- line 1266 ---------------------------------------- . } . . pub(super) fn new( . ctor: Constructor<'tcx>, . fields: Fields<'p, 'tcx>, . ty: Ty<'tcx>, . span: Span, . ) -> Self { 240,724 ( 0.00%) DeconstructedPat { ctor, fields, ty, span, reachable: Cell::new(false) } . } . . /// Construct a pattern that matches everything that starts with this constructor. . /// For example, if `ctor` is a `Constructor::Variant` for `Option::Some`, we get the pattern . /// `Some(_)`. . pub(super) fn wild_from_ctor(pcx: PatCtxt<'_, 'p, 'tcx>, ctor: Constructor<'tcx>) -> Self { 1,094 ( 0.00%) let fields = Fields::wildcards(pcx.cx, pcx.ty, &ctor); 4,376 ( 0.00%) DeconstructedPat::new(ctor, fields, pcx.ty, DUMMY_SP) . } . . /// Clone this value. This method emphasizes that cloning loses reachability information and . /// should be done carefully. 2,192 ( 0.00%) pub(super) fn clone_and_forget_reachability(&self) -> Self { 1,096 ( 0.00%) DeconstructedPat::new(self.ctor.clone(), self.fields, self.ty, self.span) 2,192 ( 0.00%) } . 136,440 ( 0.00%) pub(crate) fn from_pat(cx: &MatchCheckCtxt<'p, 'tcx>, pat: &Pat<'tcx>) -> Self { 24,040 ( 0.00%) let mkpat = |pat| DeconstructedPat::from_pat(cx, pat); . let ctor; . let fields; 78,892 ( 0.00%) match pat.kind.as_ref() { . PatKind::AscribeUserType { subpattern, .. } => return mkpat(subpattern), . PatKind::Binding { subpattern: Some(subpat), .. } => return mkpat(subpat), . PatKind::Binding { subpattern: None, .. } | PatKind::Wild => { . ctor = Wildcard; . fields = Fields::empty(); . } 2,654 ( 0.00%) PatKind::Deref { subpattern } => { . ctor = Single; 1,327 ( 0.00%) fields = Fields::singleton(cx, mkpat(subpattern)); . } 5,726 ( 0.00%) PatKind::Leaf { subpatterns } | PatKind::Variant { subpatterns, .. } => { 25,362 ( 0.00%) match pat.ty.kind() { . ty::Tuple(fs) => { . ctor = Single; 1,229 ( 0.00%) let mut wilds: SmallVec<[_; 2]> = fs . .iter() 1,263 ( 0.00%) .map(|ty| ty.expect_ty()) . .map(DeconstructedPat::wildcard) . .collect(); . for pat in subpatterns { 18,945 ( 0.00%) wilds[pat.field.index()] = mkpat(&pat.pattern); . } 13,519 ( 0.00%) fields = Fields::from_iter(cx, wilds); . } 13,491 ( 0.00%) ty::Adt(adt, substs) if adt.is_box() => { . // The only legal patterns of type `Box` (outside `std`) are `_` and box . // patterns. If we're here we can assume this is a box pattern. . // FIXME(Nadrieril): A `Box` can in theory be matched either with `Box(_, . // _)` or a box pattern. As a hack to avoid an ICE with the former, we . // ignore other fields than the first one. This will trigger an error later . // anyway. . // See https://github.com/rust-lang/rust/issues/82772 , . // explanation: https://github.com/rust-lang/rust/pull/82789#issuecomment-796921977 -- line 1328 ---------------------------------------- -- line 1335 ---------------------------------------- . mkpat(&pat.pattern) . } else { . DeconstructedPat::wildcard(substs.type_at(0)) . }; . ctor = Single; . fields = Fields::singleton(cx, pat); . } . ty::Adt(adt, _) => { 13,711 ( 0.00%) ctor = match pat.kind.as_ref() { . PatKind::Leaf { .. } => Single, 8,774 ( 0.00%) PatKind::Variant { variant_index, .. } => Variant(*variant_index), . _ => bug!(), . }; . let variant = &adt.variants[ctor.variant_index_for_adt(adt)]; . // For each field in the variant, we store the relevant index into `self.fields` if any. . let mut field_id_to_id: Vec> = 13,491 ( 0.00%) (0..variant.fields.len()).map(|_| None).collect(); 4,497 ( 0.00%) let tys = Fields::list_variant_nonhidden_fields(cx, pat.ty, variant) . .enumerate() . .map(|(i, (field, ty))| { 13,624 ( 0.00%) field_id_to_id[field.index()] = Some(i); . ty . }); . let mut wilds: SmallVec<[_; 2]> = . tys.map(DeconstructedPat::wildcard).collect(); . for pat in subpatterns { 16,940 ( 0.00%) if let Some(i) = field_id_to_id[pat.field.index()] { 50,820 ( 0.00%) wilds[i] = mkpat(&pat.pattern); . } . } 31,479 ( 0.00%) fields = Fields::from_iter(cx, wilds); . } . _ => bug!("pattern has unexpected type: pat: {:?}, ty: {:?}", pat, pat.ty), . } . } . PatKind::Constant { value } => { 619 ( 0.00%) if let Some(int_range) = IntRange::from_const(cx.tcx, cx.param_env, value) { . ctor = IntRange(int_range); . fields = Fields::empty(); . } else { . match pat.ty.kind() { . ty::Float(_) => { . ctor = FloatRange(value, value, RangeEnd::Included); . fields = Fields::empty(); . } -- line 1379 ---------------------------------------- -- line 1427 ---------------------------------------- . FixedLen(prefix.len() + suffix.len()) . }; . ctor = Slice(Slice::new(array_len, kind)); . fields = Fields::from_iter(cx, prefix.iter().chain(suffix).map(mkpat)); . } . PatKind::Or { .. } => { . ctor = Or; . let pats = expand_or_pat(pat); 740 ( 0.00%) fields = Fields::from_iter(cx, pats.into_iter().map(mkpat)); . } . } 54,576 ( 0.00%) DeconstructedPat::new(ctor, fields, pat.ty, pat.span) 122,796 ( 0.00%) } . . pub(crate) fn to_pat(&self, cx: &MatchCheckCtxt<'p, 'tcx>) -> Pat<'tcx> { . let is_wildcard = |pat: &Pat<'_>| { . matches!(*pat.kind, PatKind::Binding { subpattern: None, .. } | PatKind::Wild) . }; . let mut subpatterns = self.iter_fields().map(|p| p.to_pat(cx)); . let pat = match &self.ctor { . Single | Variant(_) => match self.ty.kind() { -- line 1447 ---------------------------------------- -- line 1520 ---------------------------------------- . bug!("can't convert to pattern: {:?}", self) . } . }; . . Pat { ty: self.ty, span: DUMMY_SP, kind: Box::new(pat) } . } . . pub(super) fn is_or_pat(&self) -> bool { 637,390 ( 0.00%) matches!(self.ctor, Or) . } . . pub(super) fn ctor(&self) -> &Constructor<'tcx> { . &self.ctor . } . pub(super) fn ty(&self) -> Ty<'tcx> { 23,478 ( 0.00%) self.ty . } . pub(super) fn span(&self) -> Span { 42,683 ( 0.00%) self.span . } . . pub(super) fn iter_fields<'a>( . &'a self, . ) -> impl Iterator> + Captures<'a> { . self.fields.iter_patterns() . } . . /// Specialize this pattern with a constructor. . /// `other_ctor` can be different from `self.ctor`, but must be covered by it. 4,779,432 ( 0.03%) pub(super) fn specialize<'a>( . &'a self, . cx: &MatchCheckCtxt<'p, 'tcx>, . other_ctor: &Constructor<'tcx>, . ) -> SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]> { 2,987,145 ( 0.02%) match (&self.ctor, other_ctor) { . (Wildcard, _) => { . // We return a wildcard for each field of `other_ctor`. 89,096 ( 0.00%) Fields::wildcards(cx, self.ty, other_ctor).iter_patterns().collect() . } . (Slice(self_slice), Slice(other_slice)) . if self_slice.arity() != other_slice.arity() => . { . // The only tricky case: two slices of different arity. Since `self_slice` covers . // `other_slice`, `self_slice` must be `VarLen`, i.e. of the form . // `[prefix, .., suffix]`. Moreover `other_slice` is guaranteed to have a larger . // arity. So we fill the middle part with enough wildcards to reach the length of -- line 1565 ---------------------------------------- -- line 1578 ---------------------------------------- . let extra_wildcards = other_slice.arity() - self_slice.arity(); . let extra_wildcards = (0..extra_wildcards).map(|_| wildcard); . prefix.iter().chain(extra_wildcards).chain(suffix).collect() . } . } . } . _ => self.fields.iter_patterns().collect(), . } 5,376,861 ( 0.03%) } . . /// We keep track for each pattern if it was ever reachable during the analysis. This is used . /// with `unreachable_spans` to report unreachable subpatterns arising from or patterns. . pub(super) fn set_reachable(&self) { . self.reachable.set(true) . } . pub(super) fn is_reachable(&self) -> bool { . self.reachable.get() . } . . /// Report the spans of subpatterns that were not reachable, if any. . pub(super) fn unreachable_spans(&self) -> Vec { . let mut spans = Vec::new(); 21,543 ( 0.00%) self.collect_unreachable_spans(&mut spans); . spans . } . 54,648 ( 0.00%) fn collect_unreachable_spans(&self, spans: &mut Vec) { . // We don't look at subpatterns if we already reported the whole pattern as unreachable. 13,662 ( 0.00%) if !self.is_reachable() { . spans.push(self.span); . } else { . for p in self.iter_fields() { 19,443 ( 0.00%) p.collect_unreachable_spans(spans); . } . } 54,648 ( 0.00%) } . } . . /// This is mostly copied from the `Pat` impl. This is best effort and not good enough for a . /// `Display` impl. . impl<'p, 'tcx> fmt::Debug for DeconstructedPat<'p, 'tcx> { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . // Printing lists is a chore. . let mut first = true; -- line 1621 ---------------------------------------- 8,109,557 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs -------------------------------------------------------------------------------- Ir -- line 57 ---------------------------------------- . /// # Examples . /// . /// Basic usage: . /// . /// ``` . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 2,300 ( 0.00%) pub fn from_str_radix(src: &str, radix: u32) -> Result { 1,150 ( 0.00%) from_str_radix(src, radix) 3,450 ( 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 { 639,900 ( 0.00%) intrinsics::ctpop(self as $ActualT) as u32 . } . . /// Returns the number of zeros in the binary representation of `self`. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 96 ---------------------------------------- -- line 118 ---------------------------------------- . /// assert_eq!(n.leading_zeros(), 2); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn leading_zeros(self) -> u32 { 1,294,453 ( 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,478,631 ( 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 { 35,324,554 ( 0.20%) 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 { 64 ( 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`. 5,697,445 ( 0.03%) unsafe { intrinsics::unchecked_add(self, rhs) } . } . . /// Checked addition with a signed integer. Computes `self + rhs`, . /// returning `None` if overflow occurred. . /// . /// # Examples . /// . /// Basic usage: -- line 472 ---------------------------------------- -- line 525 ---------------------------------------- . )] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] . #[inline(always)] . pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self { . // SAFETY: the caller must uphold the safety contract for . // `unchecked_sub`. 210,239 ( 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 7,224 ( 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 { 1,096,292 ( 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 { 52,991 ( 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 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 { 17,168,221 ( 0.10%) 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 { 6,887,867 ( 0.04%) 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 { 25,643,252 ( 0.15%) 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 { 57 ( 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)] 108 ( 0.00%) pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) { 2,853,144 ( 0.02%) let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) 216 ( 0.00%) } . . /// Calculates `self + rhs + carry` without the ability to overflow. . /// . /// Performs "ternary addition" which takes in an extra bit to add, and may return an . /// additional bit of overflow. This allows for chaining together multiple additions . /// to create "big integers" which represent larger values. . /// . #[doc = concat!("This can be thought of as a ", stringify!($BITS), "-bit \"full adder\", in the electronics sense.")] -- line 1510 ---------------------------------------- -- line 1587 ---------------------------------------- . #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")] . #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] 12 ( 0.00%) pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) { 993,999 ( 0.01%) let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) 24 ( 0.00%) } . . /// Calculates `self - rhs - borrow` without the ability to overflow. . /// . /// Performs "ternary subtraction" which takes in an extra bit to subtract, and may return . /// an additional bit of overflow. This allows for chaining together multiple subtractions . /// to create "big integers" which represent larger values. . /// . /// # Examples -- line 1606 ---------------------------------------- -- line 1673 ---------------------------------------- . /// assert_eq!(5u32.overflowing_mul(2), (10, false)); . /// 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)] 6 ( 0.00%) pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) { 5,240,992 ( 0.03%) let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) 3 ( 0.00%) } . . /// 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 . /// `false`. . /// -- line 1692 ---------------------------------------- -- line 1838 ---------------------------------------- . #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) { 21 ( 0.00%) (self.wrapping_shl(rhs), (rhs > ($BITS - 1))) . } . . /// Shifts self right by `rhs` bits. . /// . /// Returns a tuple of the shifted version of self along with a boolean . /// indicating whether the shift value was larger than or equal to the . /// number of bits. If the shift value is too large, then value is . /// masked (N-1) where N is the number of bits, and this value is then -- line 1854 ---------------------------------------- -- line 2132 ---------------------------------------- . #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")] . #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")] . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")] . #[inline(always)] . pub const fn is_power_of_two(self) -> bool { 174 ( 0.00%) self.count_ones() == 1 . } . . // Returns one less than next power of two. . // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8) . // . // 8u8.one_less_than_next_power_of_two() == 7 . // 6u8.one_less_than_next_power_of_two() == 7 . // . // This method cannot overflow, as in the `next_power_of_two` . // overflow cases it instead ends up returning the maximum value . // of the type, and can return 0 for 0. . #[inline] . #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")] . const fn one_less_than_next_power_of_two(self) -> Self { 69,756 ( 0.00%) if self <= 1 { return 0; } . 69,847 ( 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. 209,185 ( 0.00%) let z = unsafe { intrinsics::ctlz_nonzero(p) }; 70,003 ( 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 { 69,840 ( 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 ---------------------------------------- 386,943 ( 0.00%) -------------------------------------------------------------------------------- -- 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)] 71,358,153 ( 0.40%) 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 { 39 ( 0.00%) copy_nonoverlapping(x, tmp.as_mut_ptr(), 1); 39 ( 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 { 2,675 ( 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 { 2,523,056 ( 0.01%) copy_nonoverlapping(src, tmp.as_mut_ptr(), 1); 9,707,283 ( 0.06%) 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 { 124,847,518 ( 0.71%) 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. 24,733 ( 0.00%) return wrapping_sub( 58,324 ( 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 { 4,144,147 ( 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 ---------------------------------------- 12,610,935 ( 0.07%) -------------------------------------------------------------------------------- -- 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. 3,058,816 ( 0.02%) 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), 159,583 ( 0.00%) GoDown(handle) => match handle.force() { . Leaf(leaf) => return GoDown(leaf), . Internal(internal) => internal.descend(), . }, . } . } 1,510,361 ( 0.01%) } . . /// 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()); 3,253,534 ( 0.02%) for (offset, k) in unsafe { keys.get_unchecked(start_index..) }.iter().enumerate() { 12,187,216 ( 0.07%) 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 ---------------------------------------- 5,998,251 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs -------------------------------------------------------------------------------- Ir -- line 10 ---------------------------------------- . pub fn move_path_children_matching<'tcx, F>( . move_data: &MoveData<'tcx>, . path: MovePathIndex, . mut cond: F, . ) -> Option . where . F: FnMut(mir::PlaceElem<'tcx>) -> bool, . { 10,129 ( 0.00%) let mut next_child = move_data.move_paths[path].first_child; 26,918 ( 0.00%) while let Some(child_index) = next_child { . let move_path_children = &move_data.move_paths[child_index]; 20,624 ( 0.00%) if let Some(&elem) = move_path_children.place.projection.last() { 34,433 ( 0.00%) if cond(elem) { . return Some(child_index); . } . } . next_child = move_path_children.next_sibling; . } . . None . } -- line 30 ---------------------------------------- -- line 48 ---------------------------------------- . // . // FIXME: we have to do something for moving slice patterns. . fn place_contents_drop_state_cannot_differ<'tcx>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . place: mir::Place<'tcx>, . ) -> bool { . let ty = place.ty(body, tcx).ty; 3,972,420 ( 0.02%) match ty.kind() { . ty::Array(..) => { . debug!( . "place_contents_drop_state_cannot_differ place: {:?} ty: {:?} => false", . place, ty . ); . false . } . ty::Slice(..) | ty::Ref(..) | ty::RawPtr(..) => { . debug!( . "place_contents_drop_state_cannot_differ place: {:?} ty: {:?} refd => true", . place, ty . ); . true . } 3,667,203 ( 0.02%) ty::Adt(def, _) if (def.has_dtor(tcx) && !def.is_box()) || def.is_union() => { . debug!( . "place_contents_drop_state_cannot_differ place: {:?} ty: {:?} Drop => true", . place, ty . ); . true . } . _ => false, . } -- line 79 ---------------------------------------- -- line 83 ---------------------------------------- . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . lookup_result: LookupResult, . each_child: F, . ) where . F: FnMut(MovePathIndex), . { 95,040 ( 0.00%) match lookup_result { . LookupResult::Parent(..) => { . // access to untracked value - do not touch children . } . LookupResult::Exact(e) => on_all_children_bits(tcx, body, move_data, e, each_child), . } . } . . pub fn on_all_children_bits<'tcx, F>( -- line 99 ---------------------------------------- -- line 100 ---------------------------------------- . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . move_path_index: MovePathIndex, . mut each_child: F, . ) where . F: FnMut(MovePathIndex), . { 5,830,488 ( 0.03%) fn is_terminal_path<'tcx>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . path: MovePathIndex, . ) -> bool { 1,457,622 ( 0.01%) place_contents_drop_state_cannot_differ(tcx, body, move_data.move_paths[path].place) 5,830,488 ( 0.03%) } . 7,131,107 ( 0.04%) fn on_all_children_bits<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . move_path_index: MovePathIndex, . each_child: &mut F, . ) where . F: FnMut(MovePathIndex), . { 166,841 ( 0.00%) each_child(move_path_index); . 5,117,130 ( 0.03%) if is_terminal_path(tcx, body, move_data, move_path_index) { . return; . } . 526,774 ( 0.00%) let mut next_child_index = move_data.move_paths[move_path_index].first_child; 1,534,110 ( 0.01%) while let Some(child_index) = next_child_index { 678,264 ( 0.00%) on_all_children_bits(tcx, body, move_data, child_index, each_child); 113,044 ( 0.00%) next_child_index = move_data.move_paths[child_index].next_sibling; . } 5,672,852 ( 0.03%) } 3,597,751 ( 0.02%) on_all_children_bits(tcx, body, move_data, move_path_index, &mut each_child); . } . . pub fn on_all_drop_children_bits<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . ctxt: &MoveDataParamEnv<'tcx>, . path: MovePathIndex, . mut each_child: F, . ) where . F: FnMut(MovePathIndex), . { 228,583 ( 0.00%) on_all_children_bits(tcx, body, &ctxt.move_data, path, |child| { 163,372 ( 0.00%) let place = &ctxt.move_data.move_paths[path].place; 40,843 ( 0.00%) let ty = place.ty(body, tcx).ty; . debug!("on_all_drop_children_bits({:?}, {:?} : {:?})", path, place, ty); . 31,764 ( 0.00%) let erased_ty = tcx.erase_regions(ty); 247,054 ( 0.00%) if erased_ty.needs_drop(tcx, ctxt.param_env) { 40,385 ( 0.00%) each_child(child); . } else { . debug!("on_all_drop_children_bits - skipping") . } . }) . } . 59,550 ( 0.00%) pub fn drop_flag_effects_for_function_entry<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . ctxt: &MoveDataParamEnv<'tcx>, . mut callback: F, . ) where . F: FnMut(MovePathIndex, DropFlagState), . { . let move_data = &ctxt.move_data; 5,330 ( 0.00%) for arg in body.args_iter() { 14,124 ( 0.00%) let place = mir::Place::from(arg); 21,186 ( 0.00%) let lookup_result = move_data.rev_lookup.find(place.as_ref()); . on_lookup_result_bits(tcx, body, move_data, lookup_result, |mpi| { 7,180 ( 0.00%) callback(mpi, DropFlagState::Present) . }); . } 42,640 ( 0.00%) } . 7,265,304 ( 0.04%) pub fn drop_flag_effects_for_location<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . ctxt: &MoveDataParamEnv<'tcx>, . loc: Location, . mut callback: F, . ) where . F: FnMut(MovePathIndex, DropFlagState), . { . let move_data = &ctxt.move_data; . debug!("drop_flag_effects_for_location({:?})", loc); . . // first, move out of the RHS 306,300 ( 0.00%) for mi in &move_data.loc_map[loc] { 1,442,342 ( 0.01%) let path = mi.move_path_index(move_data); . debug!("moving out of path {:?}", move_data.move_paths[path]); . 447,772 ( 0.00%) on_all_children_bits(tcx, body, move_data, path, |mpi| callback(mpi, DropFlagState::Absent)) . } . . debug!("drop_flag_effects: assignment for location({:?})", loc); . 166,865 ( 0.00%) for_location_inits(tcx, body, move_data, loc, |mpi| callback(mpi, DropFlagState::Present)); 5,641,248 ( 0.03%) } . . pub fn for_location_inits<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . loc: Location, . mut callback: F, . ) where . F: FnMut(MovePathIndex), . { 306,300 ( 0.00%) for ii in &move_data.init_loc_map[loc] { 844,204 ( 0.00%) let init = move_data.inits[*ii]; 514,858 ( 0.00%) match init.kind { . InitKind::Deep => { . let path = init.path; . . on_all_children_bits(tcx, body, move_data, path, &mut callback) . } . InitKind::Shallow => { . let mpi = init.path; . callback(mpi); -- line 226 ---------------------------------------- -- line 230 ---------------------------------------- . } . } . . /// Calls `handle_inactive_variant` for each descendant move path of `enum_place` that contains a . /// `Downcast` to a variant besides the `active_variant`. . /// . /// NOTE: If there are no move paths corresponding to an inactive variant, . /// `handle_inactive_variant` will not be called for that variant. 219,396 ( 0.00%) pub(crate) fn on_all_inactive_variants<'tcx>( . tcx: TyCtxt<'tcx>, . body: &mir::Body<'tcx>, . move_data: &MoveData<'tcx>, . enum_place: mir::Place<'tcx>, . active_variant: VariantIdx, . mut handle_inactive_variant: impl FnMut(MovePathIndex), . ) { 91,415 ( 0.00%) let enum_mpi = match move_data.rev_lookup.find(enum_place.as_ref()) { . LookupResult::Exact(mpi) => mpi, . LookupResult::Parent(_) => return, . }; . . let enum_path = &move_data.move_paths[enum_mpi]; 69,216 ( 0.00%) for (variant_mpi, variant_path) in enum_path.children(&move_data.move_paths) { . // Because of the way we build the `MoveData` tree, each child should have exactly one more . // projection than `enum_place`. This additional projection must be a downcast since the . // base is an enum. 9,935 ( 0.00%) let (downcast, base_proj) = variant_path.place.projection.split_last().unwrap(); 39,740 ( 0.00%) assert_eq!(enum_place.projection.len(), base_proj.len()); . 29,805 ( 0.00%) let variant_idx = match *downcast { . mir::ProjectionElem::Downcast(_, idx) => idx, . _ => unreachable!(), . }; . 9,935 ( 0.00%) if variant_idx != active_variant { . on_all_children_bits(tcx, body, move_data, variant_mpi, |mpi| { 9,947 ( 0.00%) handle_inactive_variant(mpi) . }); . } . } 146,264 ( 0.00%) } 5,561,922 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs -------------------------------------------------------------------------------- Ir -- line 417 ---------------------------------------- . /// # #![allow(unused_mut)] . /// let mut vec: Vec = Vec::new(); . /// ``` . #[inline] . #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] . pub const fn new() -> Self { 10,370,796 ( 0.06%) Vec { buf: RawVec::NEW, len: 0 } 636 ( 0.00%) } . . /// Constructs a new, empty `Vec` with the specified capacity. . /// . /// The vector will be able to hold exactly `capacity` elements without . /// reallocating. If `capacity` is 0, the vector will not allocate. . /// . /// It is important to note that although the returned vector has the . /// *capacity* specified, the vector will have a zero *length*. For an -- line 434 ---------------------------------------- -- line 601 ---------------------------------------- . /// vec.push(11); . /// assert_eq!(vec.len(), 11); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[unstable(feature = "allocator_api", issue = "32838")] . pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { 3,650,054 ( 0.02%) Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 } . } . . /// Creates a `Vec` directly from the raw components of another vector. . /// . /// # Safety . /// . /// This is highly unsafe, due to the number of invariants that aren't . /// checked: -- line 617 ---------------------------------------- -- line 677 ---------------------------------------- . /// // Put everything back together into a Vec . /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone()); . /// assert_eq!(rebuilt, [4, 5, 6]); . /// } . /// ``` . #[inline] . #[unstable(feature = "allocator_api", issue = "32838")] . pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self { 242,431 ( 0.00%) unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } } . } . . /// Decomposes a `Vec` into its raw components. . /// . /// Returns the raw pointer to the underlying data, the length of . /// the vector (in elements), and the allocated capacity of the . /// data (in elements). These are the same arguments in the same . /// order as the arguments to [`from_raw_parts`]. -- line 693 ---------------------------------------- -- line 778 ---------------------------------------- . /// . /// ``` . /// let vec: Vec = Vec::with_capacity(10); . /// assert_eq!(vec.capacity(), 10); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn capacity(&self) -> usize { 801,335 ( 0.00%) self.buf.capacity() . } . . /// Reserves capacity for at least `additional` more elements to be inserted . /// in the given `Vec`. The collection may reserve more space to avoid . /// frequent reallocations. After calling `reserve`, capacity will be . /// greater than or equal to `self.len() + additional`. Does nothing if . /// capacity is already sufficient. . /// -- line 794 ---------------------------------------- -- line 801 ---------------------------------------- . /// ``` . /// let mut vec = vec![1]; . /// vec.reserve(10); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn reserve(&mut self, additional: usize) { 1,595,386 ( 0.01%) self.buf.reserve(self.len, additional); . } . . /// Reserves the minimum capacity for exactly `additional` more elements to . /// be inserted in the given `Vec`. After calling `reserve_exact`, . /// capacity will be greater than or equal to `self.len() + additional`. . /// Does nothing if the capacity is already sufficient. . /// . /// Note that the allocator may give the collection more space than it -- line 817 ---------------------------------------- -- line 829 ---------------------------------------- . /// ``` . /// let mut vec = vec![1]; . /// vec.reserve_exact(10); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn reserve_exact(&mut self, additional: usize) { 25,374 ( 0.00%) self.buf.reserve_exact(self.len, additional); . } . . /// Tries to reserve capacity for at least `additional` more elements to be inserted . /// in the given `Vec`. The collection may reserve more space to avoid . /// frequent reallocations. After calling `try_reserve`, capacity will be . /// greater than or equal to `self.len() + additional`. Does nothing if . /// capacity is already sufficient. . /// -- line 845 ---------------------------------------- -- line 930 ---------------------------------------- . /// assert!(vec.capacity() >= 3); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn shrink_to_fit(&mut self) { . // The capacity is never less than the length, and there's nothing to do when . // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit` . // by only calling it with a greater capacity. 69,936 ( 0.00%) if self.capacity() > self.len { 33,934 ( 0.00%) self.buf.shrink_to_fit(self.len); . } . } . . /// Shrinks the capacity of the vector with a lower bound. . /// . /// The capacity will remain at least as large as both the length . /// and the supplied value. . /// -- line 947 ---------------------------------------- -- line 990 ---------------------------------------- . /// let slice = vec.into_boxed_slice(); . /// assert_eq!(slice.into_vec().capacity(), 3); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn into_boxed_slice(mut self) -> Box<[T], A> { . unsafe { . self.shrink_to_fit(); 20,198 ( 0.00%) let me = ManuallyDrop::new(self); . let buf = ptr::read(&me.buf); . let len = me.len(); . buf.into_box(len).assume_init() . } . } . . /// Shortens the vector, keeping the first `len` elements and dropping . /// the rest. -- line 1006 ---------------------------------------- -- line 1040 ---------------------------------------- . /// let mut vec = vec![1, 2, 3]; . /// vec.truncate(0); . /// assert_eq!(vec, []); . /// ``` . /// . /// [`clear`]: Vec::clear . /// [`drain`]: Vec::drain . #[stable(feature = "rust1", since = "1.0.0")] 341,518 ( 0.00%) pub fn truncate(&mut self, len: usize) { . // This is safe because: . // . // * the slice passed to `drop_in_place` is valid; the `len > self.len` . // case avoids creating an invalid slice, and . // * the `len` of the vector is shrunk before calling `drop_in_place`, . // such that no value will be dropped twice in case `drop_in_place` . // were to panic once (if it panics twice, the program aborts). . unsafe { . // Note: It's intentional that this is `>` and not `>=`. . // Changing it to `>=` has negative performance . // implications in some cases. See #78884 for more. 381,979 ( 0.00%) if len > self.len { . return; . } . let remaining_len = self.len - len; . let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len); 858,031 ( 0.00%) self.len = len; 18,304 ( 0.00%) ptr::drop_in_place(s); . } 409,802 ( 0.00%) } . . /// Extracts a slice containing the entire vector. . /// . /// Equivalent to `&s[..]`. . /// . /// # Examples . /// . /// ``` -- line 1076 ---------------------------------------- -- line 1126 ---------------------------------------- . /// ``` . /// . /// [`as_mut_ptr`]: Vec::as_mut_ptr . #[stable(feature = "vec_as_ptr", since = "1.37.0")] . #[inline] . pub fn as_ptr(&self) -> *const T { . // We shadow the slice method of the same name to avoid going through . // `deref`, which creates an intermediate reference. 40,470,967 ( 0.23%) let ptr = self.buf.ptr(); . unsafe { . assume(!ptr.is_null()); . } . ptr . } . . /// Returns an unsafe mutable pointer to the vector's buffer. . /// -- line 1142 ---------------------------------------- -- line 1162 ---------------------------------------- . /// } . /// assert_eq!(&*x, &[0, 1, 2, 3]); . /// ``` . #[stable(feature = "vec_as_ptr", since = "1.37.0")] . #[inline] . pub fn as_mut_ptr(&mut self) -> *mut T { . // We shadow the slice method of the same name to avoid going through . // `deref_mut`, which creates an intermediate reference. 22,309,799 ( 0.13%) let ptr = self.buf.ptr(); . unsafe { . assume(!ptr.is_null()); . } . ptr . } . . /// Returns a reference to the underlying allocator. . #[unstable(feature = "allocator_api", issue = "32838")] -- line 1178 ---------------------------------------- -- line 1259 ---------------------------------------- . /// . /// Normally, here, one would use [`clear`] instead to correctly drop . /// the contents and thus not leak memory. . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub unsafe fn set_len(&mut self, new_len: usize) { . debug_assert!(new_len <= self.capacity()); . 2,560,093 ( 0.01%) self.len = new_len; 89,406 ( 0.00%) } . . /// Removes an element from the vector and returns it. . /// . /// The removed element is replaced by the last element of the vector. . /// . /// This does not preserve ordering, but is *O*(1). . /// If you need to preserve the element order, use [`remove`] instead. . /// -- line 1276 ---------------------------------------- -- line 1305 ---------------------------------------- . assert_failed(index, len); . } . unsafe { . // We replace self[index] with the last element. Note that if the . // bounds check above succeeds there must be a last element (which . // can be self[index] itself). . let value = ptr::read(self.as_ptr().add(index)); . let base_ptr = self.as_mut_ptr(); 25 ( 0.00%) ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1); . self.set_len(len - 1); . value . } . } . . /// Inserts an element at position `index` within the vector, shifting all . /// elements after it to the right. . /// -- line 1321 ---------------------------------------- -- line 1329 ---------------------------------------- . /// let mut vec = vec![1, 2, 3]; . /// vec.insert(1, 4); . /// assert_eq!(vec, [1, 4, 2, 3]); . /// vec.insert(4, 5); . /// assert_eq!(vec, [1, 4, 2, 3, 5]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 17,129 ( 0.00%) pub fn insert(&mut self, index: usize, element: T) { . #[cold] . #[inline(never)] . fn assert_failed(index: usize, len: usize) -> ! { . panic!("insertion index (is {}) should be <= len (is {})", index, len); . } . 2,820 ( 0.00%) let len = self.len(); 10,012 ( 0.00%) if index > len { . assert_failed(index, len); . } . . // space for the new element 15,604 ( 0.00%) if len == self.buf.capacity() { . self.reserve(1); . } . . unsafe { . // infallible . // The spot to put the new value . { . let p = self.as_mut_ptr().add(index); . // Shift everything over to make space. (Duplicating the . // `index`th element into two consecutive places.) 22,287 ( 0.00%) ptr::copy(p, p.offset(1), len - index); . // Write it in, overwriting the first copy of the `index`th . // element. . ptr::write(p, element); . } 15,604 ( 0.00%) self.set_len(len + 1); . } 14,682 ( 0.00%) } . . /// Removes and returns the element at position `index` within the vector, . /// shifting all elements after it to the left. . /// . /// Note: Because this shifts over the remaining elements, it has a . /// worst-case performance of *O*(*n*). If you don't need the order of elements . /// to be preserved, use [`swap_remove`] instead. If you'd like to remove . /// elements from the beginning of the `Vec`, consider using -- line 1376 ---------------------------------------- -- line 1395 ---------------------------------------- . pub fn remove(&mut self, index: usize) -> T { . #[cold] . #[inline(never)] . #[track_caller] . fn assert_failed(index: usize, len: usize) -> ! { . panic!("removal index (is {}) should be < len (is {})", index, len); . } . 1,444 ( 0.00%) let len = self.len(); 5,693 ( 0.00%) if index >= len { . assert_failed(index, len); . } . unsafe { . // infallible . let ret; . { . // the place we are taking from. . let ptr = self.as_mut_ptr().add(index); . // copy it out, unsafely having a copy of the value on . // the stack and in the vector at the same time. 1,328 ( 0.00%) ret = ptr::read(ptr); . . // Shift everything down to fill in that spot. 3,062 ( 0.00%) ptr::copy(ptr.offset(1), ptr, len - index - 1); . } 3,325 ( 0.00%) self.set_len(len - 1); . ret . } . } . . /// Retains only the elements specified by the predicate. . /// . /// In other words, remove all elements `e` such that `f(&e)` returns `false`. . /// This method operates in place, visiting each element exactly once in the -- line 1428 ---------------------------------------- -- line 1442 ---------------------------------------- . /// ``` . /// let mut vec = vec![1, 2, 3, 4, 5]; . /// let keep = [false, true, true, false, true]; . /// let mut iter = keep.iter(); . /// vec.retain(|_| *iter.next().unwrap()); . /// assert_eq!(vec, [2, 3, 5]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 2,109,023 ( 0.01%) pub fn retain(&mut self, mut f: F) . where . F: FnMut(&T) -> bool, . { 58,184 ( 0.00%) self.retain_mut(|elem| f(elem)); 2,060,656 ( 0.01%) } . . /// Retains only the elements specified by the predicate, passing a mutable reference to it. . /// . /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`. . /// This method operates in place, visiting each element exactly once in the . /// original order, and preserves the order of the retained elements. . /// . /// # Examples -- line 1463 ---------------------------------------- -- line 1474 ---------------------------------------- . /// }); . /// assert_eq!(vec, [2, 3, 4]); . /// ``` . #[unstable(feature = "vec_retain_mut", issue = "90829")] . pub fn retain_mut(&mut self, mut f: F) . where . F: FnMut(&mut T) -> bool, . { 267,602 ( 0.00%) let original_len = self.len(); . // Avoid double drop if the drop guard is not executed, . // since we may make some holes during the process. . unsafe { self.set_len(0) }; . . // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked] . // |<- processed len ->| ^- next to check . // |<- deleted cnt ->| . // |<- original_len ->| -- line 1490 ---------------------------------------- -- line 1499 ---------------------------------------- . v: &'a mut Vec, . processed_len: usize, . deleted_cnt: usize, . original_len: usize, . } . . impl Drop for BackshiftOnDrop<'_, T, A> { . fn drop(&mut self) { 249,793 ( 0.00%) if self.deleted_cnt > 0 { . // SAFETY: Trailing unchecked items must be valid since we never touch them. . unsafe { . ptr::copy( . self.v.as_ptr().add(self.processed_len), 218,048 ( 0.00%) self.v.as_mut_ptr().add(self.processed_len - self.deleted_cnt), . self.original_len - self.processed_len, . ); . } . } . // SAFETY: After filling holes, all items are in contiguous memory. . unsafe { 2 ( 0.00%) self.v.set_len(self.original_len - self.deleted_cnt); . } . } . } . . let mut g = BackshiftOnDrop { v: self, processed_len: 0, deleted_cnt: 0, original_len }; . . fn process_loop( . original_len: usize, . f: &mut F, . g: &mut BackshiftOnDrop<'_, T, A>, . ) where . F: FnMut(&mut T) -> bool, . { 2,735,000 ( 0.02%) while g.processed_len != original_len { . // SAFETY: Unchecked element must be valid. . let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) }; 718,908 ( 0.00%) if !f(cur) { . // Advance early to avoid double drop if `drop_in_place` panicked. 148,520 ( 0.00%) g.processed_len += 1; 74,028 ( 0.00%) g.deleted_cnt += 1; . // SAFETY: We never touch this element again after dropped. 547 ( 0.00%) unsafe { ptr::drop_in_place(cur) }; . // We already advanced the counter. . if DELETED { . continue; . } else { . break; . } . } . if DELETED { . // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element. . // We use copy for move, and never touch this element again. . unsafe { 114,432 ( 0.00%) let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt); . ptr::copy_nonoverlapping(cur, hole_slot, 1); . } . } 110,264 ( 0.00%) g.processed_len += 1; . } . } . . // Stage 1: Nothing was deleted. . process_loop::(original_len, &mut f, &mut g); . . // Stage 2: Some elements were deleted. . process_loop::(original_len, &mut f, &mut g); -- line 1565 ---------------------------------------- -- line 1606 ---------------------------------------- . /// ``` . /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"]; . /// . /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); . /// . /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]); . /// ``` . #[stable(feature = "dedup_by", since = "1.16.0")] 26,908 ( 0.00%) pub fn dedup_by(&mut self, mut same_bucket: F) . where . F: FnMut(&mut T, &mut T) -> bool, . { 10,356 ( 0.00%) let len = self.len(); 24,402 ( 0.00%) if len <= 1 { . return; . } . . /* INVARIANT: vec.len() > read >= write > write-1 >= 0 */ . struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> { . /* Offset of the element we want to check if it is duplicate */ . read: usize, . -- line 1627 ---------------------------------------- -- line 1670 ---------------------------------------- . let ptr = gap.vec.as_mut_ptr(); . . /* Drop items while going through Vec, it should be more efficient than . * doing slice partition_dedup + truncate */ . . /* SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr . * are always in-bounds and read_ptr never aliases prev_ptr */ . unsafe { 56,251 ( 0.00%) while gap.read < len { . let read_ptr = ptr.add(gap.read); . let prev_ptr = ptr.add(gap.write.wrapping_sub(1)); . 4,273 ( 0.00%) if same_bucket(&mut *read_ptr, &mut *prev_ptr) { . // Increase `gap.read` now since the drop may panic. . gap.read += 1; . /* We have found duplicate, drop it in-place */ . ptr::drop_in_place(read_ptr); . } else { . let write_ptr = ptr.add(gap.write); . . /* Because `read_ptr` can be equal to `write_ptr`, we either . * have to use `copy` or conditional `copy_nonoverlapping`. . * Looks like the first option is faster. */ . ptr::copy(read_ptr, write_ptr, 1); . . /* We have filled that place, so go further */ 31,014 ( 0.00%) gap.write += 1; . gap.read += 1; . } . } . . /* Technically we could let `gap` clean up with its Drop, but . * when `same_bucket` is guaranteed to not panic, this bloats a little . * the codegen, so we just do it manually */ . gap.vec.set_len(gap.write); . mem::forget(gap); . } 30,752 ( 0.00%) } . . /// Appends an element to the back of a collection. . /// . /// # Panics . /// . /// Panics if the new capacity exceeds `isize::MAX` bytes. . /// . /// # Examples -- line 1715 ---------------------------------------- -- line 1717 ---------------------------------------- . /// ``` . /// let mut vec = vec![1, 2]; . /// vec.push(3); . /// assert_eq!(vec, [1, 2, 3]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 2,630 ( 0.00%) pub fn push(&mut self, value: T) { . // This will panic or abort if we would allocate > isize::MAX bytes . // or if the length increment would overflow for zero-sized types. 15,407,439 ( 0.09%) if self.len == self.buf.capacity() { 1,152,146 ( 0.01%) self.buf.reserve_for_push(self.len); . } . unsafe { 541,008 ( 0.00%) let end = self.as_mut_ptr().add(self.len); . ptr::write(end, value); 22,668,093 ( 0.13%) self.len += 1; . } 2,104 ( 0.00%) } . . /// Removes the last element from a vector and returns it, or [`None`] if it . /// is empty. . /// . /// If you'd like to pop the first element, consider using . /// [`VecDeque::pop_front`] instead. . /// . /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front -- line 1744 ---------------------------------------- -- line 1748 ---------------------------------------- . /// ``` . /// let mut vec = vec![1, 2, 3]; . /// assert_eq!(vec.pop(), Some(3)); . /// assert_eq!(vec, [1, 2]); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn pop(&mut self) -> Option { 6,057,181 ( 0.03%) if self.len == 0 { 95 ( 0.00%) None . } else { . unsafe { 4,069,207 ( 0.02%) self.len -= 1; 1,293,127 ( 0.01%) Some(ptr::read(self.as_ptr().add(self.len()))) . } . } . } . . /// Moves all the elements of `other` into `Self`, leaving `other` empty. . /// . /// # Panics . /// -- line 1769 ---------------------------------------- -- line 1776 ---------------------------------------- . /// let mut vec2 = vec![4, 5, 6]; . /// vec.append(&mut vec2); . /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]); . /// assert_eq!(vec2, []); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "append", since = "1.4.0")] 1,113 ( 0.00%) pub fn append(&mut self, other: &mut Self) { . unsafe { . self.append_elements(other.as_slice() as _); . other.set_len(0); . } 954 ( 0.00%) } . . /// Appends elements to `Self` from other buffer. . #[cfg(not(no_global_oom_handling))] . #[inline] . unsafe fn append_elements(&mut self, other: *const [T]) { . let count = unsafe { (*other).len() }; . self.reserve(count); 340,309 ( 0.00%) let len = self.len(); 436 ( 0.00%) unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; 1,933,046 ( 0.01%) self.len += count; . } . . /// Creates a draining iterator that removes the specified range in the vector . /// and yields the removed items. . /// . /// When the iterator **is** dropped, all elements in the range are removed . /// from the vector, even if the iterator was not fully consumed. If the . /// iterator **is not** dropped (with [`mem::forget`] for example), it is -- line 1807 ---------------------------------------- -- line 1834 ---------------------------------------- . // When the Drain is first created, it shortens the length of . // the source vector to make sure no uninitialized or moved-from elements . // are accessible at all if the Drain's destructor never gets to run. . // . // Drain will ptr::read out the values to remove. . // When finished, remaining tail of the vec is copied back to cover . // the hole, and the vector length is restored to the new length. . // 81,533 ( 0.00%) let len = self.len(); . let Range { start, end } = slice::range(range, ..len); . . unsafe { . // set self.vec length's to start, to be safe in case Drain is leaked . self.set_len(start); . // Use the borrow in the IterMut to indicate borrowing behavior of the . // whole Drain iterator (like &mut T). 4,082 ( 0.00%) let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); 758 ( 0.00%) Drain { . tail_start: end, 2,756 ( 0.00%) tail_len: len - end, . iter: range_slice.iter(), . vec: NonNull::from(self), . } . } . } . . /// Clears the vector, removing all values. . /// -- line 1861 ---------------------------------------- -- line 1869 ---------------------------------------- . /// . /// v.clear(); . /// . /// assert!(v.is_empty()); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn clear(&mut self) { 611,861 ( 0.00%) self.truncate(0) . } . . /// Returns the number of elements in the vector, also referred to . /// as its 'length'. . /// . /// # Examples . /// . /// ``` -- line 1885 ---------------------------------------- -- line 1900 ---------------------------------------- . /// let mut v = Vec::new(); . /// assert!(v.is_empty()); . /// . /// v.push(1); . /// assert!(!v.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn is_empty(&self) -> bool { 1,924,482 ( 0.01%) self.len() == 0 . } . . /// Splits the collection into two at the given index. . /// . /// Returns a newly allocated vector containing the elements in the range . /// `[at, len)`. After the call, the original vector will be left containing . /// the elements `[0, at)` with its previous capacity unchanged. . /// -- line 1916 ---------------------------------------- -- line 1935 ---------------------------------------- . A: Clone, . { . #[cold] . #[inline(never)] . fn assert_failed(at: usize, len: usize) -> ! { . panic!("`at` split index (is {}) should be <= len (is {})", at, len); . } . 3,887 ( 0.00%) if at > self.len() { . assert_failed(at, self.len()); . } . 3,091 ( 0.00%) if at == 0 { . // the new vector can take over the original buffer and avoid the copy . return mem::replace( . self, . Vec::with_capacity_in(self.capacity(), self.allocator().clone()), . ); . } . . let other_len = self.len - at; -- line 1955 ---------------------------------------- -- line 1988 ---------------------------------------- . /// . /// let mut vec = vec![]; . /// let mut p = 1; . /// vec.resize_with(4, || { p *= 2; p }); . /// assert_eq!(vec, [2, 4, 8, 16]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize_with", since = "1.33.0")] 108,198 ( 0.00%) pub fn resize_with(&mut self, new_len: usize, f: F) . where . F: FnMut() -> T, . { 14,748 ( 0.00%) let len = self.len(); 29,496 ( 0.00%) if new_len > len { 133,287 ( 0.00%) self.extend_with(new_len - len, ExtendFunc(f)); . } else { . self.truncate(new_len); . } 93,450 ( 0.00%) } . . /// Consumes and leaks the `Vec`, returning a mutable reference to the contents, . /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime . /// `'a`. If the type has only static references, or none at all, then this . /// may be chosen to be `'static`. . /// . /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`, . /// so the leaked allocation may include unused capacity that is not part -- line 2014 ---------------------------------------- -- line 2070 ---------------------------------------- . #[stable(feature = "vec_spare_capacity", since = "1.60.0")] . #[inline] . pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { . // Note: . // This method is not implemented in terms of `split_at_spare_mut`, . // to prevent invalidation of pointers to the buffer. . unsafe { . slice::from_raw_parts_mut( 2 ( 0.00%) self.as_mut_ptr().add(self.len) as *mut MaybeUninit, 154 ( 0.00%) self.buf.capacity() - self.len, . ) . } . } . . /// Returns vector content as a slice of `T`, along with the remaining spare . /// capacity of the vector as a slice of `MaybeUninit`. . /// . /// The returned spare capacity slice can be used to fill the vector with data -- line 2087 ---------------------------------------- -- line 2189 ---------------------------------------- . /// assert_eq!(vec, ["hello", "world", "world"]); . /// . /// let mut vec = vec![1, 2, 3, 4]; . /// vec.resize(2, 0); . /// assert_eq!(vec, [1, 2]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize", since = "1.5.0")] 165,020 ( 0.00%) pub fn resize(&mut self, new_len: usize, value: T) { 16,502 ( 0.00%) let len = self.len(); . 49,506 ( 0.00%) if new_len > len { 19,611 ( 0.00%) self.extend_with(new_len - len, ExtendElement(value)) . } else { . self.truncate(new_len); . } 26,142 ( 0.00%) } . . /// Clones and appends all elements in a slice to the `Vec`. . /// . /// Iterates over the slice `other`, clones each element, and then appends . /// it to this `Vec`. The `other` slice is traversed in-order. . /// . /// Note that this function is same as [`extend`] except that it is . /// specialized to work with slices instead. If and when Rust gets -- line 2213 ---------------------------------------- -- line 2271 ---------------------------------------- . trait ExtendWith { . fn next(&mut self) -> T; . fn last(self) -> T; . } . . struct ExtendElement(T); . impl ExtendWith for ExtendElement { . fn next(&mut self) -> T { 2,257 ( 0.00%) self.0.clone() . } . fn last(self) -> T { . self.0 . } . } . . struct ExtendFunc(F); . impl T> ExtendWith for ExtendFunc { -- line 2287 ---------------------------------------- -- line 2291 ---------------------------------------- . fn last(mut self) -> T { . (self.0)() . } . } . . impl Vec { . #[cfg(not(no_global_oom_handling))] . /// Extend the vector by `n` values, using the given generator. 1,223,362 ( 0.01%) fn extend_with>(&mut self, n: usize, mut value: E) { . self.reserve(n); . . unsafe { 15,357 ( 0.00%) let mut ptr = self.as_mut_ptr().add(self.len()); . // Use SetLenOnDrop to work around bug where compiler . // might not realize the store through `ptr` through self.set_len() . // don't alias. . let mut local_len = SetLenOnDrop::new(&mut self.len); . . // Write all elements except the last one . for _ in 1..n { . ptr::write(ptr, value.next()); . ptr = ptr.offset(1); . // Increment the length in every step in case next() panics . local_len.increment_len(1); . } . 978,696 ( 0.01%) if n > 0 { . // We can write the last element directly without cloning needlessly . ptr::write(ptr, value.last()); . local_len.increment_len(1); . } . . // len set by scope guard . } 977,017 ( 0.01%) } . } . . impl Vec { . /// Removes consecutive repeated elements in the vector according to the . /// [`PartialEq`] trait implementation. . /// . /// If the vector is sorted, this removes all duplicates. . /// -- line 2333 ---------------------------------------- -- line 2338 ---------------------------------------- . /// . /// vec.dedup(); . /// . /// assert_eq!(vec, [1, 2, 3, 2]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn dedup(&mut self) { 3,851 ( 0.00%) self.dedup_by(|a, b| a == b) . } . } . . //////////////////////////////////////////////////////////////////////////////// . // Internal methods and functions . //////////////////////////////////////////////////////////////////////////////// . . #[doc(hidden)] . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 203,765 ( 0.00%) pub fn from_elem(elem: T, n: usize) -> Vec { 1,463,284 ( 0.01%) ::from_elem(elem, n, Global) 247,587 ( 0.00%) } . . #[doc(hidden)] . #[cfg(not(no_global_oom_handling))] . #[unstable(feature = "allocator_api", issue = "32838")] . pub fn from_elem_in(elem: T, n: usize, alloc: A) -> Vec { . ::from_elem(elem, n, alloc) . } . -- line 2367 ---------------------------------------- -- line 2424 ---------------------------------------- . // Common trait implementations for Vec . //////////////////////////////////////////////////////////////////////////////// . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::Deref for Vec { . type Target = [T]; . . fn deref(&self) -> &[T] { 51,939,021 ( 0.29%) unsafe { slice::from_raw_parts(self.as_ptr(), self.len) } 268 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::DerefMut for Vec { . fn deref_mut(&mut self) -> &mut [T] { 29,187,299 ( 0.17%) unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) } . } . } . . #[cfg(not(no_global_oom_handling))] . trait SpecCloneFrom { . fn clone_from(this: &mut Self, other: &Self); . } . -- line 2447 ---------------------------------------- -- line 2468 ---------------------------------------- . this.extend_from_slice(other); . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Vec { . #[cfg(not(test))] 708,704 ( 0.00%) fn clone(&self) -> Self { . let alloc = self.allocator().clone(); 2 ( 0.00%) <[T]>::to_vec_in(&**self, alloc) 853,203 ( 0.00%) } . . // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is . // required for this method definition, is not available. Instead use the . // `slice::to_vec` function which is only available with cfg(test) . // NB see the slice::hack module in slice.rs for more information . #[cfg(test)] . fn clone(&self) -> Self { . let alloc = self.allocator().clone(); -- line 2487 ---------------------------------------- -- line 2518 ---------------------------------------- . message = "vector indices are of type `usize` or ranges of `usize`", . label = "vector indices are of type `usize` or ranges of `usize`" . )] . impl, A: Allocator> Index for Vec { . type Output = I::Output; . . #[inline] . fn index(&self, index: I) -> &Self::Output { 918,900 ( 0.01%) Index::index(&**self, index) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_on_unimplemented( . message = "vector indices are of type `usize` or ranges of `usize`", . label = "vector indices are of type `usize` or ranges of `usize`" . )] . impl, A: Allocator> IndexMut for Vec { . #[inline] . fn index_mut(&mut self, index: I) -> &mut Self::Output { 1,568 ( 0.00%) IndexMut::index_mut(&mut **self, index) . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl FromIterator for Vec { . #[inline] . fn from_iter>(iter: I) -> Vec { 5,515,812 ( 0.03%) >::from_iter(iter.into_iter()) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl IntoIterator for Vec { . type Item = T; . type IntoIter = IntoIter; . -- line 2555 ---------------------------------------- -- line 2564 ---------------------------------------- . /// for s in v.into_iter() { . /// // s has type String, not &String . /// println!("{}", s); . /// } . /// ``` . #[inline] . fn into_iter(self) -> IntoIter { . unsafe { 2,153,497 ( 0.01%) let mut me = ManuallyDrop::new(self); . let alloc = ptr::read(me.allocator()); . let begin = me.as_mut_ptr(); . let end = if mem::size_of::() == 0 { . arith_offset(begin as *const i8, me.len() as isize) as *const T . } else { . begin.add(me.len()) as *const T . }; . let cap = me.buf.capacity(); 684,673 ( 0.00%) IntoIter { . buf: NonNull::new_unchecked(begin), . phantom: PhantomData, . cap, . alloc, . ptr: begin, . end, . } . } -- line 2589 ---------------------------------------- -- line 2591 ---------------------------------------- . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T, A: Allocator> IntoIterator for &'a Vec { . type Item = &'a T; . type IntoIter = slice::Iter<'a, T>; . . fn into_iter(self) -> slice::Iter<'a, T> { 218 ( 0.00%) self.iter() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec { . type Item = &'a mut T; . type IntoIter = slice::IterMut<'a, T>; . . fn into_iter(self) -> slice::IterMut<'a, T> { 1,084 ( 0.00%) self.iter_mut() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend for Vec { . #[inline] 11,984 ( 0.00%) fn extend>(&mut self, iter: I) { 2,593,035 ( 0.01%) >::spec_extend(self, iter.into_iter()) 11,984 ( 0.00%) } . . #[inline] . fn extend_one(&mut self, item: T) { . self.push(item); . } . . #[inline] . fn extend_reserve(&mut self, additional: usize) { -- line 2627 ---------------------------------------- -- line 2636 ---------------------------------------- . fn extend_desugared>(&mut self, mut iterator: I) { . // This is the case for a general iterator. . // . // This function should be the moral equivalent of: . // . // for item in iterator { . // self.push(item); . // } 375,945 ( 0.00%) while let Some(element) = iterator.next() { 118,031 ( 0.00%) let len = self.len(); 1,854,633 ( 0.01%) if len == self.capacity() { 2,102 ( 0.00%) let (lower, _) = iterator.size_hint(); . self.reserve(lower.saturating_add(1)); . } . unsafe { . ptr::write(self.as_mut_ptr().add(len), element); . // Since next() executes user code which can panic we have to bump the length . // after each step. . // NB can't overflow since we would have had to alloc the address space 1,272,934 ( 0.01%) self.set_len(len + 1); . } . } 17,003 ( 0.00%) } . . /// Creates a splicing iterator that replaces the specified range in the vector . /// with the given `replace_with` iterator and yields the removed items. . /// `replace_with` does not need to be the same length as `range`. . /// . /// `range` is removed even if the iterator is not consumed until the end. . /// . /// It is unspecified how many elements are removed from the vector -- line 2666 ---------------------------------------- -- line 2693 ---------------------------------------- . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "vec_splice", since = "1.21.0")] . pub fn splice(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A> . where . R: RangeBounds, . I: IntoIterator, . { 14,586 ( 0.00%) Splice { drain: self.drain(range), replace_with: replace_with.into_iter() } . } . . /// Creates an iterator which uses a closure to determine if an element should be removed. . /// . /// If the closure returns true, then the element is removed and yielded. . /// If the closure returns false, the element will remain in the vector and will not be yielded . /// by the iterator. . /// -- line 2709 ---------------------------------------- -- line 2745 ---------------------------------------- . /// assert_eq!(evens, vec![2, 4, 6, 8, 14]); . /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]); . /// ``` . #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")] . pub fn drain_filter(&mut self, filter: F) -> DrainFilter<'_, T, F, A> . where . F: FnMut(&mut T) -> bool, . { 6,538 ( 0.00%) let old_len = self.len(); . . // Guard against us getting leaked (leak amplification) . unsafe { . self.set_len(0); . } . 21,184 ( 0.00%) DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false } . } . } . . /// Extend implementation that copies elements out of references before pushing them onto the Vec. . /// . /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to . /// append the entire slice at once. . /// . /// [`copy_from_slice`]: slice::copy_from_slice . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "extend_ref", since = "1.2.0")] . impl<'a, T: Copy + 'a, A: Allocator + 'a> Extend<&'a T> for Vec { 18,200 ( 0.00%) fn extend>(&mut self, iter: I) { . self.spec_extend(iter.into_iter()) 13,650 ( 0.00%) } . . #[inline] . fn extend_one(&mut self, &item: &'a T) { . self.push(item); . } . . #[inline] . fn extend_reserve(&mut self, additional: usize) { -- line 2783 ---------------------------------------- -- line 2803 ---------------------------------------- . #[inline] . fn cmp(&self, other: &Self) -> Ordering { . Ord::cmp(&**self, &**other) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec { 2,616,566 ( 0.01%) fn drop(&mut self) { . unsafe { . // use drop for [T] . // use a raw slice to refer to the elements of the vector as weakest necessary type; . // could avoid questions of validity in certain cases 1,260,136 ( 0.01%) ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len)) . } . // RawVec handles deallocation 3,092,514 ( 0.02%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] . impl const Default for Vec { . /// Creates an empty `Vec`. . fn default() -> Vec { . Vec::new() -- line 2827 ---------------------------------------- -- line 2976 ---------------------------------------- . /// newly-allocated buffer with exactly the right capacity. . /// . /// # Examples . /// . /// ``` . /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice()); . /// ``` . fn from(v: Vec) -> Self { 4 ( 0.00%) v.into_boxed_slice() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl From<&str> for Vec { . /// Allocate a `Vec` and fill it with a UTF-8 string. . /// -- line 2992 ---------------------------------------- 14,484,730 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs -------------------------------------------------------------------------------- Ir -- line 346 ---------------------------------------- . /// . /// let c = Cell::new(5); . /// . /// c.set(10); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn set(&self, val: T) { 1,456 ( 0.00%) let old = self.replace(val); 3,308 ( 0.00%) drop(old); . } . . /// Swaps the values of two `Cell`s. . /// Difference with `std::mem::swap` is that this function doesn't require `&mut` reference. . /// . /// # Examples . /// . /// ``` -- line 363 ---------------------------------------- -- line 434 ---------------------------------------- . /// . /// let five = c.get(); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn get(&self) -> T { . // SAFETY: This can cause data races if called from a separate thread, . // but `Cell` is `!Sync` so this won't happen. 601,145 ( 0.00%) unsafe { *self.value.get() } . } . . /// Updates the contained value using a function and returns the new value. . /// . /// # Examples . /// . /// ``` . /// #![feature(cell_update)] -- line 450 ---------------------------------------- -- line 689 ---------------------------------------- . . #[inline(always)] . fn is_writing(x: BorrowFlag) -> bool { . x < UNUSED . } . . #[inline(always)] . fn is_reading(x: BorrowFlag) -> bool { 1,668,863 ( 0.01%) x > UNUSED . } . . impl RefCell { . /// Creates a new `RefCell` containing `value`. . /// . /// # Examples . /// . /// ``` -- line 705 ---------------------------------------- -- line 706 ---------------------------------------- . /// use std::cell::RefCell; . /// . /// let c = RefCell::new(5); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_refcell_new", since = "1.24.0")] . #[inline] . pub const fn new(value: T) -> RefCell { 158,359 ( 0.00%) RefCell { 121,180 ( 0.00%) value: UnsafeCell::new(value), . borrow: Cell::new(UNUSED), . #[cfg(feature = "debug_refcell")] . borrowed_at: Cell::new(None), . } . } . . /// Consumes the `RefCell`, returning the wrapped value. . /// -- line 723 ---------------------------------------- -- line 731 ---------------------------------------- . /// let five = c.into_inner(); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_cell_into_inner", issue = "78729")] . #[inline] . pub const fn into_inner(self) -> T { . // Since this function takes `self` (the `RefCell`) by value, the . // compiler statically verifies that it is not currently borrowed. 6,332 ( 0.00%) self.value.into_inner() . } . . /// Replaces the wrapped value with a new one, returning the old value, . /// without deinitializing either one. . /// . /// This function corresponds to [`std::mem::replace`](../mem/fn.replace.html). . /// . /// # Panics -- line 747 ---------------------------------------- -- line 845 ---------------------------------------- . /// let c = RefCell::new(5); . /// . /// let m = c.borrow_mut(); . /// let b = c.borrow(); // this causes a panic . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] 28,703 ( 0.00%) pub fn borrow(&self) -> Ref<'_, T> { . self.try_borrow().expect("already mutably borrowed") 86,109 ( 0.00%) } . . /// Immutably borrows the wrapped value, returning an error if the value is currently mutably . /// borrowed. . /// . /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be . /// taken out at the same time. . /// . /// This is the non-panicking variant of [`borrow`](#method.borrow). -- line 863 ---------------------------------------- -- line 937 ---------------------------------------- . /// let c = RefCell::new(5); . /// let m = c.borrow(); . /// . /// let b = c.borrow_mut(); // this causes a panic . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] 70,485 ( 0.00%) pub fn borrow_mut(&self) -> RefMut<'_, T> { . self.try_borrow_mut().expect("already borrowed") 211,455 ( 0.00%) } . . /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed. . /// . /// The borrow lasts until the returned `RefMut` or all `RefMut`s derived . /// from it exit scope. The value cannot be borrowed while this borrow is . /// active. . /// . /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut). -- line 955 ---------------------------------------- -- line 975 ---------------------------------------- . match BorrowRefMut::new(&self.borrow) { . Some(b) => { . #[cfg(feature = "debug_refcell")] . { . self.borrowed_at.set(Some(crate::panic::Location::caller())); . } . . // SAFETY: `BorrowRef` guarantees unique access. 3,663 ( 0.00%) Ok(RefMut { value: unsafe { &mut *self.value.get() }, borrow: b }) . } . None => Err(BorrowMutError { . // If a borrow occurred, then we must already have an outstanding borrow, . // so `borrowed_at` will be `Some` . #[cfg(feature = "debug_refcell")] . location: self.borrowed_at.get().unwrap(), . }), . } -- line 991 ---------------------------------------- -- line 1254 ---------------------------------------- . . struct BorrowRef<'b> { . borrow: &'b Cell, . } . . impl<'b> BorrowRef<'b> { . #[inline] . fn new(borrow: &'b Cell) -> Option> { 2,408,028 ( 0.01%) let b = borrow.get().wrapping_add(1); 1,460,026 ( 0.01%) if !is_reading(b) { . // Incrementing borrow can result in a non-reading value (<= 0) in these cases: . // 1. It was < 0, i.e. there are writing borrows, so we can't allow a read borrow . // due to Rust's reference aliasing rules . // 2. It was isize::MAX (the max amount of reading borrows) and it overflowed . // into isize::MIN (the max amount of writing borrows) so we can't allow . // an additional read borrow because isize can't represent so many read borrows . // (this can only happen if you mem::forget more than a small constant amount of . // `Ref`s, which is not good practice) -- line 1271 ---------------------------------------- -- line 1279 ---------------------------------------- . Some(BorrowRef { borrow }) . } . } . } . . impl Drop for BorrowRef<'_> { . #[inline] . fn drop(&mut self) { 878,983 ( 0.00%) let borrow = self.borrow.get(); . debug_assert!(is_reading(borrow)); 1,801,999 ( 0.01%) self.borrow.set(borrow - 1); . } . } . . impl Clone for BorrowRef<'_> { . #[inline] . fn clone(&self) -> Self { . // Since this Ref exists, we know the borrow flag . // is a reading borrow. -- line 1297 ---------------------------------------- -- line 1645 ---------------------------------------- . . struct BorrowRefMut<'b> { . borrow: &'b Cell, . } . . impl Drop for BorrowRefMut<'_> { . #[inline] . fn drop(&mut self) { 21,334,626 ( 0.12%) let borrow = self.borrow.get(); . debug_assert!(is_writing(borrow)); 42,404,369 ( 0.24%) self.borrow.set(borrow + 1); . } . } . . impl<'b> BorrowRefMut<'b> { . #[inline] . fn new(borrow: &'b Cell) -> Option> { . // NOTE: Unlike BorrowRefMut::clone, new is called to create the initial . // mutable reference, and so there must currently be no existing . // references. Thus, while clone increments the mutable refcount, here . // we explicitly only allow going from UNUSED to UNUSED - 1. 43,793,020 ( 0.25%) match borrow.get() { . UNUSED => { . borrow.set(UNUSED - 1); . Some(BorrowRefMut { borrow }) . } . _ => None, . } . } . -- line 1674 ---------------------------------------- -- line 1711 ---------------------------------------- . self.value . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl DerefMut for RefMut<'_, T> { . #[inline] . fn deref_mut(&mut self) -> &mut T { 1,799 ( 0.00%) self.value . } . } . . #[unstable(feature = "coerce_unsized", issue = "27732")] . impl<'b, T: ?Sized + Unsize, U: ?Sized> CoerceUnsized> for RefMut<'b, T> {} . . #[stable(feature = "std_guard_impls", since = "1.20.0")] . impl fmt::Display for RefMut<'_, T> { -- line 1727 ---------------------------------------- -- line 1909 ---------------------------------------- . /// ``` . #[inline(always)] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_unsafecell_get", since = "1.32.0")] . pub const fn get(&self) -> *mut T { . // We can just cast the pointer from `UnsafeCell` to `T` because of . // #[repr(transparent)]. This exploits libstd's special status, there is . // no guarantee for user code that this will work in future versions of the compiler! 9,434,442 ( 0.05%) self as *const UnsafeCell as *const T as *mut T . } . . /// Returns a mutable reference to the underlying data. . /// . /// This call borrows the `UnsafeCell` mutably (at compile-time) which . /// guarantees that we possess the only reference. . /// . /// # Examples -- line 1925 ---------------------------------------- 28,600,928 ( 0.16%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/intrinsics.rs -------------------------------------------------------------------------------- Ir -- line 2075 ---------------------------------------- . // SAFETY: As per our safety precondition, we may assume that the `abort` above is never reached. . // Therefore, compiletime_check and runtime_check are observably equivalent. . unsafe { . const_eval_select((src, dst, count), compiletime_check, runtime_check); . } . . // SAFETY: the safety contract for `copy_nonoverlapping` must be . // upheld by the caller. 59,522,881 ( 0.34%) unsafe { copy_nonoverlapping(src, dst, count) } . } . . /// Copies `count * size_of::()` bytes from `src` to `dst`. The source . /// and destination may overlap. . /// . /// If the source and destination will *never* overlap, . /// [`copy_nonoverlapping`] can be used instead. . /// -- line 2091 ---------------------------------------- -- line 2165 ---------------------------------------- . #[cfg(debug_assertions)] . // SAFETY: As per our safety precondition, we may assume that the `abort` above is never reached. . // Therefore, compiletime_check and runtime_check are observably equivalent. . unsafe { . const_eval_select((src, dst), compiletime_check, runtime_check); . } . . // SAFETY: the safety contract for `copy` must be upheld by the caller. 11,181,287 ( 0.06%) unsafe { copy(src, dst, count) } . } . . /// Sets `count * size_of::()` bytes of memory starting at `dst` to . /// `val`. . /// . /// `write_bytes` is similar to C's [`memset`], but sets `count * . /// size_of::()` bytes to `val`. . /// -- line 2181 ---------------------------------------- -- line 2266 ---------------------------------------- . #[cfg(debug_assertions)] . // SAFETY: runtime debug-assertions are a best-effort basis; it's fine to . // not do them during compile time . unsafe { . const_eval_select((dst,), compiletime_check, runtime_check); . } . . // SAFETY: the safety contract for `write_bytes` must be upheld by the caller. 964,466 ( 0.01%) unsafe { write_bytes(dst, val, count) } . } . . /// Selects which function to call depending on the context. . /// . /// If this function is evaluated at compile-time, then a call to this . /// intrinsic will be replaced with a call to `called_in_const`. It gets . /// replaced with a call to `called_at_rt` otherwise. . /// -- line 2282 ---------------------------------------- 326,530 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs -------------------------------------------------------------------------------- Ir -- line 186 ---------------------------------------- . /// // use the values stored in map . /// ``` . pub struct HashMap { . pub(crate) hash_builder: S, . pub(crate) table: RawTable<(K, V), A>, . } . . impl Clone for HashMap { 776 ( 0.00%) fn clone(&self) -> Self { 1,991 ( 0.00%) HashMap { . hash_builder: self.hash_builder.clone(), 363 ( 0.00%) table: self.table.clone(), . } 873 ( 0.00%) } . . fn clone_from(&mut self, source: &Self) { . self.table.clone_from(&source.table); . . // Update hash_builder only if we successfully cloned all elements. . self.hash_builder.clone_from(&source.hash_builder); . } . } -- line 207 ---------------------------------------- -- line 210 ---------------------------------------- . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_hasher(hash_builder: &S) -> impl Fn(&(Q, V)) -> u64 + '_ . where . K: Borrow, . Q: Hash, . S: BuildHasher, . { 372,633 ( 0.00%) move |val| make_hash::(hash_builder, &val.0) . } . . /// Ensures that a single closure type across uses of this which, in turn prevents multiple . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . fn equivalent_key(k: &Q) -> impl Fn(&(K, V)) -> bool + '_ . where . K: Borrow, . Q: ?Sized + Eq, . { 1,335,116 ( 0.01%) move |x| k.eq(x.0.borrow()) . } . . /// Ensures that a single closure type across uses of this which, in turn prevents multiple . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . fn equivalent(k: &Q) -> impl Fn(&K) -> bool + '_ . where . K: Borrow, . Q: ?Sized + Eq, . { 1,361,059 ( 0.01%) move |x| k.eq(x.borrow()) . } . . #[cfg(not(feature = "nightly"))] . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_hash(hash_builder: &S, val: &Q) -> u64 . where . K: Borrow, . Q: Hash + ?Sized, -- line 248 ---------------------------------------- -- line 251 ---------------------------------------- . use core::hash::Hasher; . let mut state = hash_builder.build_hasher(); . val.hash(&mut state); . state.finish() . } . . #[cfg(feature = "nightly")] . #[cfg_attr(feature = "inline-more", inline)] 2 ( 0.00%) pub(crate) fn make_hash(hash_builder: &S, val: &Q) -> u64 . where . K: Borrow, . Q: Hash + ?Sized, . S: BuildHasher, . { . hash_builder.hash_one(val) 4 ( 0.00%) } . . #[cfg(not(feature = "nightly"))] . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_insert_hash(hash_builder: &S, val: &K) -> u64 . where . K: Hash, . S: BuildHasher, . { -- line 274 ---------------------------------------- -- line 367 ---------------------------------------- . /// let s = DefaultHashBuilder::default(); . /// let mut map = HashMap::with_hasher(s); . /// map.insert(1, 2); . /// ``` . /// . /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html . #[cfg_attr(feature = "inline-more", inline)] . pub const fn with_hasher(hash_builder: S) -> Self { 671,177 ( 0.00%) Self { . hash_builder, . table: RawTable::new(), . } . } . . /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` . /// to hash the keys. . /// -- line 383 ---------------------------------------- -- line 437 ---------------------------------------- . /// use hashbrown::hash_map::DefaultHashBuilder; . /// . /// let s = DefaultHashBuilder::default(); . /// let mut map = HashMap::with_hasher(s); . /// map.insert(1, 2); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn with_hasher_in(hash_builder: S, alloc: A) -> Self { 1,738 ( 0.00%) Self { . hash_builder, . table: RawTable::new_in(alloc), . } . } . . /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` . /// to hash the keys. It will be allocated with the given allocator. . /// -- line 453 ---------------------------------------- -- line 527 ---------------------------------------- . /// map.insert("c", 3); . /// . /// for key in map.keys() { . /// println!("{}", key); . /// } . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn keys(&self) -> Keys<'_, K, V> { 6 ( 0.00%) Keys { inner: self.iter() } . } . . /// An iterator visiting all values in arbitrary order. . /// The iterator element type is `&'a V`. . /// . /// # Examples . /// . /// ``` -- line 543 ---------------------------------------- -- line 663 ---------------------------------------- . /// . /// let mut a = HashMap::new(); . /// assert_eq!(a.len(), 0); . /// a.insert(1, "a"); . /// assert_eq!(a.len(), 1); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn len(&self) -> usize { 70,780 ( 0.00%) self.table.len() . } . . /// Returns `true` if the map contains no elements. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; -- line 679 ---------------------------------------- -- line 680 ---------------------------------------- . /// . /// let mut a = HashMap::new(); . /// assert!(a.is_empty()); . /// a.insert(1, "a"); . /// assert!(!a.is_empty()); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn is_empty(&self) -> bool { 291,580 ( 0.00%) self.len() == 0 . } . . /// Clears the map, returning all key-value pairs as an iterator. Keeps the . /// allocated memory for reuse. . /// . /// # Examples . /// . /// ``` -- line 696 ---------------------------------------- -- line 790 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut a = HashMap::new(); . /// a.insert(1, "a"); . /// a.clear(); . /// assert!(a.is_empty()); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 6 ( 0.00%) pub fn clear(&mut self) { . self.table.clear(); 6 ( 0.00%) } . . /// Creates a consuming iterator visiting all the keys in arbitrary order. . /// The map cannot be used after calling this. . /// The iterator element type is `K`. . /// . /// # Examples . /// . /// ``` -- line 808 ---------------------------------------- -- line 963 ---------------------------------------- . /// } . /// . /// assert_eq!(letters[&'s'], 2); . /// assert_eq!(letters[&'t'], 3); . /// assert_eq!(letters[&'u'], 1); . /// assert_eq!(letters.get(&'y'), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 1,056 ( 0.00%) pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S, A> { . let hash = make_insert_hash::(&self.hash_builder, &key); . if let Some(elem) = self.table.find(hash, equivalent_key(&key)) { 350 ( 0.00%) Entry::Occupied(OccupiedEntry { . hash, . key: Some(key), . elem, . table: self, . }) . } else { 970 ( 0.00%) Entry::Vacant(VacantEntry { . hash, . key, . table: self, . }) . } 1,320 ( 0.00%) } . . /// Gets the given key's corresponding entry by reference in the map for in-place manipulation. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; . /// -- line 995 ---------------------------------------- -- line 1047 ---------------------------------------- . /// ``` . #[inline] . pub fn get(&self, k: &Q) -> Option<&V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 2,896,609 ( 0.02%) match self.get_inner(k) { . Some(&(_, ref v)) => Some(v), . None => None, . } . } . . /// Returns the key-value pair corresponding to the supplied key. . /// . /// The supplied key may be any borrowed form of the map's key type, but -- line 1063 ---------------------------------------- -- line 1091 ---------------------------------------- . } . . #[inline] . fn get_inner(&self, k: &Q) -> Option<&(K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 3,420,580 ( 0.02%) if self.table.is_empty() { . None . } else { 1 ( 0.00%) let hash = make_hash::(&self.hash_builder, k); . self.table.get(hash, equivalent_key(k)) . } . } . . /// Returns the key-value pair corresponding to the supplied key, with a mutable reference to value. . /// . /// The supplied key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for -- line 1110 ---------------------------------------- -- line 1155 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.contains_key(&1), true); . /// assert_eq!(map.contains_key(&2), false); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 1,106,416 ( 0.01%) pub fn contains_key(&self, k: &Q) -> bool . where . K: Borrow, . Q: Hash + Eq, . { . self.get_inner(k).is_some() 1,415,554 ( 0.01%) } . . /// Returns a mutable reference to the value corresponding to the key. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// . /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html -- line 1177 ---------------------------------------- -- line 1185 ---------------------------------------- . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// if let Some(x) = map.get_mut(&1) { . /// *x = "b"; . /// } . /// assert_eq!(map[&1], "b"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 889 ( 0.00%) pub fn get_mut(&mut self, k: &Q) -> Option<&mut V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 12,843 ( 0.00%) match self.get_inner_mut(k) { . Some(&mut (_, ref mut v)) => Some(v), . None => None, . } 1,778 ( 0.00%) } . . #[inline] . fn get_inner_mut(&mut self, k: &Q) -> Option<&mut (K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 4,281 ( 0.00%) if self.table.is_empty() { . None . } else { . let hash = make_hash::(&self.hash_builder, k); 6,784 ( 0.00%) self.table.get_mut(hash, equivalent_key(k)) . } . } . . /// Attempts to get mutable references to `N` values in the map at once. . /// . /// Returns an array of length `N` with the results of each query. For soundness, at most one . /// mutable reference will be returned to any value. `None` will be returned if any of the . /// keys are duplicates or missing. -- line 1223 ---------------------------------------- -- line 1495 ---------------------------------------- . /// assert_eq!(map.insert(37, "a"), None); . /// assert_eq!(map.is_empty(), false); . /// . /// map.insert(37, "b"); . /// assert_eq!(map.insert(37, "c"), Some("b")); . /// assert_eq!(map[&37], "c"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 9,009,052 ( 0.05%) pub fn insert(&mut self, k: K, v: V) -> Option { . let hash = make_insert_hash::(&self.hash_builder, &k); 21,689 ( 0.00%) if let Some((_, item)) = self.table.get_mut(hash, equivalent_key(&k)) { 2 ( 0.00%) Some(mem::replace(item, v)) . } else { 3,609,186 ( 0.02%) self.table 3,523,398 ( 0.02%) .insert(hash, (k, v), make_hasher::(&self.hash_builder)); 388,730 ( 0.00%) None . } 8,396,360 ( 0.05%) } . . /// Insert a key-value pair into the map without checking . /// if the key already exists in the map. . /// . /// Returns a reference to the key and value just inserted. . /// . /// This operation is safe if a key does not exist in the map. . /// -- line 1520 ---------------------------------------- -- line 1592 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.remove(&1), Some("a")); . /// assert_eq!(map.remove(&1), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 282,141 ( 0.00%) pub fn remove(&mut self, k: &Q) -> Option . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 1,713,265 ( 0.01%) match self.remove_entry(k) { 128,665 ( 0.00%) Some((_, v)) => Some(v), 221,041 ( 0.00%) None => None, . } 647,203 ( 0.00%) } . . /// Removes a key from the map, returning the stored key and value if the . /// key was previously in the map. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// -- line 1618 ---------------------------------------- -- line 1631 ---------------------------------------- . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn remove_entry(&mut self, k: &Q) -> Option<(K, V)> . where . K: Borrow, . Q: Hash + Eq, . { . let hash = make_hash::(&self.hash_builder, k); 665,235 ( 0.00%) self.table.remove_entry(hash, equivalent_key(k)) . } . } . . impl HashMap { . /// Creates a raw entry builder for the HashMap. . /// . /// Raw entries provide the lowest level of control for searching and . /// manipulating a map. They must be manually initialized with a hash and -- line 1647 ---------------------------------------- -- line 2209 ---------------------------------------- . /// Creates a `RawEntryMut` from the given key and its hash. . #[inline] . #[allow(clippy::wrong_self_convention)] . pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S, A> . where . K: Borrow, . Q: Eq, . { 7,314,108 ( 0.04%) self.from_hash(hash, equivalent(k)) . } . } . . impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilderMut<'a, K, V, S, A> { . /// Creates a `RawEntryMut` from the given hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] 18,795,965 ( 0.11%) pub fn from_hash(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S, A> . where . for<'b> F: FnMut(&'b K) -> bool, . { . self.search(hash, is_match) 20,242,788 ( 0.11%) } . . #[cfg_attr(feature = "inline-more", inline)] . fn search(self, hash: u64, mut is_match: F) -> RawEntryMut<'a, K, V, S, A> . where . for<'b> F: FnMut(&'b K) -> bool, . { 2,229,674 ( 0.01%) match self.map.table.find(hash, |(k, _)| is_match(k)) { 11,375,780 ( 0.06%) Some(elem) => RawEntryMut::Occupied(RawOccupiedEntryMut { . elem, . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), 1,347,016 ( 0.01%) None => RawEntryMut::Vacant(RawVacantEntryMut { . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), . } . } . } . . impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilder<'a, K, V, S, A> { -- line 2251 ---------------------------------------- -- line 2260 ---------------------------------------- . { . let hash = make_hash::(&self.map.hash_builder, k); . self.from_key_hashed_nocheck(hash, k) . } . . /// Access an entry by a key and its hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] 5,138,773 ( 0.03%) pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)> . where . K: Borrow, . Q: Eq, . { 5,587,909 ( 0.03%) self.from_hash(hash, equivalent(k)) 9,230,455 ( 0.05%) } . . #[cfg_attr(feature = "inline-more", inline)] . fn search(self, hash: u64, mut is_match: F) -> Option<(&'a K, &'a V)> . where . F: FnMut(&K) -> bool, . { 7,545,678 ( 0.04%) match self.map.table.get(hash, |(k, _)| is_match(k)) { . Some(&(ref key, ref value)) => Some((key, value)), . None => None, . } . } . . /// Access an entry by hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] -- line 2289 ---------------------------------------- -- line 2624 ---------------------------------------- . /// and returns a mutable reference to it. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::shadow_unrelated)] . pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) . where . K: Hash, . S: BuildHasher, . { 2,216,382 ( 0.01%) let &mut (ref mut k, ref mut v) = self.table.insert_entry( . hash, . (key, value), . make_hasher::(self.hash_builder), . ); . (k, v) . } . . /// Set the value of an entry with a custom hasher function. -- line 2640 ---------------------------------------- -- line 2974 ---------------------------------------- . /// map.insert("a", 1); . /// map.insert("b", 2); . /// map.insert("c", 3); . /// . /// // Not possible with .iter() . /// let vec: Vec<(&str, i32)> = map.into_iter().collect(); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 3,404 ( 0.00%) fn into_iter(self) -> IntoIter { 61,661 ( 0.00%) IntoIter { 33,638 ( 0.00%) inner: self.table.into_iter(), . } 10,212 ( 0.00%) } . } . . impl<'a, K, V> Iterator for Iter<'a, K, V> { . type Item = (&'a K, &'a V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(&'a K, &'a V)> { . // Avoid `Option::map` because it bloats LLVM IR. 591,920 ( 0.00%) match self.inner.next() { . Some(x) => unsafe { . let r = x.as_ref(); 3,471 ( 0.00%) Some((&r.0, &r.1)) . }, . None => None, . } . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { 1,633 ( 0.00%) self.inner.size_hint() . } . } . impl ExactSizeIterator for Iter<'_, K, V> { . #[cfg_attr(feature = "inline-more", inline)] . fn len(&self) -> usize { . self.inner.len() . } . } -- line 3013 ---------------------------------------- -- line 3051 ---------------------------------------- . } . } . . impl Iterator for IntoIter { . type Item = (K, V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(K, V)> { 20,547 ( 0.00%) self.inner.next() . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . } . impl ExactSizeIterator for IntoIter { . #[cfg_attr(feature = "inline-more", inline)] -- line 3067 ---------------------------------------- -- line 3076 ---------------------------------------- . f.debug_list().entries(self.iter()).finish() . } . } . . impl<'a, K, V> Iterator for Keys<'a, K, V> { . type Item = &'a K; . . #[cfg_attr(feature = "inline-more", inline)] 824 ( 0.00%) fn next(&mut self) -> Option<&'a K> { . // Avoid `Option::map` because it bloats LLVM IR. . match self.inner.next() { . Some((k, _)) => Some(k), . None => None, . } 1,648 ( 0.00%) } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . } . impl ExactSizeIterator for Keys<'_, K, V> { . #[cfg_attr(feature = "inline-more", inline)] . fn len(&self) -> usize { -- line 3098 ---------------------------------------- -- line 3819 ---------------------------------------- . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn insert(self, value: V) -> &'a mut V . where . K: Hash, . S: BuildHasher, . { . let table = &mut self.table.table; 84 ( 0.00%) let entry = table.insert_entry( . self.hash, . (self.key, value), . make_hasher::(&self.table.hash_builder), . ); . &mut entry.1 . } . . #[cfg_attr(feature = "inline-more", inline)] -- line 3835 ---------------------------------------- -- line 4557 ---------------------------------------- . /// keys with new values returned from the iterator. . impl Extend<(K, V)> for HashMap . where . K: Eq + Hash, . S: BuildHasher, . A: Allocator + Clone, . { . #[cfg_attr(feature = "inline-more", inline)] 101,326 ( 0.00%) fn extend>(&mut self, iter: T) { . // Keys may be already present or show multiple times in the iterator. . // Reserve the entire hint lower bound if the map is empty. . // Otherwise reserve half the hint (rounded up), so the map . // will only resize twice in the worst case. 64,303 ( 0.00%) let iter = iter.into_iter(); 88,894 ( 0.00%) let reserve = if self.is_empty() { . iter.size_hint().0 . } else { 3,445 ( 0.00%) (iter.size_hint().0 + 1) / 2 . }; . self.reserve(reserve); . iter.for_each(move |(k, v)| { 243,120 ( 0.00%) self.insert(k, v); . }); 73,680 ( 0.00%) } . . #[inline] . #[cfg(feature = "nightly")] . fn extend_one(&mut self, (k, v): (K, V)) { . self.insert(k, v); . } . . #[inline] -- line 4588 ---------------------------------------- 14,848,286 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs -------------------------------------------------------------------------------- Ir -- line 118 ---------------------------------------- . stability: InternedSet<'tcx, attr::Stability>, . . /// `#[rustc_const_stable]` and `#[rustc_const_unstable]` attributes . const_stability: InternedSet<'tcx, attr::ConstStability>, . } . . impl<'tcx> CtxtInterners<'tcx> { . fn new(arena: &'tcx WorkerLocal>) -> CtxtInterners<'tcx> { 17 ( 0.00%) CtxtInterners { . arena, . type_: Default::default(), . type_list: Default::default(), . substs: Default::default(), . region: Default::default(), . poly_existential_predicates: Default::default(), . canonical_var_infos: Default::default(), . predicate: Default::default(), -- line 134 ---------------------------------------- -- line 143 ---------------------------------------- . stability: Default::default(), . const_stability: Default::default(), . } . } . . /// Interns a type. . #[allow(rustc::usage_of_ty_tykind)] . #[inline(never)] 8,160,568 ( 0.05%) fn intern_ty(&self, kind: TyKind<'tcx>) -> Ty<'tcx> { . self.type_ 5,100,355 ( 0.03%) .intern(kind, |kind| { 272,162 ( 0.00%) let flags = super::flags::FlagComputation::for_kind(&kind); . . let ty_struct = TyS { 544,324 ( 0.00%) kind, . flags: flags.flags, . outer_exclusive_binder: flags.outer_exclusive_binder, . }; . . Interned(self.arena.alloc(ty_struct)) . }) . .0 9,180,639 ( 0.05%) } . . #[inline(never)] 2,208,968 ( 0.01%) fn intern_predicate( . &self, . kind: Binder<'tcx, PredicateKind<'tcx>>, . ) -> &'tcx PredicateInner<'tcx> { . self.predicate 1,932,847 ( 0.01%) .intern(kind, |kind| { 558,768 ( 0.00%) let flags = super::flags::FlagComputation::for_predicate(kind); . . let predicate_struct = PredicateInner { . kind, . flags: flags.flags, . outer_exclusive_binder: flags.outer_exclusive_binder, . }; . . Interned(self.arena.alloc(predicate_struct)) . }) . .0 2,485,089 ( 0.01%) } . } . . pub struct CommonTypes<'tcx> { . pub unit: Ty<'tcx>, . pub bool: Ty<'tcx>, . pub char: Ty<'tcx>, . pub isize: Ty<'tcx>, . pub i8: Ty<'tcx>, -- line 193 ---------------------------------------- -- line 237 ---------------------------------------- . /// safely used as a key in the maps of a TypeckResults. For that to be . /// the case, the HirId must have the same `owner` as all the other IDs in . /// this table (signified by `hir_owner`). Otherwise the HirId . /// would be in a different frame of reference and using its `local_id` . /// would result in lookup errors, or worse, in silently wrong data being . /// stored/returned. . #[inline] . fn validate_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) { 1,095,586 ( 0.01%) if hir_id.owner != hir_owner { . invalid_hir_id_for_typeck_results(hir_owner, hir_id); . } . } . . #[cold] . #[inline(never)] . fn invalid_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) { . ty::tls::with(|tcx| { -- line 253 ---------------------------------------- -- line 261 ---------------------------------------- . } . . impl<'a, V> LocalTableInContext<'a, V> { . pub fn contains_key(&self, id: hir::HirId) -> bool { . validate_hir_id_for_typeck_results(self.hir_owner, id); . self.data.contains_key(&id.local_id) . } . 848,273 ( 0.00%) pub fn get(&self, id: hir::HirId) -> Option<&V> { 168,366 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); 168,366 ( 0.00%) self.data.get(&id.local_id) 680,698 ( 0.00%) } . . pub fn iter(&self) -> hash_map::Iter<'_, hir::ItemLocalId, V> { . self.data.iter() . } . } . . impl<'a, V> ::std::ops::Index for LocalTableInContext<'a, V> { . type Output = V; . 4,746 ( 0.00%) fn index(&self, key: hir::HirId) -> &V { . self.get(key).expect("LocalTableInContext: key not found") 3,164 ( 0.00%) } . } . . pub struct LocalTableInContextMut<'a, V> { . hir_owner: LocalDefId, . data: &'a mut ItemLocalMap, . } . . impl<'a, V> LocalTableInContextMut<'a, V> { -- line 292 ---------------------------------------- -- line 507 ---------------------------------------- . pub treat_byte_string_as_slice: ItemLocalSet, . . /// Contains the data for evaluating the effect of feature `capture_disjoint_fields` . /// on closure size. . pub closure_size_eval: FxHashMap>, . } . . impl<'tcx> TypeckResults<'tcx> { 17,688 ( 0.00%) pub fn new(hir_owner: LocalDefId) -> TypeckResults<'tcx> { 209,308 ( 0.00%) TypeckResults { . hir_owner, . type_dependent_defs: Default::default(), . field_indices: Default::default(), . user_provided_types: Default::default(), . user_provided_sigs: Default::default(), . node_types: Default::default(), . node_substs: Default::default(), . adjustments: Default::default(), -- line 524 ---------------------------------------- -- line 532 ---------------------------------------- . tainted_by_errors: None, . concrete_opaque_types: Default::default(), . closure_min_captures: Default::default(), . closure_fake_reads: Default::default(), . generator_interior_types: ty::Binder::dummy(Default::default()), . treat_byte_string_as_slice: Default::default(), . closure_size_eval: Default::default(), . } 17,688 ( 0.00%) } . . /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node. 220,011 ( 0.00%) pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res { 146,674 ( 0.00%) match *qpath { 288,510 ( 0.00%) hir::QPath::Resolved(_, ref path) => path.res, . hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self . .type_dependent_def(id) 151,512 ( 0.00%) .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), . } 366,685 ( 0.00%) } . 1,674 ( 0.00%) pub fn type_dependent_defs( . &self, . ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorReported>> { 10,518 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.type_dependent_defs } 1,674 ( 0.00%) } . 28,939 ( 0.00%) pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> { 59,977 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.type_dependent_defs.get(&id.local_id).cloned().and_then(|r| r.ok()) 57,878 ( 0.00%) } . 23,144 ( 0.00%) pub fn type_dependent_def_id(&self, id: HirId) -> Option { . self.type_dependent_def(id).map(|(_, def_id)| def_id) 23,144 ( 0.00%) } . 69,806 ( 0.00%) pub fn type_dependent_defs_mut( . &mut self, . ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorReported>> { 69,806 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.type_dependent_defs } 69,806 ( 0.00%) } . . pub fn field_indices(&self) -> LocalTableInContext<'_, usize> { 25,636 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.field_indices } 4,787 ( 0.00%) } . . pub fn field_indices_mut(&mut self) -> LocalTableInContextMut<'_, usize> { 31,086 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.field_indices } 15,543 ( 0.00%) } . . pub fn user_provided_types(&self) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> { 38,014 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.user_provided_types } 19,007 ( 0.00%) } . . pub fn user_provided_types_mut( . &mut self, . ) -> LocalTableInContextMut<'_, CanonicalUserType<'tcx>> { 7,024 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.user_provided_types } 3,512 ( 0.00%) } . . pub fn node_types(&self) -> LocalTableInContext<'_, Ty<'tcx>> { 137,130 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.node_types } 68,565 ( 0.00%) } . . pub fn node_types_mut(&mut self) -> LocalTableInContextMut<'_, Ty<'tcx>> { 239,580 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_types } 119,790 ( 0.00%) } . 1,186,200 ( 0.01%) pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> { 197,700 ( 0.00%) self.node_type_opt(id).unwrap_or_else(|| { . bug!("node_type: no type for node `{}`", tls::with(|tcx| tcx.hir().node_to_string(id))) . }) 988,500 ( 0.01%) } . 247,435 ( 0.00%) pub fn node_type_opt(&self, id: hir::HirId) -> Option> { 247,435 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_types.get(&id.local_id).cloned() 494,870 ( 0.00%) } . . pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> { 27,066 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_substs } 13,533 ( 0.00%) } . 80,955 ( 0.00%) pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> { 80,955 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_substs.get(&id.local_id).cloned().unwrap_or_else(|| InternalSubsts::empty()) 161,910 ( 0.00%) } . 52,293 ( 0.00%) pub fn node_substs_opt(&self, id: hir::HirId) -> Option> { 52,293 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_substs.get(&id.local_id).cloned() 104,586 ( 0.00%) } . . // Returns the type of a pattern as a monotype. Like @expr_ty, this function . // doesn't provide type parameter substitutions. . pub fn pat_ty(&self, pat: &hir::Pat<'_>) -> Ty<'tcx> { 41,032 ( 0.00%) self.node_type(pat.hir_id) . } . . // Returns the type of an expression as a monotype. . // . // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in . // some cases, we insert `Adjustment` annotations such as auto-deref or . // auto-ref. The type returned by this function does not consider such . // adjustments. See `expr_ty_adjusted()` instead. . // . // NB (2): This type doesn't provide type parameter substitutions; e.g., if you . // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize" . // instead of "fn(ty) -> T with T = isize". . pub fn expr_ty(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> { 198,723 ( 0.00%) self.node_type(expr.hir_id) . } . . pub fn expr_ty_opt(&self, expr: &hir::Expr<'_>) -> Option> { 177,820 ( 0.00%) self.node_type_opt(expr.hir_id) . } . . pub fn adjustments(&self) -> LocalTableInContext<'_, Vec>> { 109,700 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.adjustments } 54,850 ( 0.00%) } . . pub fn adjustments_mut( . &mut self, . ) -> LocalTableInContextMut<'_, Vec>> { 149,542 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.adjustments } 74,771 ( 0.00%) } . 81,259 ( 0.00%) pub fn expr_adjustments(&self, expr: &hir::Expr<'_>) -> &[ty::adjustment::Adjustment<'tcx>] { 162,518 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, expr.hir_id); . self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..]) 162,518 ( 0.00%) } . . /// Returns the type of `expr`, considering any `Adjustment` . /// entry recorded for that expression. 13,135 ( 0.00%) pub fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> { 2,627 ( 0.00%) self.expr_adjustments(expr).last().map_or_else(|| self.expr_ty(expr), |adj| adj.target) 3,512 ( 0.00%) } . 1,180 ( 0.00%) pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr<'_>) -> Option> { 236 ( 0.00%) self.expr_adjustments(expr).last().map(|adj| adj.target).or_else(|| self.expr_ty_opt(expr)) 688 ( 0.00%) } . 8,844 ( 0.00%) pub fn is_method_call(&self, expr: &hir::Expr<'_>) -> bool { . // Only paths and method calls/overloaded operators have . // entries in type_dependent_defs, ignore the former here. 17,688 ( 0.00%) if let hir::ExprKind::Path(_) = expr.kind { . return false; . } . 18,620 ( 0.00%) matches!(self.type_dependent_defs().get(expr.hir_id), Some(Ok((DefKind::AssocFn, _)))) 17,688 ( 0.00%) } . 48,327 ( 0.00%) pub fn extract_binding_mode(&self, s: &Session, id: HirId, sp: Span) -> Option { . self.pat_binding_modes().get(id).copied().or_else(|| { . s.delay_span_bug(sp, "missing binding mode"); . None . }) 64,436 ( 0.00%) } . . pub fn pat_binding_modes(&self) -> LocalTableInContext<'_, BindingMode> { 44,503 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_binding_modes } 14,197 ( 0.00%) } . . pub fn pat_binding_modes_mut(&mut self) -> LocalTableInContextMut<'_, BindingMode> { 21,344 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_binding_modes } 10,672 ( 0.00%) } . . pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec>> { 91,060 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_adjustments } 45,530 ( 0.00%) } . . pub fn pat_adjustments_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { 27,526 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_adjustments } 13,763 ( 0.00%) } . . /// For a given closure, returns the iterator of `ty::CapturedPlace`s that are captured . /// by the closure. 4,196 ( 0.00%) pub fn closure_min_captures_flattened( . &self, . closure_def_id: DefId, . ) -> impl Iterator> { . self.closure_min_captures . .get(&closure_def_id) . .map(|closure_min_captures| closure_min_captures.values().flat_map(|v| v.iter())) . .into_iter() . .flatten() 5,245 ( 0.00%) } . . pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, HirPlace<'tcx>)> { 1,560 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.closure_kind_origins } 780 ( 0.00%) } . . pub fn closure_kind_origins_mut( . &mut self, . ) -> LocalTableInContextMut<'_, (Span, HirPlace<'tcx>)> { . LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.closure_kind_origins } . } . . pub fn liberated_fn_sigs(&self) -> LocalTableInContext<'_, ty::FnSig<'tcx>> { 4,724 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.liberated_fn_sigs } 2,362 ( 0.00%) } . . pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<'_, ty::FnSig<'tcx>> { 3,164 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.liberated_fn_sigs } 1,582 ( 0.00%) } . . pub fn fru_field_types(&self) -> LocalTableInContext<'_, Vec>> { 1,560 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.fru_field_types } 780 ( 0.00%) } . . pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { . LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.fru_field_types } . } . 297 ( 0.00%) pub fn is_coercion_cast(&self, hir_id: hir::HirId) -> bool { 99 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, hir_id); . self.coercion_casts.contains(&hir_id.local_id) 198 ( 0.00%) } . . pub fn set_coercion_cast(&mut self, id: ItemLocalId) { . self.coercion_casts.insert(id); . } . . pub fn coercion_casts(&self) -> &ItemLocalSet { 780 ( 0.00%) &self.coercion_casts 780 ( 0.00%) } . } . . impl<'a, 'tcx> HashStable> for TypeckResults<'tcx> { . fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { . let ty::TypeckResults { . hir_owner, . ref type_dependent_defs, . ref field_indices, -- line 764 ---------------------------------------- -- line 819 ---------------------------------------- . const START_INDEX = 0, . } . } . . /// Mapping of type annotation indices to canonical user type annotations. . pub type CanonicalUserTypeAnnotations<'tcx> = . IndexVec>; . 3,572 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)] . pub struct CanonicalUserTypeAnnotation<'tcx> { . pub user_ty: CanonicalUserType<'tcx>, . pub span: Span, 1,882 ( 0.00%) pub inferred_ty: Ty<'tcx>, . } . . /// Canonicalized user type annotation. . pub type CanonicalUserType<'tcx> = Canonical<'tcx, UserType<'tcx>>; . . impl<'tcx> CanonicalUserType<'tcx> { . /// Returns `true` if this represents a substitution of the form `[?0, ?1, ?2]`, . /// i.e., each thing is mapped to a canonical variable with the same index. 8,466 ( 0.00%) pub fn is_identity(&self) -> bool { 16,932 ( 0.00%) match self.value { . UserType::Ty(_) => false, . UserType::TypeOf(_, user_substs) => { 8,466 ( 0.00%) if user_substs.user_self_ty.is_some() { . return false; . } . . iter::zip(user_substs.substs, BoundVar::new(0)..).all(|(kind, cvar)| { . match kind.unpack() { 13,482 ( 0.00%) GenericArgKind::Type(ty) => match ty.kind() { . ty::Bound(debruijn, b) => { . // We only allow a `ty::INNERMOST` index in substitutions. 6,727 ( 0.00%) assert_eq!(*debruijn, ty::INNERMOST); . cvar == b.var . } . _ => false, . }, . 6,022 ( 0.00%) GenericArgKind::Lifetime(r) => match r { . ty::ReLateBound(debruijn, br) => { . // We only allow a `ty::INNERMOST` index in substitutions. . assert_eq!(*debruijn, ty::INNERMOST); . cvar == br.var . } . _ => false, . }, . -- line 867 ---------------------------------------- -- line 872 ---------------------------------------- . cvar == b . } . _ => false, . }, . } . }) . } . } 16,932 ( 0.00%) } . } . . /// A user-given type annotation attached to a constant. These arise . /// from constants that are named via paths, like `Foo::::new` and . /// so forth. 11,292 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, TyEncodable, TyDecodable)] 96,808 ( 0.00%) #[derive(HashStable, TypeFoldable, Lift)] . pub enum UserType<'tcx> { . Ty(Ty<'tcx>), . . /// The canonical type is the result of `type_of(def_id)` with the . /// given substitutions applied. . TypeOf(DefId, UserSubsts<'tcx>), . } . . impl<'tcx> CommonTypes<'tcx> { . fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> { 111 ( 0.00%) let mk = |ty| interners.intern_ty(ty); . . CommonTypes { . unit: mk(Tuple(List::empty())), . bool: mk(Bool), . char: mk(Char), . never: mk(Never), . isize: mk(Int(ty::IntTy::Isize)), . i8: mk(Int(ty::IntTy::I8)), -- line 906 ---------------------------------------- -- line 921 ---------------------------------------- . . trait_object_dummy_self: mk(Infer(ty::FreshTy(0))), . } . } . } . . impl<'tcx> CommonLifetimes<'tcx> { . fn new(interners: &CtxtInterners<'tcx>) -> CommonLifetimes<'tcx> { 67 ( 0.00%) let mk = |r| interners.region.intern(r, |r| Interned(interners.arena.alloc(r))).0; . . CommonLifetimes { 5 ( 0.00%) re_root_empty: mk(RegionKind::ReEmpty(ty::UniverseIndex::ROOT)), 5 ( 0.00%) re_static: mk(RegionKind::ReStatic), 5 ( 0.00%) re_erased: mk(RegionKind::ReErased), . } . } . } . . impl<'tcx> CommonConsts<'tcx> { . fn new(interners: &CtxtInterners<'tcx>, types: &CommonTypes<'tcx>) -> CommonConsts<'tcx> { 6 ( 0.00%) let mk_const = |c| interners.const_.intern(c, |c| Interned(interners.arena.alloc(c))).0; . . CommonConsts { . unit: mk_const(ty::Const { . val: ty::ConstKind::Value(ConstValue::Scalar(Scalar::ZST)), . ty: types.unit, . }), . } . } -- line 949 ---------------------------------------- -- line 1045 ---------------------------------------- . . /// Stores memory for globals (statics/consts). . pub(crate) alloc_map: Lock>, . . output_filenames: Arc, . } . . impl<'tcx> TyCtxt<'tcx> { 36,340 ( 0.00%) pub fn typeck_opt_const_arg( . self, . def: ty::WithOptConstParam, . ) -> &'tcx TypeckResults<'tcx> { 14,536 ( 0.00%) if let Some(param_did) = def.const_param_did { . self.typeck_const_arg((def.did, param_did)) . } else { . self.typeck(def.did) . } 29,072 ( 0.00%) } . 2,475 ( 0.00%) pub fn alloc_steal_thir(self, thir: Thir<'tcx>) -> &'tcx Steal> { 825 ( 0.00%) self.arena.alloc(Steal::new(thir)) 3,300 ( 0.00%) } . 16,500 ( 0.00%) pub fn alloc_steal_mir(self, mir: Body<'tcx>) -> &'tcx Steal> { 3,300 ( 0.00%) self.arena.alloc(Steal::new(mir)) 23,100 ( 0.00%) } . 3,300 ( 0.00%) pub fn alloc_steal_promoted( . self, . promoted: IndexVec>, . ) -> &'tcx Steal>> { 825 ( 0.00%) self.arena.alloc(Steal::new(promoted)) 4,125 ( 0.00%) } . 2,007 ( 0.00%) pub fn alloc_adt_def( . self, . did: DefId, . kind: AdtKind, . variants: IndexVec, . repr: ReprOptions, . ) -> &'tcx ty::AdtDef { 3,568 ( 0.00%) self.intern_adt_def(ty::AdtDef::new(self, did, kind, variants, repr)) 892 ( 0.00%) } . . /// Allocates a read-only byte or string literal for `mir::interpret`. 5 ( 0.00%) pub fn allocate_bytes(self, bytes: &[u8]) -> interpret::AllocId { . // Create an allocation that just contains these bytes. 1 ( 0.00%) let alloc = interpret::Allocation::from_bytes_byte_aligned_immutable(bytes); 13 ( 0.00%) let alloc = self.intern_const_alloc(alloc); . self.create_memory_alloc(alloc) 5 ( 0.00%) } . . /// Returns a range of the start/end indices specified with the . /// `rustc_layout_scalar_valid_range` attribute. . // FIXME(eddyb) this is an awkward spot for this method, maybe move it? 37,392 ( 0.00%) pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound, Bound) { 18,696 ( 0.00%) let attrs = self.get_attrs(def_id); 79,458 ( 0.00%) let get = |name| { 18,696 ( 0.00%) let attr = match attrs.iter().find(|a| a.has_name(name)) { . Some(attr) => attr, . None => return Bound::Unbounded, . }; . debug!("layout_scalar_valid_range: attr={:?}", attr); 616 ( 0.00%) if let Some( . &[ . ast::NestedMetaItem::Literal(ast::Lit { 308 ( 0.00%) kind: ast::LitKind::Int(a, _), .. . }), . ], 154 ( 0.00%) ) = attr.meta_item_list().as_deref() . { . Bound::Included(a) . } else { . self.sess . .delay_span_bug(attr.span, "invalid rustc_layout_scalar_valid_range attribute"); . Bound::Unbounded . } 93,480 ( 0.00%) }; 28,044 ( 0.00%) ( 28,044 ( 0.00%) get(sym::rustc_layout_scalar_valid_range_start), 14,022 ( 0.00%) get(sym::rustc_layout_scalar_valid_range_end), . ) 37,392 ( 0.00%) } . . pub fn lift>(self, value: T) -> Option { . value.lift_to_tcx(self) . } . . /// Creates a type context and call the closure with a `TyCtxt` reference . /// to the context. The closure enforces that the type context and any interned . /// value (types, substs, etc.) can only be used while `ty::tls` has a valid . /// reference to the context, to allow formatting values that need it. 23 ( 0.00%) pub fn create_global_ctxt( . s: &'tcx Session, . lint_store: Lrc, . arena: &'tcx WorkerLocal>, . resolutions: ty::ResolverOutputs, . krate: &'tcx hir::Crate<'tcx>, . dep_graph: DepGraph, . on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>, . queries: &'tcx dyn query::QueryEngine<'tcx>, . query_kinds: &'tcx [DepKindStruct], . crate_name: &str, . output_filenames: OutputFilenames, . ) -> GlobalCtxt<'tcx> { 1 ( 0.00%) let data_layout = TargetDataLayout::parse(&s.target).unwrap_or_else(|err| { . s.fatal(&err); . }); . let interners = CtxtInterners::new(arena); . let common_types = CommonTypes::new(&interners); . let common_lifetimes = CommonLifetimes::new(&interners); . let common_consts = CommonConsts::new(&interners, &common_types); . 127 ( 0.00%) GlobalCtxt { . sess: s, 6 ( 0.00%) lint_store, . arena, 2 ( 0.00%) interners, 5 ( 0.00%) dep_graph, 4 ( 0.00%) untracked_resolutions: resolutions, 2 ( 0.00%) prof: s.prof.clone(), . types: common_types, . lifetimes: common_lifetimes, . consts: common_consts, . untracked_crate: krate, . on_disk_cache, . queries, . query_caches: query::QueryCaches::default(), . query_kinds, . ty_rcache: Default::default(), . pred_rcache: Default::default(), . selection_cache: Default::default(), . evaluation_cache: Default::default(), 1 ( 0.00%) crate_name: Symbol::intern(crate_name), . data_layout, . alloc_map: Lock::new(interpret::AllocMap::new()), . output_filenames: Arc::new(output_filenames), . } 9 ( 0.00%) } . . crate fn query_kind(self, k: DepKind) -> &'tcx DepKindStruct { . &self.query_kinds[k as usize] . } . . /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used. . #[track_caller] . pub fn ty_error(self) -> Ty<'tcx> { -- line 1191 ---------------------------------------- -- line 1217 ---------------------------------------- . ty: Ty<'tcx>, . span: S, . msg: &str, . ) -> &'tcx Const<'tcx> { . self.sess.delay_span_bug(span, msg); . self.mk_const(ty::Const { val: ty::ConstKind::Error(DelaySpanBugEmitted(())), ty }) . } . 56,483 ( 0.00%) pub fn consider_optimizing String>(self, msg: T) -> bool { 8,069 ( 0.00%) let cname = self.crate_name(LOCAL_CRATE); 61,287 ( 0.00%) self.sess.consider_optimizing(cname.as_str(), msg) 64,552 ( 0.00%) } . . /// Obtain all lang items of this crate and all dependencies (recursively) 2,113,181 ( 0.01%) pub fn lang_items(self) -> &'tcx rustc_hir::lang_items::LanguageItems { . self.get_lang_items(()) 2,716,947 ( 0.02%) } . . /// Obtain the given diagnostic item's `DefId`. Use `is_diagnostic_item` if you just want to . /// compare against another `DefId`, since `is_diagnostic_item` is cheaper. 651 ( 0.00%) pub fn get_diagnostic_item(self, name: Symbol) -> Option { . self.all_diagnostic_items(()).name_to_id.get(&name).copied() 744 ( 0.00%) } . . /// Obtain the diagnostic item's name 110,243 ( 0.00%) pub fn get_diagnostic_name(self, id: DefId) -> Option { . self.diagnostic_items(id.krate).id_to_name.get(&id).copied() 125,992 ( 0.00%) } . . /// Check whether the diagnostic item with the given `name` has the given `DefId`. 74,858 ( 0.00%) pub fn is_diagnostic_item(self, name: Symbol, did: DefId) -> bool { . self.diagnostic_items(did.krate).name_to_id.get(&name) == Some(&did) 85,552 ( 0.00%) } . 22,561 ( 0.00%) pub fn stability(self) -> &'tcx stability::Index<'tcx> { . self.stability_index(()) 29,007 ( 0.00%) } . 942,886 ( 0.01%) pub fn features(self) -> &'tcx rustc_feature::Features { . self.features_query(()) 1,077,584 ( 0.01%) } . 91,211 ( 0.00%) pub fn def_key(self, id: DefId) -> rustc_hir::definitions::DefKey { . // Accessing the DefKey is ok, since it is part of DefPathHash. 779,977 ( 0.00%) if let Some(id) = id.as_local() { . self.untracked_resolutions.definitions.def_key(id) . } else { 689,832 ( 0.00%) self.untracked_resolutions.cstore.def_key(id) . } 65,632 ( 0.00%) } . . /// Converts a `DefId` into its fully expanded `DefPath` (every . /// `DefId` is really just an interned `DefPath`). . /// . /// Note that if `id` is not local to this crate, the result will . /// be a non-local `DefPath`. 238 ( 0.00%) pub fn def_path(self, id: DefId) -> rustc_hir::definitions::DefPath { . // Accessing the DefPath is ok, since it is part of DefPathHash. 357 ( 0.00%) if let Some(id) = id.as_local() { 87 ( 0.00%) self.untracked_resolutions.definitions.def_path(id) . } else { 450 ( 0.00%) self.untracked_resolutions.cstore.def_path(id) . } 357 ( 0.00%) } . . #[inline] . pub fn def_path_hash(self, def_id: DefId) -> rustc_hir::definitions::DefPathHash { . // Accessing the DefPathHash is ok, it is incr. comp. stable. 16,251 ( 0.00%) if let Some(def_id) = def_id.as_local() { . self.untracked_resolutions.definitions.def_path_hash(def_id) . } else { 11,699 ( 0.00%) self.untracked_resolutions.cstore.def_path_hash(def_id) . } . } . . #[inline] . pub fn stable_crate_id(self, crate_num: CrateNum) -> StableCrateId { . if crate_num == LOCAL_CRATE { . self.sess.local_stable_crate_id() . } else { -- line 1296 ---------------------------------------- -- line 1353 ---------------------------------------- . &(format!("{:08x}", stable_crate_id.to_u64()))[..4], . self.def_path(def_id).to_string_no_crate_verbose() . ) . } . . /// Note that this is *untracked* and should only be used within the query . /// system if the result is otherwise tracked through queries . pub fn cstore_untracked(self) -> &'tcx ty::CrateStoreDyn { 93,398 ( 0.00%) &*self.untracked_resolutions.cstore 46,699 ( 0.00%) } . . /// Note that this is *untracked* and should only be used within the query . /// system if the result is otherwise tracked through queries . pub fn definitions_untracked(self) -> &'tcx hir::definitions::Definitions { . &self.untracked_resolutions.definitions . } . . #[inline(always)] . pub fn create_stable_hashing_context(self) -> StableHashingContext<'tcx> { 9,993 ( 0.00%) let resolutions = &self.gcx.untracked_resolutions; 40,006 ( 0.00%) StableHashingContext::new(self.sess, &resolutions.definitions, &*resolutions.cstore) . } . . #[inline(always)] . pub fn create_no_span_stable_hashing_context(self) -> StableHashingContext<'tcx> { . let resolutions = &self.gcx.untracked_resolutions; . StableHashingContext::ignore_spans( . self.sess, . &resolutions.definitions, -- line 1381 ---------------------------------------- -- line 1390 ---------------------------------------- . /// If `true`, we should use the MIR-based borrowck, but also . /// fall back on the AST borrowck if the MIR-based one errors. . pub fn migrate_borrowck(self) -> bool { . self.borrowck_mode().migrate() . } . . /// What mode(s) of borrowck should we run? AST? MIR? both? . /// (Also considers the `#![feature(nll)]` setting.) 1,560 ( 0.00%) pub fn borrowck_mode(self) -> BorrowckMode { . // Here are the main constraints we need to deal with: . // . // 1. An opts.borrowck_mode of `BorrowckMode::Migrate` is . // synonymous with no `-Z borrowck=...` flag at all. . // . // 2. We want to allow developers on the Nightly channel . // to opt back into the "hard error" mode for NLL, . // (which they can do via specifying `#![feature(nll)]` -- line 1406 ---------------------------------------- -- line 1413 ---------------------------------------- . // errors. (To simplify the code here, it now even overrides . // a user's attempt to specify `-Z borrowck=compare`, which . // we arguably do not need anymore and should remove.) . // . // * Otherwise, if no `-Z borrowck=...` then use migrate mode . // . // * Otherwise, use the behavior requested via `-Z borrowck=...` . 2,340 ( 0.00%) if self.features().nll { . return BorrowckMode::Mir; . } . 780 ( 0.00%) self.sess.opts.borrowck_mode 3,120 ( 0.00%) } . . /// If `true`, we should use lazy normalization for constants, otherwise . /// we still evaluate them eagerly. . #[inline] . pub fn lazy_normalization(self) -> bool { 112 ( 0.00%) let features = self.features(); . // Note: We only use lazy normalization for generic const expressions. 30 ( 0.00%) features.generic_const_exprs . } . . #[inline] . pub fn local_crate_exports_generics(self) -> bool { . debug_assert!(self.sess.opts.share_generics()); . 5,771 ( 0.00%) self.sess.crate_types().iter().any(|crate_type| { 9,623 ( 0.00%) match crate_type { . CrateType::Executable . | CrateType::Staticlib . | CrateType::ProcMacro . | CrateType::Cdylib => false, . . // FIXME rust-lang/rust#64319, rust-lang/rust#64872: . // We want to block export of generics from dylibs, . // but we must fix rust-lang/rust#65890 before we can -- line 1450 ---------------------------------------- -- line 1540 ---------------------------------------- . // FIXME(#42706) -- in some cases, we could do better here. . return true; . } . false . } . . /// Determines whether identifiers in the assembly have strict naming rules. . /// Currently, only NVPTX* targets need it. 13,426 ( 0.00%) pub fn has_strict_asm_symbol_naming(self) -> bool { 13,426 ( 0.00%) self.sess.target.arch.contains("nvptx") 26,852 ( 0.00%) } . . /// Returns `&'static core::panic::Location<'static>`. 14,790 ( 0.00%) pub fn caller_location_ty(self) -> Ty<'tcx> { . self.mk_imm_ref( 2,465 ( 0.00%) self.lifetimes.re_static, . self.type_of(self.require_lang_item(LangItem::PanicLocation, None)) 4,930 ( 0.00%) .subst(self, self.mk_substs([self.lifetimes.re_static.into()].iter())), . ) 14,790 ( 0.00%) } . . /// Returns a displayable description and article for the given `def_id` (e.g. `("a", "struct")`). 6,017 ( 0.00%) pub fn article_and_description(self, def_id: DefId) -> (&'static str, &'static str) { 4,376 ( 0.00%) match self.def_kind(def_id) { . DefKind::Generator => match self.generator_kind(def_id).unwrap() { . rustc_hir::GeneratorKind::Async(..) => ("an", "async closure"), . rustc_hir::GeneratorKind::Gen => ("a", "generator"), . }, 9,846 ( 0.00%) def_kind => (def_kind.article(), def_kind.descr(def_id)), . } 4,923 ( 0.00%) } . 98,259 ( 0.00%) pub fn type_length_limit(self) -> Limit { . self.limits(()).type_length_limit 112,296 ( 0.00%) } . 731,430 ( 0.00%) pub fn recursion_limit(self) -> Limit { . self.limits(()).recursion_limit 835,920 ( 0.00%) } . 440,223 ( 0.00%) pub fn move_size_limit(self) -> Limit { . self.limits(()).move_size_limit 503,112 ( 0.00%) } . 14,189 ( 0.00%) pub fn const_eval_limit(self) -> Limit { . self.limits(()).const_eval_limit 16,216 ( 0.00%) } . . pub fn all_traits(self) -> impl Iterator + 'tcx { . iter::once(LOCAL_CRATE) . .chain(self.crates(()).iter().copied()) . .flat_map(move |cnum| self.traits_in_crate(cnum).iter().copied()) . } . } . -- line 1594 ---------------------------------------- -- line 1614 ---------------------------------------- . fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option; . } . . macro_rules! nop_lift { . ($set:ident; $ty:ty => $lifted:ty) => { . impl<'a, 'tcx> Lift<'tcx> for $ty { . type Lifted = $lifted; . fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option { 13,916 ( 0.00%) if tcx.interners.$set.contains_pointer_to(&Interned(self)) { . Some(unsafe { mem::transmute(self) }) . } else { . None . } . } . } . }; . } -- line 1630 ---------------------------------------- -- line 1684 ---------------------------------------- . /// This is the implicit state of rustc. It contains the current . /// `TyCtxt` and query. It is updated when creating a local interner or . /// executing a new query. Whenever there's a `TyCtxt` value available . /// you should also have access to an `ImplicitCtxt` through the functions . /// in this module. . #[derive(Clone)] . pub struct ImplicitCtxt<'a, 'tcx> { . /// The current `TyCtxt`. 2 ( 0.00%) pub tcx: TyCtxt<'tcx>, . . /// The current query job, if any. This is updated by `JobOwner::start` in . /// `ty::query::plumbing` when executing a query. . pub query: Option>, . . /// Where to store diagnostics for the current query job, if any. . /// This is updated by `JobOwner::start` in `ty::query::plumbing` when executing a query. . pub diagnostics: Option<&'a Lock>>, -- line 1700 ---------------------------------------- -- line 1703 ---------------------------------------- . pub layout_depth: usize, . . /// The current dep graph task. This is used to add dependencies to queries . /// when executing them. . pub task_deps: TaskDepsRef<'a>, . } . . impl<'a, 'tcx> ImplicitCtxt<'a, 'tcx> { 5 ( 0.00%) pub fn new(gcx: &'tcx GlobalCtxt<'tcx>) -> Self { . let tcx = TyCtxt { gcx }; 25 ( 0.00%) ImplicitCtxt { . tcx, . query: None, . diagnostics: None, . layout_depth: 0, . task_deps: TaskDepsRef::Ignore, . } 5 ( 0.00%) } . } . . /// Sets Rayon's thread-local variable, which is preserved for Rayon jobs . /// to `value` during the call to `f`. It is restored to its previous value after. . /// This is used to set the pointer to the new `ImplicitCtxt`. . #[cfg(parallel_compiler)] . #[inline] . fn set_tlv R, R>(value: usize, f: F) -> R { -- line 1728 ---------------------------------------- -- line 1745 ---------------------------------------- . . /// Sets TLV to `value` during the call to `f`. . /// It is restored to its previous value after. . /// This is used to set the pointer to the new `ImplicitCtxt`. . #[cfg(not(parallel_compiler))] . #[inline] . fn set_tlv R, R>(value: usize, f: F) -> R { . let old = get_tlv(); 206,628 ( 0.00%) let _reset = rustc_data_structures::OnDrop(move || TLV.with(|tlv| tlv.set(old))); . TLV.with(|tlv| tlv.set(value)); . f() . } . . /// Gets the pointer to the current `ImplicitCtxt`. . #[cfg(not(parallel_compiler))] . #[inline] . fn get_tlv() -> usize { -- line 1761 ---------------------------------------- -- line 1763 ---------------------------------------- . } . . /// Sets `context` as the new current `ImplicitCtxt` for the duration of the function `f`. . #[inline] . pub fn enter_context<'a, 'tcx, F, R>(context: &ImplicitCtxt<'a, 'tcx>, f: F) -> R . where . F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R, . { 1 ( 0.00%) set_tlv(context as *const _ as usize, || f(&context)) . } . . /// Allows access to the current `ImplicitCtxt` in a closure if one is available. . #[inline] . pub fn with_context_opt(f: F) -> R . where . F: for<'a, 'tcx> FnOnce(Option<&ImplicitCtxt<'a, 'tcx>>) -> R, . { . let context = get_tlv(); 863,511 ( 0.00%) if context == 0 { . f(None) . } else { . // We could get an `ImplicitCtxt` pointer from another thread. . // Ensure that `ImplicitCtxt` is `Sync`. . sync::assert_sync::>(); . . unsafe { f(Some(&*(context as *const ImplicitCtxt<'_, '_>))) } . } -- line 1789 ---------------------------------------- -- line 1791 ---------------------------------------- . . /// Allows access to the current `ImplicitCtxt`. . /// Panics if there is no `ImplicitCtxt` available. . #[inline] . pub fn with_context(f: F) -> R . where . F: for<'a, 'tcx> FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R, . { 6,630 ( 0.00%) with_context_opt(|opt_context| f(opt_context.expect("no ImplicitCtxt stored in tls"))) . } . . /// Allows access to the current `ImplicitCtxt` whose tcx field is the same as the tcx argument . /// passed in. This means the closure is given an `ImplicitCtxt` with the same `'tcx` lifetime . /// as the `TyCtxt` passed in. . /// This will panic if you pass it a `TyCtxt` which is different from the current . /// `ImplicitCtxt`'s `tcx` field. . #[inline] . pub fn with_related_context<'tcx, F, R>(tcx: TyCtxt<'tcx>, f: F) -> R . where . F: FnOnce(&ImplicitCtxt<'_, 'tcx>) -> R, . { . with_context(|context| unsafe { 402,979 ( 0.00%) assert!(ptr_eq(context.tcx.gcx, tcx.gcx)); . let context: &ImplicitCtxt<'_, '_> = mem::transmute(context); 396,220 ( 0.00%) f(context) . }) . } . . /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`. . /// Panics if there is no `ImplicitCtxt` available. . #[inline] . pub fn with(f: F) -> R . where -- line 1823 ---------------------------------------- -- line 1981 ---------------------------------------- . fn into_pointer(&self) -> *const () { . self.0 as *const _ as *const () . } . } . . #[allow(rustc::usage_of_ty_tykind)] . impl<'tcx> Borrow> for Interned<'tcx, TyS<'tcx>> { . fn borrow<'a>(&'a self) -> &'a TyKind<'tcx> { 903,973 ( 0.01%) &self.0.kind() . } . } . . impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> { . fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0.kind() == other.0.kind() -- line 1997 ---------------------------------------- -- line 1998 ---------------------------------------- . } . } . . impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {} . . impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 702,032 ( 0.00%) self.0.kind().hash(s) . } . } . . impl<'tcx> Borrow>> for Interned<'tcx, PredicateInner<'tcx>> { . fn borrow<'a>(&'a self) -> &'a Binder<'tcx, PredicateKind<'tcx>> { 193,696 ( 0.00%) &self.0.kind . } . } . . impl<'tcx> PartialEq for Interned<'tcx, PredicateInner<'tcx>> { . fn eq(&self, other: &Interned<'tcx, PredicateInner<'tcx>>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0.kind == other.0.kind -- line 2020 ---------------------------------------- -- line 2021 ---------------------------------------- . } . } . . impl<'tcx> Eq for Interned<'tcx, PredicateInner<'tcx>> {} . . impl<'tcx> Hash for Interned<'tcx, PredicateInner<'tcx>> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 114,684 ( 0.00%) self.0.kind.hash(s) . } . } . . impl<'tcx, T> Borrow<[T]> for Interned<'tcx, List> { . fn borrow<'a>(&'a self) -> &'a [T] { 926,979 ( 0.01%) &self.0[..] . } . } . . impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, List> { . fn eq(&self, other: &Interned<'tcx, List>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0[..] == other.0[..] -- line 2043 ---------------------------------------- -- line 2044 ---------------------------------------- . } . } . . impl<'tcx, T: Eq> Eq for Interned<'tcx, List> {} . . impl<'tcx, T: Hash> Hash for Interned<'tcx, List> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 176,582 ( 0.00%) self.0[..].hash(s) . } . } . . macro_rules! direct_interners { . ($($name:ident: $method:ident($ty:ty),)+) => { . $(impl<'tcx> Borrow<$ty> for Interned<'tcx, $ty> { . fn borrow<'a>(&'a self) -> &'a $ty { 269,045 ( 0.00%) &self.0 . } . } . . impl<'tcx> PartialEq for Interned<'tcx, $ty> { . fn eq(&self, other: &Self) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` . // equals `x == y`. . self.0 == other.0 -- line 2068 ---------------------------------------- -- line 2070 ---------------------------------------- . } . . impl<'tcx> Eq for Interned<'tcx, $ty> {} . . impl<'tcx> Hash for Interned<'tcx, $ty> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == . // x.hash(s)`. 141,539 ( 0.00%) self.0.hash(s) . } . } . . impl<'tcx> TyCtxt<'tcx> { 2,411,674 ( 0.01%) pub fn $method(self, v: $ty) -> &'tcx $ty { 1,266,612 ( 0.01%) self.interners.$name.intern(v, |v| { 35,777 ( 0.00%) Interned(self.interners.arena.alloc(v)) . }).0 2,696,112 ( 0.02%) } . })+ . } . } . . direct_interners! { . region: mk_region(RegionKind), . const_: mk_const(Const<'tcx>), . const_allocation: intern_const_alloc(Allocation), -- line 2095 ---------------------------------------- -- line 2097 ---------------------------------------- . adt_def: intern_adt_def(AdtDef), . stability: intern_stability(attr::Stability), . const_stability: intern_const_stability(attr::ConstStability), . } . . macro_rules! slice_interners { . ($($field:ident: $method:ident($ty:ty)),+ $(,)?) => ( . impl<'tcx> TyCtxt<'tcx> { 10,384,773 ( 0.06%) $(pub fn $method(self, v: &[$ty]) -> &'tcx List<$ty> { . self.interners.$field.intern_ref(v, || { . Interned(List::from_arena(&*self.arena, v)) . }).0 9,275,805 ( 0.05%) })+ . } . ); . } . . slice_interners!( . type_list: _intern_type_list(Ty<'tcx>), . substs: _intern_substs(GenericArg<'tcx>), . canonical_var_infos: _intern_canonical_var_infos(CanonicalVarInfo<'tcx>), -- line 2117 ---------------------------------------- -- line 2129 ---------------------------------------- . /// unsafe. . pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> { . assert_eq!(sig.unsafety(), hir::Unsafety::Normal); . self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig { unsafety: hir::Unsafety::Unsafe, ..sig })) . } . . /// Given the def_id of a Trait `trait_def_id` and the name of an associated item `assoc_name` . /// returns true if the `trait_def_id` defines an associated item of name `assoc_name`. 228 ( 0.00%) pub fn trait_may_define_assoc_type(self, trait_def_id: DefId, assoc_name: Ident) -> bool { . self.super_traits_of(trait_def_id).any(|trait_did| { . self.associated_items(trait_did) . .find_by_name_and_kind(self, assoc_name, ty::AssocKind::Type, trait_did) . .is_some() . }) 171 ( 0.00%) } . . /// Computes the def-ids of the transitive supertraits of `trait_def_id`. This (intentionally) . /// does not compute the full elaborated super-predicates but just the set of def-ids. It is used . /// to identify which traits may define a given associated type to help avoid cycle errors. . /// Returns a `DefId` iterator. . fn super_traits_of(self, trait_def_id: DefId) -> impl Iterator + 'tcx { . let mut set = FxHashSet::default(); 38 ( 0.00%) let mut stack = vec![trait_def_id]; . . set.insert(trait_def_id); . 171 ( 0.00%) iter::from_fn(move || -> Option { 52 ( 0.00%) let trait_did = stack.pop()?; 26 ( 0.00%) let generic_predicates = self.super_predicates_of(trait_did); . . for (predicate, _) in generic_predicates.predicates { 21 ( 0.00%) if let ty::PredicateKind::Trait(data) = predicate.kind().skip_binder() { 14 ( 0.00%) if set.insert(data.def_id()) { . stack.push(data.def_id()); . } . } . } . . Some(trait_did) . }) . } -- line 2169 ---------------------------------------- -- line 2188 ---------------------------------------- . self.mk_fn_sig(params_iter, s.output(), s.c_variadic, unsafety, abi::Abi::Rust) . }) . } . . /// Same a `self.mk_region(kind)`, but avoids accessing the interners if . /// `*r == kind`. . #[inline] . pub fn reuse_or_mk_region(self, r: Region<'tcx>, kind: RegionKind) -> Region<'tcx> { 254,708 ( 0.00%) if *r == kind { r } else { self.mk_region(kind) } . } . . #[allow(rustc::usage_of_ty_tykind)] . #[inline] . pub fn mk_ty(self, st: TyKind<'tcx>) -> Ty<'tcx> { 7,141,694 ( 0.04%) self.interners.intern_ty(st) . } . . #[inline] . pub fn mk_predicate(self, binder: Binder<'tcx, PredicateKind<'tcx>>) -> Predicate<'tcx> { 3,021,654 ( 0.02%) let inner = self.interners.intern_predicate(binder); . Predicate { inner } . } . . #[inline] 2,679,144 ( 0.02%) pub fn reuse_or_mk_predicate( . self, . pred: Predicate<'tcx>, . binder: Binder<'tcx, PredicateKind<'tcx>>, . ) -> Predicate<'tcx> { 184,566 ( 0.00%) if pred.kind() != binder { self.mk_predicate(binder) } else { pred } 2,679,144 ( 0.02%) } . . pub fn mk_mach_int(self, tm: IntTy) -> Ty<'tcx> { 1,180 ( 0.00%) match tm { . IntTy::Isize => self.types.isize, . IntTy::I8 => self.types.i8, . IntTy::I16 => self.types.i16, . IntTy::I32 => self.types.i32, . IntTy::I64 => self.types.i64, . IntTy::I128 => self.types.i128, . } 1,180 ( 0.00%) } . . pub fn mk_mach_uint(self, tm: UintTy) -> Ty<'tcx> { 3,308 ( 0.00%) match tm { . UintTy::Usize => self.types.usize, . UintTy::U8 => self.types.u8, . UintTy::U16 => self.types.u16, . UintTy::U32 => self.types.u32, . UintTy::U64 => self.types.u64, . UintTy::U128 => self.types.u128, . } 3,308 ( 0.00%) } . . pub fn mk_mach_float(self, tm: FloatTy) -> Ty<'tcx> { . match tm { . FloatTy::F32 => self.types.f32, . FloatTy::F64 => self.types.f64, . } . } . . #[inline] . pub fn mk_static_str(self) -> Ty<'tcx> { 2,674 ( 0.00%) self.mk_imm_ref(self.lifetimes.re_static, self.types.str_) . } . . #[inline] . pub fn mk_adt(self, def: &'tcx AdtDef, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . // Take a copy of substs so that we own the vectors inside. . self.mk_ty(Adt(def, substs)) . } . . #[inline] . pub fn mk_foreign(self, def_id: DefId) -> Ty<'tcx> { . self.mk_ty(Foreign(def_id)) . } . 120 ( 0.00%) fn mk_generic_adt(self, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> { . let adt_def = self.adt_def(wrapper_def_id); . let substs = 225 ( 0.00%) InternalSubsts::for_item(self, wrapper_def_id, |param, substs| match param.kind { . GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => bug!(), 15 ( 0.00%) GenericParamDefKind::Type { has_default, .. } => { 60 ( 0.00%) if param.index == 0 { . ty_param.into() . } else { 15 ( 0.00%) assert!(has_default); 45 ( 0.00%) self.type_of(param.def_id).subst(self, substs).into() . } . } . }); 15 ( 0.00%) self.mk_ty(Adt(adt_def, substs)) 120 ( 0.00%) } . . #[inline] . pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> { 75 ( 0.00%) let def_id = self.require_lang_item(LangItem::OwnedBox, None); 116 ( 0.00%) self.mk_generic_adt(def_id, ty) . } . . #[inline] . pub fn mk_lang_item(self, ty: Ty<'tcx>, item: LangItem) -> Option> { . let def_id = self.lang_items().require(item).ok()?; . Some(self.mk_generic_adt(def_id, ty)) . } . -- line 2293 ---------------------------------------- -- line 2329 ---------------------------------------- . } . . #[inline] . pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> { . self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Not }) . } . . #[inline] 9,789 ( 0.00%) pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> { . self.mk_ty(Array(ty, ty::Const::from_usize(self, n))) 9,952 ( 0.00%) } . . #[inline] . pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> { . self.mk_ty(Slice(ty)) . } . . #[inline] . pub fn intern_tup(self, ts: &[Ty<'tcx>]) -> Ty<'tcx> { 4,400 ( 0.00%) let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect(); 5,522 ( 0.00%) self.mk_ty(Tuple(self.intern_substs(&kinds))) . } . . pub fn mk_tup], Ty<'tcx>>>(self, iter: I) -> I::Output { 31,814 ( 0.00%) iter.intern_with(|ts| { 6,811 ( 0.00%) let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect(); 64,208 ( 0.00%) self.mk_ty(Tuple(self.intern_substs(&kinds))) 28,584 ( 0.00%) }) . } . . #[inline] . pub fn mk_unit(self) -> Ty<'tcx> { 7,087 ( 0.00%) self.types.unit . } . . #[inline] . pub fn mk_diverging_default(self) -> Ty<'tcx> { . if self.features().never_type_fallback { self.types.never } else { self.types.unit } . } . . #[inline] . pub fn mk_fn_def(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . self.mk_ty(FnDef(def_id, substs)) . } . . #[inline] . pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> { 3,412 ( 0.00%) self.mk_ty(FnPtr(fty)) . } . . #[inline] . pub fn mk_dynamic( . self, . obj: &'tcx List>>, . reg: ty::Region<'tcx>, . ) -> Ty<'tcx> { -- line 2384 ---------------------------------------- -- line 2412 ---------------------------------------- . . #[inline] . pub fn mk_ty_var(self, v: TyVid) -> Ty<'tcx> { . self.mk_ty_infer(TyVar(v)) . } . . #[inline] . pub fn mk_const_var(self, v: ConstVid<'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> { 1,848 ( 0.00%) self.mk_const(ty::Const { val: ty::ConstKind::Infer(InferConst::Var(v)), ty }) . } . . #[inline] . pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> { . self.mk_ty_infer(IntVar(v)) . } . . #[inline] -- line 2428 ---------------------------------------- -- line 2445 ---------------------------------------- . self.mk_ty(Param(ParamTy { index, name })) . } . . #[inline] . pub fn mk_const_param(self, index: u32, name: Symbol, ty: Ty<'tcx>) -> &'tcx Const<'tcx> { . self.mk_const(ty::Const { val: ty::ConstKind::Param(ParamConst { index, name }), ty }) . } . 26,432 ( 0.00%) pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 13,376 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { 16,512 ( 0.00%) self.mk_region(ty::ReEarlyBound(param.to_early_bound_region_data())).into() . } 2,048 ( 0.00%) GenericParamDefKind::Type { .. } => self.mk_ty_param(param.index, param.name).into(), . GenericParamDefKind::Const { .. } => { . self.mk_const_param(param.index, param.name, self.type_of(param.def_id)).into() . } . } 26,432 ( 0.00%) } . . #[inline] . pub fn mk_opaque(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . self.mk_ty(Opaque(def_id, substs)) . } . 6,031 ( 0.00%) pub fn mk_place_field(self, place: Place<'tcx>, f: Field, ty: Ty<'tcx>) -> Place<'tcx> { 6,031 ( 0.00%) self.mk_place_elem(place, PlaceElem::Field(f, ty)) 12,062 ( 0.00%) } . 208 ( 0.00%) pub fn mk_place_deref(self, place: Place<'tcx>) -> Place<'tcx> { 624 ( 0.00%) self.mk_place_elem(place, PlaceElem::Deref) 416 ( 0.00%) } . 2,358 ( 0.00%) pub fn mk_place_downcast( . self, . place: Place<'tcx>, . adt_def: &'tcx AdtDef, . variant_index: VariantIdx, . ) -> Place<'tcx> { 2,358 ( 0.00%) self.mk_place_elem( . place, 4,716 ( 0.00%) PlaceElem::Downcast(Some(adt_def.variants[variant_index].name), variant_index), . ) 4,716 ( 0.00%) } . . pub fn mk_place_downcast_unnamed( . self, . place: Place<'tcx>, . variant_index: VariantIdx, . ) -> Place<'tcx> { . self.mk_place_elem(place, PlaceElem::Downcast(None, variant_index)) . } . 8 ( 0.00%) pub fn mk_place_index(self, place: Place<'tcx>, index: Local) -> Place<'tcx> { 8 ( 0.00%) self.mk_place_elem(place, PlaceElem::Index(index)) 16 ( 0.00%) } . . /// This method copies `Place`'s projection, add an element and reintern it. Should not be used . /// to build a full `Place` it's just a convenient way to grab a projection and modify it in . /// flight. 109,062 ( 0.00%) pub fn mk_place_elem(self, place: Place<'tcx>, elem: PlaceElem<'tcx>) -> Place<'tcx> { . let mut projection = place.projection.to_vec(); . projection.push(elem); . . Place { local: place.local, projection: self.intern_place_elems(&projection) } 121,180 ( 0.00%) } . 13,741 ( 0.00%) pub fn intern_poly_existential_predicates( . self, . eps: &[ty::Binder<'tcx, ExistentialPredicate<'tcx>>], . ) -> &'tcx List>> { 2,031 ( 0.00%) assert!(!eps.is_empty()); . assert!( . eps.array_windows() 472 ( 0.00%) .all(|[a, b]| a.skip_binder().stable_cmp(self, &b.skip_binder()) . != Ordering::Greater) . ); 8,124 ( 0.00%) self._intern_poly_existential_predicates(eps) 15,704 ( 0.00%) } . . pub fn intern_predicates(self, preds: &[Predicate<'tcx>]) -> &'tcx List> { . // FIXME consider asking the input slice to be sorted to avoid . // re-interning permutations, in which case that would be asserted . // here. 19,420 ( 0.00%) if preds.is_empty() { . // The macro-generated method below asserts we don't intern an empty slice. . List::empty() . } else { 7,505 ( 0.00%) self._intern_predicates(preds) . } 23,928 ( 0.00%) } . . pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List> { 180,396 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_type_list(ts) } 26,944 ( 0.00%) } . . pub fn intern_substs(self, ts: &[GenericArg<'tcx>]) -> &'tcx List> { 1,659,193 ( 0.01%) if ts.is_empty() { List::empty() } else { self._intern_substs(ts) } 139,266 ( 0.00%) } . . pub fn intern_projs(self, ps: &[ProjectionKind]) -> &'tcx List { . if ps.is_empty() { List::empty() } else { self._intern_projs(ps) } . } . . pub fn intern_place_elems(self, ts: &[PlaceElem<'tcx>]) -> &'tcx List> { 91,957 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_place_elems(ts) } 57,214 ( 0.00%) } . . pub fn intern_canonical_var_infos( . self, . ts: &[CanonicalVarInfo<'tcx>], . ) -> CanonicalVarInfos<'tcx> { 89,443 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_canonical_var_infos(ts) } 418 ( 0.00%) } . . pub fn intern_bound_variable_kinds( . self, . ts: &[ty::BoundVariableKind], . ) -> &'tcx List { 16,159 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_bound_variable_kinds(ts) } 20,122 ( 0.00%) } . . pub fn mk_fn_sig( . self, . inputs: I, . output: I::Item, . c_variadic: bool, . unsafety: hir::Unsafety, . abi: abi::Abi, . ) -> , ty::FnSig<'tcx>>>::Output . where . I: Iterator, ty::FnSig<'tcx>>>, . { . inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig { 6,517 ( 0.00%) inputs_and_output: self.intern_type_list(xs), 1,343 ( 0.00%) c_variadic, 1,896 ( 0.00%) unsafety, 1,580 ( 0.00%) abi, 440 ( 0.00%) }) . } . . pub fn mk_poly_existential_predicates< . I: InternAs< . [ty::Binder<'tcx, ExistentialPredicate<'tcx>>], . &'tcx List>>, . >, . >( . self, . iter: I, . ) -> I::Output { 7,839 ( 0.00%) iter.intern_with(|xs| self.intern_poly_existential_predicates(xs)) . } . . pub fn mk_predicates], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 20 ( 0.00%) iter.intern_with(|xs| self.intern_predicates(xs)) . } . . pub fn mk_type_list], &'tcx List>>>(self, iter: I) -> I::Output { 154,893 ( 0.00%) iter.intern_with(|xs| self.intern_type_list(xs)) . } . 4,341 ( 0.00%) pub fn mk_substs], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 917,209 ( 0.01%) iter.intern_with(|xs| self.intern_substs(xs)) 5,788 ( 0.00%) } . . pub fn mk_place_elems], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 264,234 ( 0.00%) iter.intern_with(|xs| self.intern_place_elems(xs)) . } . 62,293 ( 0.00%) pub fn mk_substs_trait(self, self_ty: Ty<'tcx>, rest: &[GenericArg<'tcx>]) -> SubstsRef<'tcx> { . self.mk_substs(iter::once(self_ty.into()).chain(rest.iter().cloned())) 124,586 ( 0.00%) } . . pub fn mk_bound_variable_kinds< . I: InternAs<[ty::BoundVariableKind], &'tcx List>, . >( . self, . iter: I, . ) -> I::Output { 74,001 ( 0.00%) iter.intern_with(|xs| self.intern_bound_variable_kinds(xs)) . } . . /// Walks upwards from `id` to find a node which might change lint levels with attributes. . /// It stops at `bound` and just returns it if reached. 576,086 ( 0.00%) pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId { 576,086 ( 0.00%) let hir = self.hir(); . loop { 1,155,228 ( 0.01%) if id == bound { . return bound; . } . 1,583,842 ( 0.01%) if hir.attrs(id).iter().any(|attr| Level::from_symbol(attr.name_or_empty()).is_some()) { . return id; . } . let next = hir.get_parent_node(id); 908,334 ( 0.01%) if next == id { . bug!("lint traversal reached the root of the crate"); . } . id = next; . } 822,980 ( 0.00%) } . 23,560 ( 0.00%) pub fn lint_level_at_node( . self, . lint: &'static Lint, . mut id: hir::HirId, . ) -> (Level, LintLevelSource) { . let sets = self.lint_levels(()); . loop { 147,952 ( 0.00%) if let Some(pair) = sets.level_and_source(lint, id, self.sess) { . return pair; . } 11,858 ( 0.00%) let next = self.hir().get_parent_node(id); 35,574 ( 0.00%) if next == id { . bug!("lint traversal reached the root of the crate"); . } . id = next; . } 23,560 ( 0.00%) } . 882 ( 0.00%) pub fn struct_span_lint_hir( . self, . lint: &'static Lint, . hir_id: HirId, . span: impl Into, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { 13,005 ( 0.00%) let (level, src) = self.lint_level_at_node(lint, hir_id); 3,513 ( 0.00%) struct_lint_level(self.sess, lint, level, src, Some(span.into()), decorate); 504 ( 0.00%) } . . pub fn struct_lint_node( . self, . lint: &'static Lint, . id: HirId, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { . let (level, src) = self.lint_level_at_node(lint, id); . struct_lint_level(self.sess, lint, level, src, None, decorate); . } . 25,039 ( 0.00%) pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx [TraitCandidate]> { 7,154 ( 0.00%) let map = self.in_scope_traits_map(id.owner)?; . let candidates = map.get(&id.local_id)?; 7,154 ( 0.00%) Some(&*candidates) 28,616 ( 0.00%) } . 50,127 ( 0.00%) pub fn named_region(self, id: HirId) -> Option { . debug!(?id, "named_region"); . self.named_region_map(id.owner).and_then(|map| map.get(&id.local_id).cloned()) 64,449 ( 0.00%) } . 6,120 ( 0.00%) pub fn is_late_bound(self, id: HirId) -> bool { . self.is_late_bound_map(id.owner) 346 ( 0.00%) .map_or(false, |(owner, set)| owner == id.owner && set.contains(&id.local_id)) 5,440 ( 0.00%) } . 39,270 ( 0.00%) pub fn object_lifetime_defaults(self, id: HirId) -> Option> { . self.object_lifetime_defaults_map(id.owner) 50,490 ( 0.00%) } . 12,186 ( 0.00%) pub fn late_bound_vars(self, id: HirId) -> &'tcx List { . self.mk_bound_variable_kinds( . self.late_bound_vars_map(id.owner) . .and_then(|map| map.get(&id.local_id).cloned()) . .unwrap_or_else(|| { . bug!("No bound vars found for {:?} ({:?})", self.hir().node_to_string(id), id) . }) . .iter(), . ) 12,186 ( 0.00%) } . . pub fn lifetime_scope(self, id: HirId) -> Option { . self.lifetime_scope_map(id.owner).and_then(|mut map| map.remove(&id.local_id)) . } . . /// Whether the `def_id` counts as const fn in the current crate, considering all active . /// feature gates 330 ( 0.00%) pub fn is_const_fn(self, def_id: DefId) -> bool { 33 ( 0.00%) if self.is_const_fn_raw(def_id) { 10 ( 0.00%) match self.lookup_const_stability(def_id) { 20 ( 0.00%) Some(stability) if stability.level.is_unstable() => { . // has a `rustc_const_unstable` attribute, check whether the user enabled the . // corresponding feature gate. 8 ( 0.00%) self.features() . .declared_lib_features . .iter() . .any(|&(sym, _)| sym == stability.feature) . } . // functions without const stability are either stable user written . // const fn or the user is using feature gates and we thus don't . // care what they do . _ => true, . } . } else { . false . } 297 ( 0.00%) } . } . . impl<'tcx> TyCtxtAt<'tcx> { . /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used. . #[track_caller] . pub fn ty_error(self) -> Ty<'tcx> { . self.tcx.ty_error_with_message(self.span, "TyKind::Error constructed but no error reported") . } -- line 2759 ---------------------------------------- -- line 2774 ---------------------------------------- . } . . impl InternAs<[T], R> for I . where . E: InternIteratorElement, . I: Iterator, . { . type Output = E::Output; 267,872 ( 0.00%) fn intern_with(self, f: F) -> Self::Output . where . F: FnOnce(&[T]) -> R, . { 3,816,713 ( 0.02%) E::intern_with(self, f) 159,111 ( 0.00%) } . } . . pub trait InternIteratorElement: Sized { . type Output; . fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output; . } . . impl InternIteratorElement for T { . type Output = R; 511,051 ( 0.00%) fn intern_with, F: FnOnce(&[T]) -> R>( . mut iter: I, . f: F, . ) -> Self::Output { . // This code is hot enough that it's worth specializing for the most . // common length lists, to avoid the overhead of `SmallVec` creation. . // Lengths 0, 1, and 2 typically account for ~95% of cases. If . // `size_hint` is incorrect a panic will occur via an `unwrap` or an . // `assert`. 556,201 ( 0.00%) match iter.size_hint() { . (0, Some(0)) => { 6 ( 0.00%) assert!(iter.next().is_none()); . f(&[]) . } . (1, Some(1)) => { . let t0 = iter.next().unwrap(); 16 ( 0.00%) assert!(iter.next().is_none()); 83,166 ( 0.00%) f(&[t0]) . } . (2, Some(2)) => { . let t0 = iter.next().unwrap(); . let t1 = iter.next().unwrap(); 603 ( 0.00%) assert!(iter.next().is_none()); 67,063 ( 0.00%) f(&[t0, t1]) . } 2,984 ( 0.00%) _ => f(&iter.collect::>()), . } 429,998 ( 0.00%) } . } . . impl<'a, T, R> InternIteratorElement for &'a T . where . T: Clone + 'a, . { . type Output = R; 20,042 ( 0.00%) fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output { . // This code isn't hot. 176 ( 0.00%) f(&iter.cloned().collect::>()) 16,194 ( 0.00%) } . } . . impl InternIteratorElement for Result { . type Output = Result; 1,425,410 ( 0.01%) fn intern_with, F: FnOnce(&[T]) -> R>( . mut iter: I, . f: F, . ) -> Self::Output { . // This code is hot enough that it's worth specializing for the most . // common length lists, to avoid the overhead of `SmallVec` creation. . // Lengths 0, 1, and 2 typically account for ~95% of cases. If . // `size_hint` is incorrect a panic will occur via an `unwrap` or an . // `assert`, unless a failure happens first, in which case the result . // will be an error anyway. 1,077,320 ( 0.01%) Ok(match iter.size_hint() { . (0, Some(0)) => { . assert!(iter.next().is_none()); . f(&[]) . } . (1, Some(1)) => { 5,733 ( 0.00%) let t0 = iter.next().unwrap()?; . assert!(iter.next().is_none()); 74,008 ( 0.00%) f(&[t0]) . } . (2, Some(2)) => { 1,663 ( 0.00%) let t0 = iter.next().unwrap()?; 1,663 ( 0.00%) let t1 = iter.next().unwrap()?; 2,463 ( 0.00%) assert!(iter.next().is_none()); 113,052 ( 0.00%) f(&[t0, t1]) . } 7,637 ( 0.00%) _ => f(&iter.collect::, _>>()?), . }) 1,610,104 ( 0.01%) } . } . . // We are comparing types with different invariant lifetimes, so `ptr::eq` . // won't work for us. . fn ptr_eq(t: *const T, u: *const U) -> bool { 402,979 ( 0.00%) t as *const () == u as *const () . } . . pub fn provide(providers: &mut ty::query::Providers) { 2 ( 0.00%) providers.in_scope_traits_map = . |tcx, id| tcx.hir_crate(()).owners[id].as_ref().map(|owner_info| &owner_info.trait_map); 3 ( 0.00%) providers.resolutions = |tcx, ()| &tcx.untracked_resolutions; 2 ( 0.00%) providers.module_reexports = . |tcx, id| tcx.resolutions(()).reexport_map.get(&id).map(|v| &v[..]); 2 ( 0.00%) providers.crate_name = |tcx, id| { 1 ( 0.00%) assert_eq!(id, LOCAL_CRATE); 1 ( 0.00%) tcx.crate_name . }; 2 ( 0.00%) providers.maybe_unused_trait_import = . |tcx, id| tcx.resolutions(()).maybe_unused_trait_imports.contains(&id); 2 ( 0.00%) providers.maybe_unused_extern_crates = . |tcx, ()| &tcx.resolutions(()).maybe_unused_extern_crates[..]; 2 ( 0.00%) providers.names_imported_by_glob_use = |tcx, id| { . tcx.arena.alloc(tcx.resolutions(()).glob_map.get(&id).cloned().unwrap_or_default()) . }; . 11 ( 0.00%) providers.lookup_stability = |tcx, id| tcx.stability().local_stability(id.expect_local()); 2 ( 0.00%) providers.lookup_const_stability = . |tcx, id| tcx.stability().local_const_stability(id.expect_local()); 2 ( 0.00%) providers.lookup_deprecation_entry = 25,768 ( 0.00%) |tcx, id| tcx.stability().local_deprecation_entry(id.expect_local()); 2 ( 0.00%) providers.extern_mod_stmt_cnum = . |tcx, id| tcx.resolutions(()).extern_crate_map.get(&id).cloned(); 3 ( 0.00%) providers.output_filenames = |tcx, ()| tcx.output_filenames.clone(); 3 ( 0.00%) providers.features_query = |tcx, ()| tcx.sess.features_untracked(); 2 ( 0.00%) providers.is_panic_runtime = |tcx, cnum| { 1 ( 0.00%) assert_eq!(cnum, LOCAL_CRATE); 7 ( 0.00%) tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::panic_runtime) . }; 2 ( 0.00%) providers.is_compiler_builtins = |tcx, cnum| { 1 ( 0.00%) assert_eq!(cnum, LOCAL_CRATE); 7 ( 0.00%) tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::compiler_builtins) . }; 2 ( 0.00%) providers.has_panic_handler = |tcx, cnum| { 1 ( 0.00%) assert_eq!(cnum, LOCAL_CRATE); . // We want to check if the panic handler was defined in this crate 3 ( 0.00%) tcx.lang_items().panic_impl().map_or(false, |did| did.is_local()) . }; . } 3,834,647 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/obligation_forest/mod.rs -------------------------------------------------------------------------------- Ir -- line 121 ---------------------------------------- . #[derive(Debug)] . pub enum ProcessResult { . Unchanged, . Changed(Vec), . Error(E), . } . . #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] 117,280 ( 0.00%) struct ObligationTreeId(usize); . . type ObligationTreeIdGenerator = . std::iter::Map, fn(usize) -> ObligationTreeId>; . . pub struct ObligationForest { . /// The list of obligations. In between calls to `process_obligations`, . /// this list only contains nodes in the `Pending` or `Waiting` state. . /// -- line 137 ---------------------------------------- -- line 181 ---------------------------------------- . has_parent: bool, . . /// Identifier of the obligation tree to which this node belongs. . obligation_tree_id: ObligationTreeId, . } . . impl Node { . fn new(parent: Option, obligation: O, obligation_tree_id: ObligationTreeId) -> Node { 1,263,872 ( 0.01%) Node { . obligation, . state: Cell::new(NodeState::Pending), 140,048 ( 0.00%) dependents: if let Some(parent_index) = parent { vec![parent_index] } else { vec![] }, . has_parent: parent.is_some(), . obligation_tree_id, . } . } . } . . /// The state of one node in some tree within the forest. This represents the . /// current state of processing for the obligation (of type `O`) associated -- line 200 ---------------------------------------- -- line 223 ---------------------------------------- . /// | compress() . /// v . /// (Removed) . /// ``` . /// The `Error` state can be introduced in several places, via `error_at()`. . /// . /// Outside of `ObligationForest` methods, nodes should be either `Pending` or . /// `Waiting`. 17,201,526 ( 0.10%) #[derive(Debug, Copy, Clone, PartialEq, Eq)] . enum NodeState { . /// This obligation has not yet been selected successfully. Cannot have . /// subobligations. . Pending, . . /// This obligation was selected successfully, but may or may not have . /// subobligations. . Success, -- line 239 ---------------------------------------- -- line 279 ---------------------------------------- . pub stalled: bool, . } . . impl OutcomeTrait for Outcome { . type Error = Error; . type Obligation = O; . . fn new() -> Self { 186,906 ( 0.00%) Self { stalled: true, errors: vec![] } . } . . fn mark_not_stalled(&mut self) { 76,609 ( 0.00%) self.stalled = false; . } . . fn is_stalled(&self) -> bool { 47,840 ( 0.00%) self.stalled . } . . fn record_completed(&mut self, _outcome: &Self::Obligation) { . // do nothing . } . . fn record_error(&mut self, error: Self::Error) { 48 ( 0.00%) self.errors.push(error) . } . } . . #[derive(Debug, PartialEq, Eq)] . pub struct Error { . pub error: E, . pub backtrace: Vec, . } . . impl ObligationForest { 26,484 ( 0.00%) pub fn new() -> ObligationForest { 317,808 ( 0.00%) ObligationForest { . nodes: vec![], . done_cache: Default::default(), . active_cache: Default::default(), . reused_node_vec: vec![], . obligation_tree_id_generator: (0..).map(ObligationTreeId), . error_cache: Default::default(), . } 26,484 ( 0.00%) } . . /// Returns the total number of nodes in the forest that have not . /// yet been fully resolved. . pub fn len(&self) -> usize { . self.nodes.len() . } . . /// Registers an obligation. . pub fn register_obligation(&mut self, obligation: O) { . // Ignore errors here - there is no guarantee of success. 949,559 ( 0.01%) let _ = self.register_obligation_at(obligation, None); . } . . // Returns Err(()) if we already know this obligation failed. 1,322,486 ( 0.01%) fn register_obligation_at(&mut self, obligation: O, parent: Option) -> Result<(), ()> { 240,452 ( 0.00%) let cache_key = obligation.as_cache_key(); 240,452 ( 0.00%) if self.done_cache.contains(&cache_key) { . debug!("register_obligation_at: ignoring already done obligation: {:?}", obligation); . return Ok(()); . } . 555,372 ( 0.00%) match self.active_cache.entry(cache_key) { . Entry::Occupied(o) => { 27,140 ( 0.00%) let node = &mut self.nodes[*o.get()]; 27,140 ( 0.00%) if let Some(parent_index) = parent { . // If the node is already in `active_cache`, it has already . // had its chance to be marked with a parent. So if it's . // not already present, just dump `parent` into the . // dependents as a non-parent. 20,475 ( 0.00%) if !node.dependents.contains(&parent_index) { . node.dependents.push(parent_index); . } . } 40,710 ( 0.00%) if let NodeState::Error = node.state.get() { Err(()) } else { Ok(()) } . } 236,976 ( 0.00%) Entry::Vacant(v) => { 473,952 ( 0.00%) let obligation_tree_id = match parent { 40,704 ( 0.00%) Some(parent_index) => self.nodes[parent_index].obligation_tree_id, . None => self.obligation_tree_id_generator.next().unwrap(), . }; . . let already_failed = parent.is_some() . && self . .error_cache . .get(&obligation_tree_id) . .map_or(false, |errors| errors.contains(v.key())); . . if already_failed { . Err(()) . } else { 78,992 ( 0.00%) let new_index = self.nodes.len(); . v.insert(new_index); . self.nodes.push(Node::new(parent, obligation, obligation_tree_id)); . Ok(()) . } . } . } 1,082,034 ( 0.01%) } . . /// Converts all remaining obligations to the given error. 222,957 ( 0.00%) pub fn to_errors(&mut self, error: E) -> Vec> { . let errors = self . .nodes . .iter() . .enumerate() . .filter(|(_index, node)| node.state.get() == NodeState::Pending) . .map(|(index, _node)| Error { error: error.clone(), backtrace: self.error_at(index) }) . .collect(); . 63,702 ( 0.00%) self.compress(|_| assert!(false)); . errors 191,106 ( 0.00%) } . . /// Returns the set of obligations that are in a pending state. . pub fn map_pending_obligations(&self, f: F) -> Vec

. where . F: Fn(&O) -> P, . { 114 ( 0.00%) self.nodes . .iter() . .filter(|node| node.state.get() == NodeState::Pending) . .map(|node| f(&node.obligation)) . .collect() . } . 21 ( 0.00%) fn insert_into_error_cache(&mut self, index: usize) { . let node = &self.nodes[index]; 3 ( 0.00%) self.error_cache 9 ( 0.00%) .entry(node.obligation_tree_id) . .or_default() . .insert(node.obligation.as_cache_key()); 24 ( 0.00%) } . . /// Performs a pass through the obligation list. This must . /// be called in a loop until `outcome.stalled` is false. . /// . /// This _cannot_ be unrolled (presently, at least). . #[inline(never)] 841,077 ( 0.00%) pub fn process_obligations(&mut self, processor: &mut P) -> OUT . where . P: ObligationProcessor, . OUT: OutcomeTrait>, . { . let mut outcome = OUT::new(); . . // Note that the loop body can append new nodes, and those new nodes . // will then be processed by subsequent iterations of the loop. . // . // We can't use an iterator for the loop because `self.nodes` is . // appended to and the borrow checker would complain. We also can't use . // `for index in 0..self.nodes.len() { ... }` because the range would . // be computed with the initial length, and we would miss the appended . // nodes. Therefore we use a `while` loop. . let mut index = 0; 9,539,150 ( 0.05%) while let Some(node) = self.nodes.get_mut(index) { . // `processor.process_obligation` can modify the predicate within . // `node.obligation`, and that predicate is the key used for . // `self.active_cache`. This means that `self.active_cache` can get . // out of sync with `nodes`. It's not very common, but it does . // happen, and code in `compress` has to allow for it. 18,891,394 ( 0.11%) if node.state.get() != NodeState::Pending { 36,791 ( 0.00%) index += 1; . continue; . } . 459,242 ( 0.00%) match processor.process_obligation(&mut node.obligation) { . ProcessResult::Unchanged => { . // No change in state. . } 306,424 ( 0.00%) ProcessResult::Changed(children) => { . // We are not (yet) stalled. . outcome.mark_not_stalled(); . node.state.set(NodeState::Success); . 400,790 ( 0.00%) for child in children { 802,111 ( 0.00%) let st = self.register_obligation_at(child, Some(index)); 94,366 ( 0.00%) if let Err(()) = st { . // Error already reported - propagate it . // to our node. . self.error_at(index); . } . } . } . ProcessResult::Error(err) => { . outcome.mark_not_stalled(); 99 ( 0.00%) outcome.record_error(Error { error: err, backtrace: self.error_at(index) }); . } . } 18,817,812 ( 0.11%) index += 1; . } . . // There's no need to perform marking, cycle processing and compression when nothing . // changed. 47,840 ( 0.00%) if !outcome.is_stalled() { . self.mark_successes(); . self.process_cycles(processor); 37,888 ( 0.00%) self.compress(|obl| outcome.record_completed(obl)); . } . . outcome 841,077 ( 0.00%) } . . /// Returns a vector of obligations for `p` and all of its . /// ancestors, putting them into the error state in the process. 21 ( 0.00%) fn error_at(&self, mut index: usize) -> Vec { . let mut error_stack: Vec = vec![]; . let mut trace = vec![]; . . loop { . let node = &self.nodes[index]; 3 ( 0.00%) node.state.set(NodeState::Error); . trace.push(node.obligation.clone()); 6 ( 0.00%) if node.has_parent { . // The first dependent is the parent, which is treated . // specially. . error_stack.extend(node.dependents.iter().skip(1)); . index = node.dependents[0]; . } else { . // No parent; treat all dependents non-specially. . error_stack.extend(node.dependents.iter()); . break; -- line 504 ---------------------------------------- -- line 509 ---------------------------------------- . let node = &self.nodes[index]; . if node.state.get() != NodeState::Error { . node.state.set(NodeState::Error); . error_stack.extend(node.dependents.iter()); . } . } . . trace 24 ( 0.00%) } . . /// Mark all `Waiting` nodes as `Success`, except those that depend on a . /// pending node. . fn mark_successes(&self) { . // Convert all `Waiting` nodes to `Success`. . for node in &self.nodes { 2,780,936 ( 0.02%) if node.state.get() == NodeState::Waiting { . node.state.set(NodeState::Success); . } . } . . // Convert `Success` nodes that depend on a pending node back to . // `Waiting`. . for node in &self.nodes { 2,546,514 ( 0.01%) if node.state.get() == NodeState::Pending { . // This call site is hot. . self.inlined_mark_dependents_as_waiting(node); . } . } . } . . // This always-inlined function is for the hot call site. . #[inline(always)] . fn inlined_mark_dependents_as_waiting(&self, node: &Node) { 12,427 ( 0.00%) for &index in node.dependents.iter() { . let node = &self.nodes[index]; 12,427 ( 0.00%) let state = node.state.get(); 12,427 ( 0.00%) if state == NodeState::Success { . // This call site is cold. 31,176 ( 0.00%) self.uninlined_mark_dependents_as_waiting(node); . } else { . debug_assert!(state == NodeState::Waiting || state == NodeState::Error) . } . } . } . . // This never-inlined function is for the cold call site. . #[inline(never)] 72,744 ( 0.00%) fn uninlined_mark_dependents_as_waiting(&self, node: &Node) { . // Mark node Waiting in the cold uninlined code instead of the hot inlined . node.state.set(NodeState::Waiting); . self.inlined_mark_dependents_as_waiting(node) 83,136 ( 0.00%) } . . /// Report cycles between all `Success` nodes, and convert all `Success` . /// nodes to `Done`. This must be called after `mark_successes`. . fn process_cycles

(&mut self, processor: &mut P) . where . P: ObligationProcessor, . { 18,944 ( 0.00%) let mut stack = std::mem::take(&mut self.reused_node_vec); . for (index, node) in self.nodes.iter().enumerate() { . // For some benchmarks this state test is extremely hot. It's a win . // to handle the no-op cases immediately to avoid the cost of the . // function call. 2,546,514 ( 0.01%) if node.state.get() == NodeState::Success { 372,670 ( 0.00%) self.find_cycles_from_node(&mut stack, processor, index); . } . } . . debug_assert!(stack.is_empty()); 151,552 ( 0.00%) self.reused_node_vec = stack; . } . 900,828 ( 0.01%) fn find_cycles_from_node

(&self, stack: &mut Vec, processor: &mut P, index: usize) . where . P: ObligationProcessor, . { . let node = &self.nodes[index]; 200,184 ( 0.00%) if node.state.get() == NodeState::Success { 4,168 ( 0.00%) match stack.iter().rposition(|&n| n == index) { . None => { . stack.push(index); 25,558 ( 0.00%) for &dep_index in node.dependents.iter() { 102,232 ( 0.00%) self.find_cycles_from_node(stack, processor, dep_index); . } . stack.pop(); . node.state.set(NodeState::Done); . } . Some(rpos) => { . // Cycle detected. . processor.process_backedge( . stack[rpos..].iter().map(|&i| &self.nodes[i].obligation), . PhantomData, . ); . } . } . } 800,736 ( 0.00%) } . . /// Compresses the vector, removing all popped nodes. This adjusts the . /// indices and hence invalidates any outstanding indices. `process_cycles` . /// must be run beforehand to remove any cycles on `Success` nodes. . #[inline(never)] 374,509 ( 0.00%) fn compress(&mut self, mut outcome_cb: impl FnMut(&O)) { 50,795 ( 0.00%) let orig_nodes_len = self.nodes.len(); . let mut node_rewrites: Vec<_> = std::mem::take(&mut self.reused_node_vec); . debug_assert!(node_rewrites.is_empty()); . node_rewrites.extend(0..orig_nodes_len); . let mut dead_nodes = 0; . . // Move removable nodes to the end, preserving the order of the . // remaining nodes. . // . // LOOP INVARIANT: . // self.nodes[0..index - dead_nodes] are the first remaining nodes . // self.nodes[index - dead_nodes..index] are all dead . // self.nodes[index..] are unchanged . for index in 0..orig_nodes_len { . let node = &self.nodes[index]; 12,808,346 ( 0.07%) match node.state.get() { . NodeState::Pending | NodeState::Waiting => { 4,939,810 ( 0.03%) if dead_nodes > 0 { 1,483,344 ( 0.01%) self.nodes.swap(index, index - dead_nodes); 2,472,240 ( 0.01%) node_rewrites[index] -= dead_nodes; . } . } . NodeState::Done => { . // This lookup can fail because the contents of . // `self.active_cache` are not guaranteed to match those of . // `self.nodes`. See the comment in `process_obligation` . // for more details. 277,354 ( 0.00%) if let Some((predicate, _)) = 229,818 ( 0.00%) self.active_cache.remove_entry(&node.obligation.as_cache_key()) . { . self.done_cache.insert(predicate); . } else { . self.done_cache.insert(node.obligation.as_cache_key().clone()); . } . // Extract the success stories. . outcome_cb(&node.obligation); 153,212 ( 0.00%) node_rewrites[index] = orig_nodes_len; 153,212 ( 0.00%) dead_nodes += 1; . } . NodeState::Error => { . // We *intentionally* remove the node from the cache at this point. Otherwise . // tests must come up with a different type on every type error they . // check against. 9 ( 0.00%) self.active_cache.remove(&node.obligation.as_cache_key()); 6 ( 0.00%) self.insert_into_error_cache(index); 6 ( 0.00%) node_rewrites[index] = orig_nodes_len; 6 ( 0.00%) dead_nodes += 1; . } . NodeState::Success => unreachable!(), . } . } . . if dead_nodes > 0 { . // Remove the dead nodes and rewrite indices. 36,608 ( 0.00%) self.nodes.truncate(orig_nodes_len - dead_nodes); 18,304 ( 0.00%) self.apply_rewrites(&node_rewrites); . } . . node_rewrites.truncate(0); 203,180 ( 0.00%) self.reused_node_vec = node_rewrites; 406,360 ( 0.00%) } . . #[inline(never)] 164,736 ( 0.00%) fn apply_rewrites(&mut self, node_rewrites: &[usize]) { . let orig_nodes_len = node_rewrites.len(); . . for node in &mut self.nodes { . let mut i = 0; 2,450,988 ( 0.01%) while let Some(dependent) = node.dependents.get_mut(i) { 42,324 ( 0.00%) let new_index = node_rewrites[*dependent]; 21,162 ( 0.00%) if new_index >= orig_nodes_len { . node.dependents.swap_remove(i); . if i == 0 && node.has_parent { . // We just removed the parent. . node.has_parent = false; . } . } else { 10,581 ( 0.00%) *dependent = new_index; 21,162 ( 0.00%) i += 1; . } . } . } . . // This updating of `self.active_cache` is necessary because the . // removal of nodes within `compress` can fail. See above. . self.active_cache.retain(|_predicate, index| { 9,877,908 ( 0.06%) let new_index = node_rewrites[*index]; 4,938,954 ( 0.03%) if new_index >= orig_nodes_len { . false . } else { 2,440,407 ( 0.01%) *index = new_index; . true . } . }); 146,432 ( 0.00%) } . } 21,362,527 ( 0.12%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/type_variable.rs -------------------------------------------------------------------------------- Ir -- line 44 ---------------------------------------- . /// Convert from a specific kind of undo to the more general UndoLog . impl<'tcx> From for UndoLog<'tcx> { . fn from(l: Instantiate) -> Self { . UndoLog::Values(sv::UndoLog::Other(l)) . } . } . . impl<'tcx> Rollback> for TypeVariableStorage<'tcx> { 174,019 ( 0.00%) fn reverse(&mut self, undo: UndoLog<'tcx>) { 734,951 ( 0.00%) match undo { 135,144 ( 0.00%) UndoLog::EqRelation(undo) => self.eq_relations.reverse(undo), 79,458 ( 0.00%) UndoLog::SubRelation(undo) => self.sub_relations.reverse(undo), 133,436 ( 0.00%) UndoLog::Values(undo) => self.values.reverse(undo), . } 348,038 ( 0.00%) } . } . . pub struct TypeVariableStorage<'tcx> { . values: sv::SnapshotVecStorage, . . /// Two variables are unified in `eq_relations` when we have a . /// constraint `?X == ?Y`. This table also stores, for each key, . /// the known value. -- line 66 ---------------------------------------- -- line 136 ---------------------------------------- . DynReturnFn, . LatticeVariable, . } . . pub(crate) struct TypeVariableData { . origin: TypeVariableOrigin, . } . 1,654,298 ( 0.01%) #[derive(Copy, Clone, Debug)] . pub enum TypeVariableValue<'tcx> { . Known { value: Ty<'tcx> }, . Unknown { universe: ty::UniverseIndex }, . } . . impl<'tcx> TypeVariableValue<'tcx> { . /// If this value is known, returns the type it is known to be. . /// Otherwise, `None`. . pub fn known(&self) -> Option> { 1,053,136 ( 0.01%) match *self { . TypeVariableValue::Unknown { .. } => None, . TypeVariableValue::Known { value } => Some(value), . } . } . . pub fn is_unknown(&self) -> bool { . match *self { . TypeVariableValue::Unknown { .. } => true, -- line 162 ---------------------------------------- -- line 166 ---------------------------------------- . } . . pub(crate) struct Instantiate; . . pub(crate) struct Delegate; . . impl<'tcx> TypeVariableStorage<'tcx> { . pub fn new() -> TypeVariableStorage<'tcx> { 93,003 ( 0.00%) TypeVariableStorage { . values: sv::SnapshotVecStorage::new(), . eq_relations: ut::UnificationTableStorage::new(), . sub_relations: ut::UnificationTableStorage::new(), . } . } . . #[inline] . pub(crate) fn with_log<'a>( -- line 182 ---------------------------------------- -- line 188 ---------------------------------------- . } . . impl<'tcx> TypeVariableTable<'_, 'tcx> { . /// Returns the origin that was given when `vid` was created. . /// . /// Note that this function does not return care whether . /// `vid` has been unified with something else or not. . pub fn var_origin(&self, vid: ty::TyVid) -> &TypeVariableOrigin { 2,761 ( 0.00%) &self.storage.values.get(vid.as_usize()).origin . } . . /// Records that `a == b`, depending on `dir`. . /// . /// Precondition: neither `a` nor `b` are known. . pub fn equate(&mut self, a: ty::TyVid, b: ty::TyVid) { . debug_assert!(self.probe(a).is_unknown()); . debug_assert!(self.probe(b).is_unknown()); 4,683 ( 0.00%) self.eq_relations().union(a, b); 4,014 ( 0.00%) self.sub_relations().union(a, b); . } . . /// Records that `a <: b`, depending on `dir`. . /// . /// Precondition: neither `a` nor `b` are known. . pub fn sub(&mut self, a: ty::TyVid, b: ty::TyVid) { . debug_assert!(self.probe(a).is_unknown()); . debug_assert!(self.probe(b).is_unknown()); 22,804 ( 0.00%) self.sub_relations().union(a, b); . } . . /// Instantiates `vid` with the type `ty`. . /// . /// Precondition: `vid` must not have been previously instantiated. 352,505 ( 0.00%) pub fn instantiate(&mut self, vid: ty::TyVid, ty: Ty<'tcx>) { . let vid = self.root_var(vid); . debug_assert!(self.probe(vid).is_unknown()); . debug_assert!( . self.eq_relations().probe_value(vid).is_unknown(), . "instantiating type variable `{:?}` twice: new-value = {:?}, old-value={:?}", . vid, . ty, . self.eq_relations().probe_value(vid) . ); 493,507 ( 0.00%) self.eq_relations().union_value(vid, TypeVariableValue::Known { value: ty }); . . // Hack: we only need this so that `types_escaping_snapshot` . // can see what has been unified; see the Delegate impl for . // more details. . self.undo_log.push(Instantiate); 352,505 ( 0.00%) } . . /// Creates a new type variable. . /// . /// - `diverging`: indicates if this is a "diverging" type . /// variable, e.g., one created as the type of a `return` . /// expression. The code in this module doesn't care if a . /// variable is diverging, but the main Rust type-checker will . /// sometimes "unify" such variables with the `!` or `()` types. . /// - `origin`: indicates *why* the type variable was created. . /// The code in this module doesn't care, but it can be useful . /// for improving error messages. 429,702 ( 0.00%) pub fn new_var( . &mut self, . universe: ty::UniverseIndex, . origin: TypeVariableOrigin, . ) -> ty::TyVid { 644,553 ( 0.00%) let eq_key = self.eq_relations().new_key(TypeVariableValue::Unknown { universe }); . 358,085 ( 0.00%) let sub_key = self.sub_relations().new_key(()); 71,617 ( 0.00%) assert_eq!(eq_key.vid, sub_key); . 644,553 ( 0.00%) let index = self.values().push(TypeVariableData { origin }); 286,468 ( 0.00%) assert_eq!(eq_key.vid.as_u32(), index as u32); . . debug!("new_var(index={:?}, universe={:?}, origin={:?}", eq_key.vid, universe, origin,); . . eq_key.vid 501,319 ( 0.00%) } . . /// Returns the number of type variables created thus far. . pub fn num_vars(&self) -> usize { 7,028 ( 0.00%) self.storage.values.len() . } . . /// Returns the "root" variable of `vid` in the `eq_relations` . /// equivalence table. All type variables that have been equated . /// will yield the same root variable (per the union-find . /// algorithm), so `root_var(a) == root_var(b)` implies that `a == . /// b` (transitively). . pub fn root_var(&mut self, vid: ty::TyVid) -> ty::TyVid { 304,743 ( 0.00%) self.eq_relations().find(vid).vid . } . . /// Returns the "root" variable of `vid` in the `sub_relations` . /// equivalence table. All type variables that have been are . /// related via equality or subtyping will yield the same root . /// variable (per the union-find algorithm), so `sub_root_var(a) . /// == sub_root_var(b)` implies that: . /// . /// exists X. (a <: X || X <: a) && (b <: X || X <: b) 379 ( 0.00%) pub fn sub_root_var(&mut self, vid: ty::TyVid) -> ty::TyVid { 226,983 ( 0.00%) self.sub_relations().find(vid) 758 ( 0.00%) } . . /// Returns `true` if `a` and `b` have same "sub-root" (i.e., exists some . /// type X such that `forall i in {a, b}. (i <: X || X <: i)`. . pub fn sub_unified(&mut self, a: ty::TyVid, b: ty::TyVid) -> bool { . self.sub_root_var(a) == self.sub_root_var(b) . } . . /// Retrieves the type to which `vid` has been instantiated, if . /// any. 3,778,445 ( 0.02%) pub fn probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> { . self.inlined_probe(vid) 3,778,445 ( 0.02%) } . . /// An always-inlined variant of `probe`, for very hot call sites. . #[inline(always)] . pub fn inlined_probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> { 20,190,002 ( 0.11%) self.eq_relations().inlined_probe_value(vid) . } . . /// If `t` is a type-inference variable, and it has been . /// instantiated, then return the with which it was . /// instantiated. Otherwise, returns `t`. . pub fn replace_if_possible(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 813,138 ( 0.00%) match *t.kind() { 591,395 ( 0.00%) ty::Infer(ty::TyVar(v)) => match self.probe(v) { . TypeVariableValue::Unknown { .. } => t, . TypeVariableValue::Known { value } => value, . }, . _ => t, . } . } . . #[inline] -- line 323 ---------------------------------------- -- line 324 ---------------------------------------- . fn values( . &mut self, . ) -> sv::SnapshotVec, &mut InferCtxtUndoLogs<'tcx>> { . self.storage.values.with_log(self.undo_log) . } . . #[inline] . fn eq_relations(&mut self) -> super::UnificationTable<'_, 'tcx, TyVidEqKey<'tcx>> { 12,064,482 ( 0.07%) self.storage.eq_relations.with_log(self.undo_log) . } . . #[inline] . fn sub_relations(&mut self) -> super::UnificationTable<'_, 'tcx, ty::TyVid> { 158,956 ( 0.00%) self.storage.sub_relations.with_log(self.undo_log) . } . . /// Returns a range of the type variables created during the snapshot. 35,140 ( 0.00%) pub fn vars_since_snapshot( . &mut self, . value_count: usize, . ) -> (Range, Vec) { . let range = TyVid::from_usize(value_count)..TyVid::from_usize(self.num_vars()); 42,168 ( 0.00%) ( . range.start..range.end, . (range.start.as_usize()..range.end.as_usize()) . .map(|index| self.storage.values.get(index).origin) . .collect(), . ) 42,168 ( 0.00%) } . . /// Returns indices of all variables that are not yet . /// instantiated. . pub fn unsolved_variables(&mut self) -> Vec { . (0..self.storage.values.len()) . .filter_map(|i| { . let vid = ty::TyVid::from_usize(i); 201,912 ( 0.00%) match self.probe(vid) { . TypeVariableValue::Unknown { .. } => Some(vid), . TypeVariableValue::Known { .. } => None, . } . }) . .collect() . } . } . -- line 368 ---------------------------------------- -- line 391 ---------------------------------------- . /// These structs (a newtyped TyVid) are used as the unification key . /// for the `eq_relations`; they carry a `TypeVariableValue` along . /// with them. . #[derive(Copy, Clone, Debug, PartialEq, Eq)] . pub(crate) struct TyVidEqKey<'tcx> { . vid: ty::TyVid, . . // in the table, we map each ty-vid to one of these: 28,965,804 ( 0.16%) phantom: PhantomData>, . } . . impl<'tcx> From for TyVidEqKey<'tcx> { . #[inline] // make this function eligible for inlining - it is quite hot. . fn from(vid: ty::TyVid) -> Self { . TyVidEqKey { vid, phantom: PhantomData } . } . } -- line 407 ---------------------------------------- -- line 419 ---------------------------------------- . "TyVidEqKey" . } . } . . impl<'tcx> ut::UnifyValue for TypeVariableValue<'tcx> { . type Error = ut::NoError; . . fn unify_values(value1: &Self, value2: &Self) -> Result { 285,349 ( 0.00%) match (value1, value2) { . // We never equate two type variables, both of which . // have known types. Instead, we recursively equate . // those types. . (&TypeVariableValue::Known { .. }, &TypeVariableValue::Known { .. }) => { . bug!("equating two type variables, both of which have known types") . } . . // If one side is known, prefer that one. . (&TypeVariableValue::Known { .. }, &TypeVariableValue::Unknown { .. }) => Ok(*value1), . (&TypeVariableValue::Unknown { .. }, &TypeVariableValue::Known { .. }) => Ok(*value2), . . // If both sides are *unknown*, it hardly matters, does it? . ( 669 ( 0.00%) &TypeVariableValue::Unknown { universe: universe1 }, 669 ( 0.00%) &TypeVariableValue::Unknown { universe: universe2 }, . ) => { . // If we unify two unbound variables, ?T and ?U, then whatever . // value they wind up taking (which must be the same value) must . // be nameable by both universes. Therefore, the resulting . // universe is the minimum of the two universes, because that is . // the one which contains the fewest names in scope. . let universe = cmp::min(universe1, universe2); 2,676 ( 0.00%) Ok(TypeVariableValue::Unknown { universe }) . } . } . } . } 195,313 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/fulfill.rs -------------------------------------------------------------------------------- Ir -- line 33 ---------------------------------------- . . impl<'tcx> ForestObligation for PendingPredicateObligation<'tcx> { . /// Note that we include both the `ParamEnv` and the `Predicate`, . /// as the `ParamEnv` can influence whether fulfillment succeeds . /// or fails. . type CacheKey = ty::ParamEnvAnd<'tcx, ty::Predicate<'tcx>>; . . fn as_cache_key(&self) -> Self::CacheKey { 677,724 ( 0.00%) self.obligation.param_env.and(self.obligation.predicate) . } . } . . /// The fulfillment context is used to drive trait resolution. It . /// consists of a list of obligations that must be (eventually) . /// satisfied. The job is to track which are satisfied, which yielded . /// errors, and which are still pending. At any point, users can call . /// `select_where_possible`, and the fulfillment context will try to do -- line 49 ---------------------------------------- -- line 79 ---------------------------------------- . // outside of any snapshot, so any use of it inside a snapshot . // will lead to trouble and therefore is checked against, but . // other fulfillment contexts sometimes do live inside of . // a snapshot (they don't *straddle* a snapshot, so there . // is no trouble there). . usable_in_snapshot: bool, . } . 30 ( 0.00%) #[derive(Clone, Debug)] . pub struct PendingPredicateObligation<'tcx> { . pub obligation: PredicateObligation<'tcx>, . // This is far more often read than modified, meaning that we . // should mostly optimize for reading speed, while modifying is not as relevant. . // . // For whatever reason using a boxed slice is slower than using a `Vec` here. . pub stalled_on: Vec>, . } . . // `PendingPredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger. . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . static_assert_size!(PendingPredicateObligation<'_>, 72); . . impl<'a, 'tcx> FulfillmentContext<'tcx> { . /// Creates a new fulfillment context. 8,431 ( 0.00%) pub fn new() -> FulfillmentContext<'tcx> { 116,982 ( 0.00%) FulfillmentContext { 18,692 ( 0.00%) predicates: ObligationForest::new(), . relationships: FxHashMap::default(), . register_region_obligations: true, . usable_in_snapshot: false, . } 8,431 ( 0.00%) } . . pub fn new_in_snapshot() -> FulfillmentContext<'tcx> { 342 ( 0.00%) FulfillmentContext { 114 ( 0.00%) predicates: ObligationForest::new(), . relationships: FxHashMap::default(), . register_region_obligations: true, . usable_in_snapshot: true, . } . } . . pub fn new_ignoring_regions() -> FulfillmentContext<'tcx> { 31,168 ( 0.00%) FulfillmentContext { 7,792 ( 0.00%) predicates: ObligationForest::new(), . relationships: FxHashMap::default(), . register_region_obligations: false, . usable_in_snapshot: false, . } . } . . /// Attempts to select obligations using `selcx`. . fn select(&mut self, selcx: &mut SelectionContext<'a, 'tcx>) -> Vec> { 149,018 ( 0.00%) let span = debug_span!("select", obligation_forest_size = ?self.predicates.len()); . let _enter = span.enter(); . . let mut errors = Vec::new(); . . loop { . debug!("select: starting another iteration"); . . // Process pending obligations. . let outcome: Outcome<_, _> = 654,171 ( 0.00%) self.predicates.process_obligations(&mut FulfillProcessor { . selcx, 93,453 ( 0.00%) register_region_obligations: self.register_region_obligations, . }); . debug!("select: outcome={:#?}", outcome); . . // FIXME: if we kept the original cache key, we could mark projection . // obligations as complete for the projection cache here. . . errors.extend(outcome.errors.into_iter().map(to_fulfillment_error)); . . // If nothing new was added, no need to keep looping. 186,906 ( 0.00%) if outcome.stalled { . break; . } . } . . debug!( . "select({} predicates remaining, {} errors) done", . self.predicates.len(), . errors.len() -- line 162 ---------------------------------------- -- line 169 ---------------------------------------- . impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> { . /// "Normalize" a projection type `::X` by . /// creating a fresh type variable `$0` as well as a projection . /// predicate `::X == $0`. When the . /// inference engine runs, it will attempt to find an impl of . /// `SomeTrait` or a where-clause that lets us unify `$0` with . /// something concrete. If this fails, we'll unify `$0` with . /// `projection_ty` again. 2,508 ( 0.00%) #[tracing::instrument(level = "debug", skip(self, infcx, param_env, cause))] . fn normalize_projection_type( . &mut self, . infcx: &InferCtxt<'_, 'tcx>, . param_env: ty::ParamEnv<'tcx>, . projection_ty: ty::ProjectionTy<'tcx>, . cause: ObligationCause<'tcx>, . ) -> Ty<'tcx> { . debug_assert!(!projection_ty.has_escaping_bound_vars()); . . // FIXME(#20304) -- cache . . let mut selcx = SelectionContext::new(infcx); . let mut obligations = vec![]; 1,026 ( 0.00%) let normalized_ty = project::normalize_projection_type( . &mut selcx, . param_env, . projection_ty, 570 ( 0.00%) cause, . 0, . &mut obligations, . ); . self.register_predicate_obligations(infcx, obligations); . . debug!(?normalized_ty); . . normalized_ty . } . 438,258 ( 0.00%) fn register_predicate_obligation( . &mut self, . infcx: &InferCtxt<'_, 'tcx>, . obligation: PredicateObligation<'tcx>, . ) { . // this helps to reduce duplicate errors, as well as making . // debug output much nicer to read and so on. 219,129 ( 0.00%) let obligation = infcx.resolve_vars_if_possible(obligation); . . debug!(?obligation, "register_predicate_obligation"); . 438,258 ( 0.00%) assert!(!infcx.is_in_snapshot() || self.usable_in_snapshot); . 219,129 ( 0.00%) super::relationships::update(self, infcx, &obligation); . . self.predicates . .register_obligation(PendingPredicateObligation { obligation, stalled_on: vec![] }); 365,215 ( 0.00%) } . 254,824 ( 0.00%) fn select_all_or_error(&mut self, infcx: &InferCtxt<'_, 'tcx>) -> Vec> { . { 31,853 ( 0.00%) let errors = self.select_where_possible(infcx); 31,853 ( 0.00%) if !errors.is_empty() { 10 ( 0.00%) return errors; . } . } . 159,255 ( 0.00%) self.predicates.to_errors(CodeAmbiguity).into_iter().map(to_fulfillment_error).collect() 222,971 ( 0.00%) } . 745,090 ( 0.00%) fn select_where_possible( . &mut self, . infcx: &InferCtxt<'_, 'tcx>, . ) -> Vec> { . let mut selcx = SelectionContext::new(infcx); . self.select(&mut selcx) 670,581 ( 0.00%) } . 561 ( 0.00%) fn pending_obligations(&self) -> Vec> { . self.predicates.map_pending_obligations(|o| o.obligation.clone()) 748 ( 0.00%) } . . fn relationships(&mut self) -> &mut FxHashMap { 97 ( 0.00%) &mut self.relationships 97 ( 0.00%) } . } . . struct FulfillProcessor<'a, 'b, 'tcx> { . selcx: &'a mut SelectionContext<'b, 'tcx>, . register_region_obligations: bool, . } . . fn mk_pending(os: Vec>) -> Vec> { -- line 258 ---------------------------------------- -- line 275 ---------------------------------------- . #[inline(always)] . fn process_obligation( . &mut self, . pending_obligation: &mut Self::Obligation, . ) -> ProcessResult { . // If we were stalled on some unresolved variables, first check whether . // any of them have been resolved; if not, don't bother doing more work . // yet. 56,216,460 ( 0.32%) let change = match pending_obligation.stalled_on.len() { . // Match arms are in order of frequency, which matters because this . // code is so hot. 1 and 0 dominate; 2+ is fairly rare. . 1 => { 27,927,600 ( 0.16%) let infer_var = pending_obligation.stalled_on[0]; 9,309,200 ( 0.05%) self.selcx.infcx().ty_or_const_infer_var_changed(infer_var) . } . 0 => { . // In this case we haven't changed, but wish to make a change. . true . } . _ => { . // This `for` loop was once a call to `all()`, but this lower-level . // form was a perf win. See #64545 for details. 62,142 ( 0.00%) (|| { 120,777 ( 0.00%) for &infer_var in &pending_obligation.stalled_on { 4,977 ( 0.00%) if self.selcx.infcx().ty_or_const_infer_var_changed(infer_var) { . return true; . } . } . false . })() . } . }; . 5,255 ( 0.00%) if !change { . debug!( . "process_predicate: pending obligation {:?} still stalled on {:?}", . self.selcx.infcx().resolve_vars_if_possible(pending_obligation.obligation.clone()), . pending_obligation.stalled_on . ); . return ProcessResult::Unchanged; . } . 306,024 ( 0.00%) self.progress_changed_obligations(pending_obligation) . } . . fn process_backedge<'c, I>( . &mut self, . cycle: I, . _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>, . ) where . I: Clone + Iterator>, -- line 325 ---------------------------------------- -- line 333 ---------------------------------------- . } . } . . impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> { . // The code calling this method is extremely hot and only rarely . // actually uses this, so move this part of the code . // out of that loop. . #[inline(never)] 1,020,080 ( 0.01%) fn progress_changed_obligations( . &mut self, . pending_obligation: &mut PendingPredicateObligation<'tcx>, . ) -> ProcessResult, FulfillmentErrorCode<'tcx>> { . pending_obligation.stalled_on.truncate(0); . . let obligation = &mut pending_obligation.obligation; . 306,024 ( 0.00%) if obligation.predicate.has_infer_types_or_consts() { 56,657 ( 0.00%) obligation.predicate = 169,971 ( 0.00%) self.selcx.infcx().resolve_vars_if_possible(obligation.predicate); . } . . debug!(?obligation, ?obligation.cause, "process_obligation"); . . let infcx = self.selcx.infcx(); . 90,702 ( 0.00%) let binder = obligation.predicate.kind(); 714,056 ( 0.00%) match binder.no_bound_vars() { 1,540 ( 0.00%) None => match binder.skip_binder() { . // Evaluation will discard candidates using the leak check. . // This means we need to pass it the bound version of our . // predicate. . ty::PredicateKind::Trait(trait_ref) => { . let trait_obligation = obligation.with(binder.rebind(trait_ref)); . 280 ( 0.00%) self.process_trait_obligation( . obligation, 840 ( 0.00%) trait_obligation, . &mut pending_obligation.stalled_on, . ) . } . ty::PredicateKind::Projection(data) => { . let project_obligation = obligation.with(binder.rebind(data)); . 280 ( 0.00%) self.process_projection_obligation( . obligation, 840 ( 0.00%) project_obligation, . &mut pending_obligation.stalled_on, . ) . } . ty::PredicateKind::RegionOutlives(_) . | ty::PredicateKind::TypeOutlives(_) . | ty::PredicateKind::WellFormed(_) . | ty::PredicateKind::ObjectSafe(_) . | ty::PredicateKind::ClosureKind(..) -- line 386 ---------------------------------------- -- line 397 ---------------------------------------- . ty::PredicateKind::TypeWellFormedFromEnv(..) => { . bug!("TypeWellFormedFromEnv is only used for Chalk") . } . }, . Some(pred) => match pred { . ty::PredicateKind::Trait(data) => { . let trait_obligation = obligation.with(Binder::dummy(data)); . 253,790 ( 0.00%) self.process_trait_obligation( . obligation, 1,116,676 ( 0.01%) trait_obligation, . &mut pending_obligation.stalled_on, . ) . } . . ty::PredicateKind::RegionOutlives(data) => { 29,598 ( 0.00%) match infcx.region_outlives_predicate(&obligation.cause, Binder::dummy(data)) { 19,732 ( 0.00%) Ok(()) => ProcessResult::Changed(vec![]), . Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)), . } . } . . ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(t_a, r_b)) => { 17,580 ( 0.00%) if self.register_region_obligations { 43,950 ( 0.00%) self.selcx.infcx().register_region_obligation_with_cause( . t_a, . r_b, . &obligation.cause, . ); . } . ProcessResult::Changed(vec![]) . } . . ty::PredicateKind::Projection(ref data) => { . let project_obligation = obligation.with(Binder::dummy(*data)); . 38,655 ( 0.00%) self.process_projection_obligation( . obligation, 115,965 ( 0.00%) project_obligation, . &mut pending_obligation.stalled_on, . ) . } . . ty::PredicateKind::ObjectSafe(trait_def_id) => { 204 ( 0.00%) if !self.selcx.tcx().is_object_safe(trait_def_id) { . ProcessResult::Error(CodeSelectionError(Unimplemented)) . } else { . ProcessResult::Changed(vec![]) . } . } . . ty::PredicateKind::ClosureKind(_, closure_substs, kind) => { 1,203 ( 0.00%) match self.selcx.infcx().closure_kind(closure_substs) { . Some(closure_kind) => { 2,406 ( 0.00%) if closure_kind.extends(kind) { . ProcessResult::Changed(vec![]) . } else { . ProcessResult::Error(CodeSelectionError(Unimplemented)) . } . } . None => ProcessResult::Unchanged, . } . } . . ty::PredicateKind::WellFormed(arg) => { 186,809 ( 0.00%) match wf::obligations( . self.selcx.infcx(), 53,374 ( 0.00%) obligation.param_env, 53,374 ( 0.00%) obligation.cause.body_id, 80,061 ( 0.00%) obligation.recursion_depth + 1, . arg, . obligation.cause.span, . ) { . None => { 24,852 ( 0.00%) pending_obligation.stalled_on = 43,491 ( 0.00%) vec![TyOrConstInferVar::maybe_from_generic_arg(arg).unwrap()]; 12,426 ( 0.00%) ProcessResult::Unchanged . } 61,422 ( 0.00%) Some(os) => ProcessResult::Changed(mk_pending(os)), . } . } . . ty::PredicateKind::Subtype(subtype) => { 20,016 ( 0.00%) match self.selcx.infcx().subtype_predicate( . &obligation.cause, . obligation.param_env, . Binder::dummy(subtype), . ) { . None => { . // None means that both are unresolved. 12,205 ( 0.00%) pending_obligation.stalled_on = vec![ 2,441 ( 0.00%) TyOrConstInferVar::maybe_from_ty(subtype.a).unwrap(), 4,882 ( 0.00%) TyOrConstInferVar::maybe_from_ty(subtype.b).unwrap(), . ]; . ProcessResult::Unchanged . } . Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)), . Some(Err(err)) => { . let expected_found = . ExpectedFound::new(subtype.a_is_expected, subtype.a, subtype.b); . ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError( -- line 497 ---------------------------------------- -- line 498 ---------------------------------------- . expected_found, . err, . )) . } . } . } . . ty::PredicateKind::Coerce(coerce) => { 120 ( 0.00%) match self.selcx.infcx().coerce_predicate( . &obligation.cause, . obligation.param_env, . Binder::dummy(coerce), . ) { . None => { . // None means that both are unresolved. 20 ( 0.00%) pending_obligation.stalled_on = vec![ 4 ( 0.00%) TyOrConstInferVar::maybe_from_ty(coerce.a).unwrap(), 8 ( 0.00%) TyOrConstInferVar::maybe_from_ty(coerce.b).unwrap(), . ]; . ProcessResult::Unchanged . } . Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)), . Some(Err(err)) => { . let expected_found = ExpectedFound::new(false, coerce.a, coerce.b); . ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError( . expected_found, -- line 523 ---------------------------------------- -- line 639 ---------------------------------------- . } . } . } . ty::PredicateKind::TypeWellFormedFromEnv(..) => { . bug!("TypeWellFormedFromEnv is only used for Chalk") . } . }, . } 918,072 ( 0.01%) } . 965,732 ( 0.01%) #[instrument(level = "debug", skip(self, obligation, stalled_on))] . fn process_trait_obligation( . &mut self, . obligation: &PredicateObligation<'tcx>, . trait_obligation: TraitObligation<'tcx>, . stalled_on: &mut Vec>, . ) -> ProcessResult, FulfillmentErrorCode<'tcx>> { 50,828 ( 0.00%) let infcx = self.selcx.infcx(); 152,484 ( 0.00%) if obligation.predicate.is_global() { . // no type variables present, can use evaluation for better caching. . // FIXME: consider caching errors too. 45,482 ( 0.00%) if infcx.predicate_must_hold_considering_regions(obligation) { . debug!( . "selecting trait at depth {} evaluated to holds", . obligation.recursion_depth . ); 44,016 ( 0.00%) return ProcessResult::Changed(vec![]); . } . } . 201,734 ( 0.00%) match self.selcx.select(&trait_obligation) { . Ok(Some(impl_source)) => { . debug!("selecting trait at depth {} yielded Ok(Some)", obligation.recursion_depth); 285,570 ( 0.00%) ProcessResult::Changed(mk_pending(impl_source.nested_obligations())) . } . Ok(None) => { . debug!("selecting trait at depth {} yielded Ok(None)", obligation.recursion_depth); . . // This is a bit subtle: for the most part, the . // only reason we can fail to make progress on . // trait selection is because we don't have enough . // information about the types in the trait. . stalled_on.clear(); . stalled_on.extend(substs_infer_vars( . self.selcx, 12,952 ( 0.00%) trait_obligation.predicate.map_bound(|pred| pred.trait_ref.substs), . )); . . debug!( . "process_predicate: pending obligation {:?} now stalled on {:?}", . infcx.resolve_vars_if_possible(obligation.clone()), . stalled_on . ); . 12,952 ( 0.00%) ProcessResult::Unchanged . } . Err(selection_err) => { . debug!("selecting trait at depth {} yielded Err", obligation.recursion_depth); . 42 ( 0.00%) ProcessResult::Error(CodeSelectionError(selection_err)) . } . } . } . 85,811 ( 0.00%) fn process_projection_obligation( . &mut self, . obligation: &PredicateObligation<'tcx>, . project_obligation: PolyProjectionObligation<'tcx>, . stalled_on: &mut Vec>, . ) -> ProcessResult, FulfillmentErrorCode<'tcx>> { 7,801 ( 0.00%) let tcx = self.selcx.tcx(); . 23,403 ( 0.00%) if obligation.predicate.is_global() { . // no type variables present, can use evaluation for better caching. . // FIXME: consider caching errors too. 330 ( 0.00%) if self.selcx.infcx().predicate_must_hold_considering_regions(obligation) { 738 ( 0.00%) if let Some(key) = ProjectionCacheKey::from_poly_projection_predicate( . &mut self.selcx, 861 ( 0.00%) project_obligation.predicate, . ) { . // If `predicate_must_hold_considering_regions` succeeds, then we've . // evaluated all sub-obligations. We can therefore mark the 'root' . // obligation as complete, and skip evaluating sub-obligations. 738 ( 0.00%) self.selcx . .infcx() . .inner . .borrow_mut() . .projection_cache() . .complete(key, EvaluationResult::EvaluatedToOk); . } 246 ( 0.00%) return ProcessResult::Changed(vec![]); . } else { . tracing::debug!("Does NOT hold: {:?}", obligation); . } . } . 53,746 ( 0.00%) match project::poly_project_and_unify_type(self.selcx, &project_obligation) { . Ok(Ok(Some(os))) => ProcessResult::Changed(mk_pending(os)), . Ok(Ok(None)) => { . stalled_on.clear(); . stalled_on.extend(substs_infer_vars( . self.selcx, 3,789 ( 0.00%) project_obligation.predicate.map_bound(|pred| pred.projection_ty.substs), . )); 3,789 ( 0.00%) ProcessResult::Unchanged . } . // Let the caller handle the recursion . Ok(Err(project::InProgress)) => ProcessResult::Changed(mk_pending(vec![ . project_obligation.with(project_obligation.predicate.to_predicate(tcx)), . ])), . Err(e) => ProcessResult::Error(CodeProjectionError(e)), . } 62,408 ( 0.00%) } . } . . /// Returns the set of inference variables contained in `substs`. . fn substs_infer_vars<'a, 'tcx>( . selcx: &mut SelectionContext<'a, 'tcx>, . substs: ty::Binder<'tcx, SubstsRef<'tcx>>, . ) -> impl Iterator> { . selcx . .infcx() . .resolve_vars_if_possible(substs) . .skip_binder() // ok because this check doesn't care about regions . .iter() . .filter(|arg| arg.has_infer_types_or_consts()) . .flat_map(|arg| { 95,330 ( 0.00%) let mut walker = arg.walk(); 171,844 ( 0.00%) while let Some(c) = walker.next() { 19,116 ( 0.00%) if !c.has_infer_types_or_consts() { . walker.visited.remove(&c); 48 ( 0.00%) walker.skip_current_subtree(); . } . } . walker.visited.into_iter() . }) . .filter_map(TyOrConstInferVar::maybe_from_generic_arg) . } . . fn to_fulfillment_error<'tcx>( . error: Error, FulfillmentErrorCode<'tcx>>, . ) -> FulfillmentError<'tcx> { . let mut iter = error.backtrace.into_iter(); 3 ( 0.00%) let obligation = iter.next().unwrap().obligation; . // The root obligation is the last item in the backtrace - if there's only . // one item, then it's the same as the main obligation . let root_obligation = iter.next_back().map_or_else(|| obligation.clone(), |e| e.obligation); 90 ( 0.00%) FulfillmentError::new(obligation, error.error, root_obligation) . } 38,471,890 ( 0.22%) -------------------------------------------------------------------------------- -- 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 . // . 11,106,250 ( 0.06%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 8,329,686 ( 0.05%) 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. 435,192 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 652,788 ( 0.00%) libc::calloc(layout.size(), 1) as *mut u8 . } else { . let ptr = self.alloc(layout); . if !ptr.is_null() { . ptr::write_bytes(ptr, 0, layout.size()); . } . ptr . } . } . . #[inline] . unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { 2,885,350 ( 0.02%) libc::free(ptr as *mut libc::c_void) . } . . #[inline] . unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { 1,011,332 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 2,022,664 ( 0.01%) libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8 . } else { . realloc_fallback(self, ptr, layout, new_size) . } . } . } . . cfg_if::cfg_if! { . if #[cfg(any( -- line 56 ---------------------------------------- -- line 84 ---------------------------------------- . } else if #[cfg(target_os = "wasi")] { . #[inline] . unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { . libc::aligned_alloc(layout.align(), layout.size()) as *mut u8 . } . } else { . #[inline] . unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { 1 ( 0.00%) let mut out = ptr::null_mut(); . // posix_memalign requires that the alignment be a multiple of `sizeof(void*)`. . // Since these are all powers of 2, we can just use max. . let align = layout.align().max(crate::mem::size_of::()); 2 ( 0.00%) let ret = libc::posix_memalign(&mut out, align, layout.size()); 2 ( 0.00%) if ret != 0 { ptr::null_mut() } else { out as *mut u8 } . } . } . } 1 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs -------------------------------------------------------------------------------- Ir -- line 21 ---------------------------------------- . use rustc_target::spec::abi; . use std::borrow::Cow; . use std::cmp::Ordering; . use std::marker::PhantomData; . use std::ops::Range; . use ty::util::IntTypeExt; . . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 3 ( 0.00%) #[derive(HashStable, TypeFoldable, Lift)] . pub struct TypeAndMut<'tcx> { 17,205 ( 0.00%) pub ty: Ty<'tcx>, 86,025 ( 0.00%) pub mutbl: hir::Mutability, . } . . #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)] . #[derive(HashStable)] . /// A "free" region `fr` can be interpreted as "some region . /// at least as big as the scope `fr.scope`". . pub struct FreeRegion { 193,738 ( 0.00%) pub scope: DefId, 173,234 ( 0.00%) pub bound_region: BoundRegionKind, . } . 1,077,633 ( 0.01%) #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)] 202 ( 0.00%) #[derive(HashStable)] . pub enum BoundRegionKind { . /// An anonymous region parameter for a given fn (&T) 31,961 ( 0.00%) BrAnon(u32), . . /// Named region parameters for functions (a in &'a T) . /// . /// The `DefId` is needed to distinguish free regions in . /// the event of shadowing. 1,769 ( 0.00%) BrNamed(DefId, Symbol), . . /// Anonymous region for the implicit env pointer parameter . /// to a closure . BrEnv, . } . 2,627 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, PartialOrd, Ord)] . #[derive(HashStable)] . pub struct BoundRegion { 196,762 ( 0.00%) pub var: BoundVar, 167,790 ( 0.00%) pub kind: BoundRegionKind, . } . . impl BoundRegionKind { . pub fn is_named(&self) -> bool { . match *self { . BoundRegionKind::BrNamed(_, name) => name != kw::UnderscoreLifetime, . _ => false, . } . } . } . . /// Defines the kinds of types. . /// . /// N.B., if you change this, you'll probably want to change the corresponding . /// AST structure in `rustc_ast/src/ast.rs` as well. 31,824,071 ( 0.18%) #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable, Debug)] 407,260 ( 0.00%) #[derive(HashStable)] . #[rustc_diagnostic_item = "TyKind"] . pub enum TyKind<'tcx> { . /// The primitive boolean type. Written as `bool`. . Bool, . . /// The primitive character type; holds a Unicode scalar value . /// (a non-surrogate code point). Written as `char`. . Char, -- line 90 ---------------------------------------- -- line 99 ---------------------------------------- . Float(ty::FloatTy), . . /// Algebraic data types (ADT). For example: structures, enumerations and unions. . /// . /// InternalSubsts here, possibly against intuition, *may* contain `Param`s. . /// That is, even after substitution it is possible that there are type . /// variables. This happens when the `Adt` corresponds to an ADT . /// definition and not a concrete use of it. 4,996,677 ( 0.03%) Adt(&'tcx AdtDef, SubstsRef<'tcx>), . . /// An unsized FFI type that is opaque to Rust. Written as `extern type T`. . Foreign(DefId), . . /// The pointee of a string slice. Written as `str`. . Str, . . /// An array with the given length. Written as `[T; n]`. 24,155 ( 0.00%) Array(Ty<'tcx>, &'tcx ty::Const<'tcx>), . . /// The pointee of an array slice. Written as `[T]`. . Slice(Ty<'tcx>), . . /// A raw pointer. Written as `*mut T` or `*const T` . RawPtr(TypeAndMut<'tcx>), . . /// A reference; a pointer with an associated lifetime. Written as . /// `&'a mut T` or `&'a T`. 2,883,013 ( 0.02%) Ref(Region<'tcx>, Ty<'tcx>, hir::Mutability), . . /// The anonymous type of a function declaration/definition. Each . /// function has a unique type, which is output (for a function . /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`. . /// . /// For example the type of `bar` here: . /// . /// ```rust -- line 134 ---------------------------------------- -- line 143 ---------------------------------------- . /// . /// ```rust . /// fn foo() -> i32 { 1 } . /// let bar: fn() -> i32 = foo; . /// ``` . FnPtr(PolyFnSig<'tcx>), . . /// A trait object. Written as `dyn for<'b> Trait<'b, Assoc = u32> + Send + 'a`. 76,873 ( 0.00%) Dynamic(&'tcx List>>, ty::Region<'tcx>), . . /// The anonymous type of a closure. Used to represent the type of . /// `|a| a`. . Closure(DefId, SubstsRef<'tcx>), . . /// The anonymous type of a generator. Used to represent the type of . /// `|a| yield a`. . Generator(DefId, SubstsRef<'tcx>, hir::Movability), -- line 159 ---------------------------------------- -- line 180 ---------------------------------------- . /// The substitutions are for the generics of the function in question. . /// After typeck, the concrete type can be found in the `types` map. . Opaque(DefId, SubstsRef<'tcx>), . . /// A type parameter; for example, `T` in `fn f(x: T) {}`. . Param(ParamTy), . . /// Bound type variable, used only when preparing a trait query. 10,641 ( 0.00%) Bound(ty::DebruijnIndex, BoundTy), . . /// A placeholder type - universally quantified higher-ranked type. . Placeholder(ty::PlaceholderType), . . /// A type variable used during type checking. . Infer(InferTy), . . /// A placeholder for a type which could not be computed; this is -- line 196 ---------------------------------------- -- line 330 ---------------------------------------- . pub closure_kind_ty: T, . pub closure_sig_as_fn_ptr_ty: T, . pub tupled_upvars_ty: T, . } . . impl<'tcx> ClosureSubsts<'tcx> { . /// Construct `ClosureSubsts` from `ClosureSubstsParts`, containing `Substs` . /// for the closure parent, alongside additional closure-specific components. 45 ( 0.00%) pub fn new( . tcx: TyCtxt<'tcx>, . parts: ClosureSubstsParts<'tcx, Ty<'tcx>>, . ) -> ClosureSubsts<'tcx> { . ClosureSubsts { . substs: tcx.mk_substs( 90 ( 0.00%) parts.parent_substs.iter().copied().chain( 180 ( 0.00%) [parts.closure_kind_ty, parts.closure_sig_as_fn_ptr_ty, parts.tupled_upvars_ty] . .iter() . .map(|&ty| ty.into()), . ), . ), . } 90 ( 0.00%) } . . /// Divides the closure substs into their respective components. . /// The ordering assumed here must match that used by `ClosureSubsts::new` above. 2,469 ( 0.00%) fn split(self) -> ClosureSubstsParts<'tcx, GenericArg<'tcx>> { . match self.substs[..] { 13,928 ( 0.00%) [ 3,845 ( 0.00%) ref parent_substs @ .., 4,368 ( 0.00%) closure_kind_ty, 1,645 ( 0.00%) closure_sig_as_fn_ptr_ty, 3,424 ( 0.00%) tupled_upvars_ty, 9,876 ( 0.00%) ] => ClosureSubstsParts { . parent_substs, . closure_kind_ty, . closure_sig_as_fn_ptr_ty, . tupled_upvars_ty, . }, . _ => bug!("closure substs missing synthetics"), . } 7,407 ( 0.00%) } . . /// Returns `true` only if enough of the synthetic types are known to . /// allow using all of the methods on `ClosureSubsts` without panicking. . /// . /// Used primarily by `ty::print::pretty` to be able to handle closure . /// types that haven't had their synthetic types substituted in. 4 ( 0.00%) pub fn is_valid(self) -> bool { 8 ( 0.00%) self.substs.len() >= 3 8 ( 0.00%) && matches!(self.split().tupled_upvars_ty.expect_ty().kind(), Tuple(_)) 8 ( 0.00%) } . . /// Returns the substitutions of the closure's parent. . pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] { . self.split().parent_substs . } . . /// Returns an iterator over the list of types of captured paths by the closure. . /// In case there was a type error in figuring out the types of the captured path, an . /// empty iterator is returned. . #[inline] 1,722 ( 0.00%) pub fn upvar_tys(self) -> impl Iterator> + 'tcx { 2,111 ( 0.00%) match self.tupled_upvars_ty().kind() { . TyKind::Error(_) => None, 1,070 ( 0.00%) TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()), . TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"), . ty => bug!("Unexpected representation of upvar types tuple {:?}", ty), . } . .into_iter() . .flatten() 1,148 ( 0.00%) } . . /// Returns the tuple type representing the upvars for this closure. . #[inline] . pub fn tupled_upvars_ty(self) -> Ty<'tcx> { 12,349 ( 0.00%) self.split().tupled_upvars_ty.expect_ty() . } . . /// Returns the closure kind for this closure; may return a type . /// variable during inference. To get the closure kind during . /// inference, use `infcx.closure_kind(substs)`. 858 ( 0.00%) pub fn kind_ty(self) -> Ty<'tcx> { . self.split().closure_kind_ty.expect_ty() 1,716 ( 0.00%) } . . /// Returns the `fn` pointer type representing the closure signature for this . /// closure. . // FIXME(eddyb) this should be unnecessary, as the shallowly resolved . // type is known at the time of the creation of `ClosureSubsts`, . // see `rustc_typeck::check::closure`. 2 ( 0.00%) pub fn sig_as_fn_ptr_ty(self) -> Ty<'tcx> { . self.split().closure_sig_as_fn_ptr_ty.expect_ty() 4 ( 0.00%) } . . /// Returns the closure kind for this closure; only usable outside . /// of an inference context, because in that context we know that . /// there are no type variables. . /// . /// If you have an inference context, use `infcx.closure_kind()`. 22 ( 0.00%) pub fn kind(self) -> ty::ClosureKind { 148 ( 0.00%) self.kind_ty().to_opt_closure_kind().unwrap() 44 ( 0.00%) } . . /// Extracts the signature from the closure. 955 ( 0.00%) pub fn sig(self) -> ty::PolyFnSig<'tcx> { . let ty = self.sig_as_fn_ptr_ty(); 1,910 ( 0.00%) match ty.kind() { 3,820 ( 0.00%) ty::FnPtr(sig) => *sig, . _ => bug!("closure_sig_as_fn_ptr_ty is not a fn-ptr: {:?}", ty.kind()), . } 2,865 ( 0.00%) } . } . . /// Similar to `ClosureSubsts`; see the above documentation for more. . #[derive(Copy, Clone, Debug, TypeFoldable)] . pub struct GeneratorSubsts<'tcx> { . pub substs: SubstsRef<'tcx>, . } . -- line 448 ---------------------------------------- -- line 676 ---------------------------------------- . } . . impl<'tcx> UpvarSubsts<'tcx> { . /// Returns an iterator over the list of types of captured paths by the closure/generator. . /// In case there was a type error in figuring out the types of the captured path, an . /// empty iterator is returned. . #[inline] . pub fn upvar_tys(self) -> impl Iterator> + 'tcx { 134 ( 0.00%) let tupled_tys = match self { 179 ( 0.00%) UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(), . UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(), . }; . 291 ( 0.00%) match tupled_tys.kind() { . TyKind::Error(_) => None, 246 ( 0.00%) TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()), . TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"), . ty => bug!("Unexpected representation of upvar types tuple {:?}", ty), . } . .into_iter() . .flatten() . } . . #[inline] . pub fn tupled_upvars_ty(self) -> Ty<'tcx> { 224 ( 0.00%) match self { 262 ( 0.00%) UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(), . UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(), . } . } . } . . /// An inline const is modeled like . /// . /// const InlineConst<'l0...'li, T0...Tj, R>: R; -- line 710 ---------------------------------------- -- line 760 ---------------------------------------- . } . . /// Returns the type of this inline const. . pub fn ty(self) -> Ty<'tcx> { . self.split().ty.expect_ty() . } . } . 58,500 ( 0.00%) #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash, TyEncodable, TyDecodable)] 64,901 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub enum ExistentialPredicate<'tcx> { . /// E.g., `Iterator`. . Trait(ExistentialTraitRef<'tcx>), . /// E.g., `Iterator::Item = T`. . Projection(ExistentialProjection<'tcx>), . /// E.g., `Send`. 38 ( 0.00%) AutoTrait(DefId), . } . . impl<'tcx> ExistentialPredicate<'tcx> { . /// Compares via an ordering that will not change if modules are reordered or other changes are . /// made to the tree. In particular, this ordering is preserved across incremental compilations. 610 ( 0.00%) pub fn stable_cmp(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Ordering { . use self::ExistentialPredicate::*; 568 ( 0.00%) match (*self, *other) { . (Trait(_), Trait(_)) => Ordering::Equal, . (Projection(ref a), Projection(ref b)) => { . tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)) . } . (AutoTrait(ref a), AutoTrait(ref b)) => { . tcx.def_path_hash(*a).cmp(&tcx.def_path_hash(*b)) . } . (Trait(_), _) => Ordering::Less, . (Projection(_), Trait(_)) => Ordering::Greater, . (Projection(_), _) => Ordering::Less, . (AutoTrait(_), _) => Ordering::Greater, . } 732 ( 0.00%) } . } . . impl<'tcx> Binder<'tcx, ExistentialPredicate<'tcx>> { 7,308 ( 0.00%) pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::Predicate<'tcx> { . use crate::ty::ToPredicate; 4,060 ( 0.00%) match self.skip_binder() { . ExistentialPredicate::Trait(tr) => { . self.rebind(tr).with_self_ty(tcx, self_ty).without_const().to_predicate(tcx) . } . ExistentialPredicate::Projection(p) => { . self.rebind(p.with_self_ty(tcx, self_ty)).to_predicate(tcx) . } . ExistentialPredicate::AutoTrait(did) => { . let trait_ref = self.rebind(ty::TraitRef { . def_id: did, . substs: tcx.mk_substs_trait(self_ty, &[]), . }); . trait_ref.without_const().to_predicate(tcx) . } . } 6,496 ( 0.00%) } . } . . impl<'tcx> List>> { . /// Returns the "principal `DefId`" of this set of existential predicates. . /// . /// A Rust trait object type consists (in addition to a lifetime bound) . /// of a set of trait bounds, which are separated into any number . /// of auto-trait bounds, and at most one non-auto-trait bound. The -- line 826 ---------------------------------------- -- line 839 ---------------------------------------- . /// are the set `{Sync}`. . /// . /// It is also possible to have a "trivial" trait object that . /// consists only of auto traits, with no principal - for example, . /// `dyn Send + Sync`. In that case, the set of auto-trait bounds . /// is `{Send, Sync}`, while there is no principal. These trait objects . /// have a "trivial" vtable consisting of just the size, alignment, . /// and destructor. 864 ( 0.00%) pub fn principal(&self) -> Option>> { 5,944 ( 0.00%) self[0] 3,352 ( 0.00%) .map_bound(|this| match this { . ExistentialPredicate::Trait(tr) => Some(tr), . _ => None, 3,456 ( 0.00%) }) . .transpose() 2,592 ( 0.00%) } . 824 ( 0.00%) pub fn principal_def_id(&self) -> Option { . self.principal().map(|trait_ref| trait_ref.skip_binder().def_id) 1,648 ( 0.00%) } . . #[inline] . pub fn projection_bounds<'a>( . &'a self, . ) -> impl Iterator>> + 'a { . self.iter().filter_map(|predicate| { 36 ( 0.00%) predicate 384 ( 0.00%) .map_bound(|pred| match pred { 20 ( 0.00%) ExistentialPredicate::Projection(projection) => Some(projection), . _ => None, . }) . .transpose() . }) . } . . #[inline] . pub fn auto_traits<'a>(&'a self) -> impl Iterator + 'a { -- line 875 ---------------------------------------- -- line 886 ---------------------------------------- . /// T: Foo . /// . /// This would be represented by a trait-reference where the `DefId` is the . /// `DefId` for the trait `Foo` and the substs define `T` as parameter 0, . /// and `U` as parameter 1. . /// . /// Trait references also appear in object types like `Foo`, but in . /// that case the `Self` parameter is absent from the substitutions. 29,795 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 2,196,754 ( 0.01%) #[derive(HashStable, TypeFoldable)] . pub struct TraitRef<'tcx> { 4,253 ( 0.00%) pub def_id: DefId, 1,423,709 ( 0.01%) pub substs: SubstsRef<'tcx>, . } . . impl<'tcx> TraitRef<'tcx> { 2,404 ( 0.00%) pub fn new(def_id: DefId, substs: SubstsRef<'tcx>) -> TraitRef<'tcx> { . TraitRef { def_id, substs } 9,616 ( 0.00%) } . . /// Returns a `TraitRef` of the form `P0: Foo` where `Pi` . /// are the parameters defined on trait. 765 ( 0.00%) pub fn identity(tcx: TyCtxt<'tcx>, def_id: DefId) -> Binder<'tcx, TraitRef<'tcx>> { 340 ( 0.00%) ty::Binder::dummy(TraitRef { . def_id, 510 ( 0.00%) substs: InternalSubsts::identity_for_item(tcx, def_id), . }) 680 ( 0.00%) } . . #[inline] 9 ( 0.00%) pub fn self_ty(&self) -> Ty<'tcx> { . self.substs.type_at(0) 6 ( 0.00%) } . 11,360 ( 0.00%) pub fn from_method( . tcx: TyCtxt<'tcx>, . trait_id: DefId, . substs: SubstsRef<'tcx>, . ) -> ty::TraitRef<'tcx> { . let defs = tcx.generics_of(trait_id); . 1,420 ( 0.00%) ty::TraitRef { def_id: trait_id, substs: tcx.intern_substs(&substs[..defs.params.len()]) } 15,620 ( 0.00%) } . } . . pub type PolyTraitRef<'tcx> = Binder<'tcx, TraitRef<'tcx>>; . . impl<'tcx> PolyTraitRef<'tcx> { . pub fn self_ty(&self) -> Binder<'tcx, Ty<'tcx>> { . self.map_bound_ref(|tr| tr.self_ty()) . } . . pub fn def_id(&self) -> DefId { 4,245 ( 0.00%) self.skip_binder().def_id 1,415 ( 0.00%) } . 6,826 ( 0.00%) pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> { 13,652 ( 0.00%) self.map_bound(|trait_ref| ty::TraitPredicate { . trait_ref, . constness: ty::BoundConstness::NotConst, . polarity: ty::ImplPolarity::Positive, . }) 6,826 ( 0.00%) } . } . . /// An existential reference to a trait, where `Self` is erased. . /// For example, the trait object `Trait<'a, 'b, X, Y>` is: . /// . /// exists T. T: Trait<'a, 'b, X, Y> . /// . /// The substitutions don't include the erased `Self`, only trait . /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above). 144 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 32,162 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct ExistentialTraitRef<'tcx> { 4,196 ( 0.00%) pub def_id: DefId, 37,421 ( 0.00%) pub substs: SubstsRef<'tcx>, . } . . impl<'tcx> ExistentialTraitRef<'tcx> { 388 ( 0.00%) pub fn erase_self_ty( . tcx: TyCtxt<'tcx>, . trait_ref: ty::TraitRef<'tcx>, . ) -> ty::ExistentialTraitRef<'tcx> { . // Assert there is a Self. . trait_ref.substs.type_at(0); . . ty::ExistentialTraitRef { . def_id: trait_ref.def_id, . substs: tcx.intern_substs(&trait_ref.substs[1..]), . } 388 ( 0.00%) } . . /// Object types don't have a self type specified. Therefore, when . /// we convert the principal trait-ref into a normal trait-ref, . /// you must give *some* self type. A common choice is `mk_err()` . /// or some placeholder type. 20 ( 0.00%) pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::TraitRef<'tcx> { . // otherwise the escaping vars would be captured by the binder . // debug_assert!(!self_ty.has_escaping_bound_vars()); . 10 ( 0.00%) ty::TraitRef { def_id: self.def_id, substs: tcx.mk_substs_trait(self_ty, self.substs) } 50 ( 0.00%) } . } . . pub type PolyExistentialTraitRef<'tcx> = Binder<'tcx, ExistentialTraitRef<'tcx>>; . . impl<'tcx> PolyExistentialTraitRef<'tcx> { . pub fn def_id(&self) -> DefId { . self.skip_binder().def_id . } . . /// Object types don't have a self type specified. Therefore, when . /// we convert the principal trait-ref into a normal trait-ref, . /// you must give *some* self type. A common choice is `mk_err()` . /// or some placeholder type. 1,512 ( 0.00%) pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::PolyTraitRef<'tcx> { 1,788 ( 0.00%) self.map_bound(|trait_ref| trait_ref.with_self_ty(tcx, self_ty)) 2,016 ( 0.00%) } . } . 97,646 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 360 ( 0.00%) #[derive(HashStable)] . pub enum BoundVariableKind { . Ty(BoundTyKind), . Region(BoundRegionKind), . Const, . } . . /// Binder is a binder for higher-ranked lifetimes or types. It is part of the . /// compiler's representation for things like `for<'a> Fn(&'a isize)` . /// (which would be represented by the type `PolyTraitRef == . /// Binder<'tcx, TraitRef>`). Note that when we instantiate, . /// erase, or otherwise "discharge" these bound vars, we change the . /// type from `Binder<'tcx, T>` to just `T` (see . /// e.g., `liberate_late_bound_regions`). . /// . /// `Decodable` and `Encodable` are implemented for `Binder` using the `impl_binder_encode_decode!` macro. 78,723 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] 961,426 ( 0.01%) pub struct Binder<'tcx, T>(T, &'tcx List); . . impl<'tcx, T> Binder<'tcx, T> . where . T: TypeFoldable<'tcx>, . { . /// Wraps `value` in a binder, asserting that `value` does not . /// contain any bound vars that would be bound by the . /// binder. This is commonly used to 'inject' a value T into a . /// different binding level. 60,545 ( 0.00%) pub fn dummy(value: T) -> Binder<'tcx, T> { 321,448 ( 0.00%) assert!(!value.has_escaping_bound_vars()); 724,710 ( 0.00%) Binder(value, ty::List::empty()) 60,131 ( 0.00%) } . . pub fn bind_with_vars(value: T, vars: &'tcx List) -> Binder<'tcx, T> { . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(vars); . value.visit_with(&mut validator); . } 33,717 ( 0.00%) Binder(value, vars) . } . } . . impl<'tcx, T> Binder<'tcx, T> { . /// Skips the binder and returns the "bound" value. This is a . /// risky thing to do because it's easy to get confused about . /// De Bruijn indices and the like. It is usually better to . /// discharge the binder using `no_bound_vars` or -- line 1053 ---------------------------------------- -- line 1059 ---------------------------------------- . /// accounting. . /// . /// Some examples where `skip_binder` is reasonable: . /// . /// - extracting the `DefId` from a PolyTraitRef; . /// - comparing the self type of a PolyTraitRef to see if it is equal to . /// a type parameter `X`, since the type `X` does not reference any regions . pub fn skip_binder(self) -> T { 2,365,898 ( 0.01%) self.0 . } . . pub fn bound_vars(&self) -> &'tcx List { 1,299 ( 0.00%) self.1 . } . . pub fn as_ref(&self) -> Binder<'tcx, &T> { 6,441 ( 0.00%) Binder(&self.0, self.1) . } . . pub fn map_bound_ref_unchecked(&self, f: F) -> Binder<'tcx, U> . where . F: FnOnce(&T) -> U, . { . let value = f(&self.0); . Binder(value, self.1) -- line 1083 ---------------------------------------- -- line 1085 ---------------------------------------- . . pub fn map_bound_ref>(&self, f: F) -> Binder<'tcx, U> . where . F: FnOnce(&T) -> U, . { . self.as_ref().map_bound(f) . } . 424 ( 0.00%) pub fn map_bound>(self, f: F) -> Binder<'tcx, U> . where . F: FnOnce(T) -> U, . { 52,132 ( 0.00%) let value = f(self.0); . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(self.1); . value.visit_with(&mut validator); . } 467,882 ( 0.00%) Binder(value, self.1) 432 ( 0.00%) } . . pub fn try_map_bound, E>(self, f: F) -> Result, E> . where . F: FnOnce(T) -> Result, . { . let value = f(self.0)?; . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(self.1); . value.visit_with(&mut validator); . } 12,406 ( 0.00%) Ok(Binder(value, self.1)) . } . . /// Wraps a `value` in a binder, using the same bound variables as the . /// current `Binder`. This should not be used if the new value *changes* . /// the bound variables. Note: the (old or new) value itself does not . /// necessarily need to *name* all the bound variables. . /// . /// This currently doesn't do anything different than `bind`, because we -- line 1122 ---------------------------------------- -- line 1126 ---------------------------------------- . pub fn rebind(&self, value: U) -> Binder<'tcx, U> . where . U: TypeFoldable<'tcx>, . { . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(self.bound_vars()); . value.visit_with(&mut validator); . } 18,928 ( 0.00%) Binder(value, self.1) . } . . /// Unwraps and returns the value within, but only if it contains . /// no bound vars at all. (In other words, if this binder -- . /// and indeed any enclosing binder -- doesn't bind anything at . /// all.) Otherwise, returns `None`. . /// . /// (One could imagine having a method that just unwraps a single -- line 1142 ---------------------------------------- -- line 1143 ---------------------------------------- . /// binder, but permits late-bound vars bound by enclosing . /// binders, but that would require adjusting the debruijn . /// indices, and given the shallow binding structure we often use, . /// would not be that useful.) . pub fn no_bound_vars(self) -> Option . where . T: TypeFoldable<'tcx>, . { 418,456 ( 0.00%) if self.0.has_escaping_bound_vars() { None } else { Some(self.skip_binder()) } 955 ( 0.00%) } . . /// Splits the contents into two things that share the same binder . /// level as the original, returning two distinct binders. . /// . /// `f` should consider bound regions at depth 1 to be free, and . /// anything it produces with bound regions at depth 1 will be . /// bound in the resulting return values. . pub fn split(self, f: F) -> (Binder<'tcx, U>, Binder<'tcx, V>) -- line 1160 ---------------------------------------- -- line 1170 ---------------------------------------- . pub fn transpose(self) -> Option> { . let bound_vars = self.1; . self.0.map(|v| Binder(v, bound_vars)) . } . } . . /// Represents the projection of an associated type. In explicit UFCS . /// form this would be written `>::N`. 2,254 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 148,139 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct ProjectionTy<'tcx> { . /// The parameters of the associated item. 94,687 ( 0.00%) pub substs: SubstsRef<'tcx>, . . /// The `DefId` of the `TraitItem` for the associated type `N`. . /// . /// Note that this is not the `DefId` of the `TraitRef` containing this . /// associated type, which is in `tcx.associated_item(item_def_id).container`. 104,408 ( 0.00%) pub item_def_id: DefId, . } . . impl<'tcx> ProjectionTy<'tcx> { 41,202 ( 0.00%) pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId { 11,772 ( 0.00%) tcx.associated_item(self.item_def_id).container.id() 47,088 ( 0.00%) } . . /// Extracts the underlying trait reference and own substs from this projection. . /// For example, if this is a projection of `::Item<'a>`, . /// then this function would return a `T: Iterator` trait reference and `['a]` as the own substs 25,368 ( 0.00%) pub fn trait_ref_and_own_substs( . &self, . tcx: TyCtxt<'tcx>, . ) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) { 10,872 ( 0.00%) let def_id = tcx.associated_item(self.item_def_id).container.id(); . let trait_generics = tcx.generics_of(def_id); 18,120 ( 0.00%) ( . ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, trait_generics) }, . &self.substs[trait_generics.count()..], . ) 32,616 ( 0.00%) } . . /// Extracts the underlying trait reference from this projection. . /// For example, if this is a projection of `::Item`, . /// then this function would return a `T: Iterator` trait reference. . /// . /// WARNING: This will drop the substs for generic associated types . /// consider calling [Self::trait_ref_and_own_substs] to get those . /// as well. 52,578 ( 0.00%) pub fn trait_ref(&self, tcx: TyCtxt<'tcx>) -> ty::TraitRef<'tcx> { 5,842 ( 0.00%) let def_id = self.trait_def_id(tcx); 5,842 ( 0.00%) ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, tcx.generics_of(def_id)) } 64,262 ( 0.00%) } . 11,630 ( 0.00%) pub fn self_ty(&self) -> Ty<'tcx> { 34,890 ( 0.00%) self.substs.type_at(0) 23,260 ( 0.00%) } . } . . #[derive(Copy, Clone, Debug, TypeFoldable)] . pub struct GenSig<'tcx> { . pub resume_ty: Ty<'tcx>, . pub yield_ty: Ty<'tcx>, . pub return_ty: Ty<'tcx>, . } -- line 1233 ---------------------------------------- -- line 1235 ---------------------------------------- . pub type PolyGenSig<'tcx> = Binder<'tcx, GenSig<'tcx>>; . . /// Signature of a function type, which we have arbitrarily . /// decided to use to refer to the input/output types. . /// . /// - `inputs`: is the list of arguments and their modes. . /// - `output`: is the return type. . /// - `c_variadic`: indicates whether this is a C-variadic function. 172,411 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 99,584 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct FnSig<'tcx> { 7,846 ( 0.00%) pub inputs_and_output: &'tcx List>, 70,153 ( 0.00%) pub c_variadic: bool, 12,803 ( 0.00%) pub unsafety: hir::Unsafety, 75,837 ( 0.00%) pub abi: abi::Abi, . } . . impl<'tcx> FnSig<'tcx> { 78,082 ( 0.00%) pub fn inputs(&self) -> &'tcx [Ty<'tcx>] { 340,456 ( 0.00%) &self.inputs_and_output[..self.inputs_and_output.len() - 1] 156,164 ( 0.00%) } . 40,513 ( 0.00%) pub fn output(&self) -> Ty<'tcx> { 319,887 ( 0.00%) self.inputs_and_output[self.inputs_and_output.len() - 1] 81,026 ( 0.00%) } . . // Creates a minimal `FnSig` to be used when encountering a `TyKind::Error` in a fallible . // method. . fn fake() -> FnSig<'tcx> { . FnSig { . inputs_and_output: List::empty(), . c_variadic: false, . unsafety: hir::Unsafety::Normal, -- line 1267 ---------------------------------------- -- line 1270 ---------------------------------------- . } . } . . pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>; . . impl<'tcx> PolyFnSig<'tcx> { . #[inline] . pub fn inputs(&self) -> Binder<'tcx, &'tcx [Ty<'tcx>]> { 21,525 ( 0.00%) self.map_bound_ref_unchecked(|fn_sig| fn_sig.inputs()) . } . #[inline] . pub fn input(&self, index: usize) -> ty::Binder<'tcx, Ty<'tcx>> { 32,774 ( 0.00%) self.map_bound_ref(|fn_sig| fn_sig.inputs()[index]) . } . pub fn inputs_and_output(&self) -> ty::Binder<'tcx, &'tcx List>> { . self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output) 791 ( 0.00%) } . #[inline] . pub fn output(&self) -> ty::Binder<'tcx, Ty<'tcx>> { 17,235 ( 0.00%) self.map_bound_ref(|fn_sig| fn_sig.output()) . } . pub fn c_variadic(&self) -> bool { 1,580 ( 0.00%) self.skip_binder().c_variadic 790 ( 0.00%) } . pub fn unsafety(&self) -> hir::Unsafety { 13,536 ( 0.00%) self.skip_binder().unsafety 6,768 ( 0.00%) } . pub fn abi(&self) -> abi::Abi { 137,388 ( 0.00%) self.skip_binder().abi 34,347 ( 0.00%) } . } . . pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>; . 80 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 1,460 ( 0.00%) #[derive(HashStable)] . pub struct ParamTy { 394 ( 0.00%) pub index: u32, . pub name: Symbol, . } . . impl<'tcx> ParamTy { 158 ( 0.00%) pub fn new(index: u32, name: Symbol) -> ParamTy { . ParamTy { index, name } 79 ( 0.00%) } . . pub fn for_def(def: &ty::GenericParamDef) -> ParamTy { 60 ( 0.00%) ParamTy::new(def.index, def.name) 30 ( 0.00%) } . . #[inline] . pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { . tcx.mk_ty_param(self.index, self.name) . } . } . . #[derive(Copy, Clone, Hash, TyEncodable, TyDecodable, Eq, PartialEq, Ord, PartialOrd)] 53 ( 0.00%) #[derive(HashStable)] . pub struct ParamConst { 266 ( 0.00%) pub index: u32, 266 ( 0.00%) pub name: Symbol, . } . . impl ParamConst { . pub fn new(index: u32, name: Symbol) -> ParamConst { . ParamConst { index, name } . } . . pub fn for_def(def: &ty::GenericParamDef) -> ParamConst { -- line 1338 ---------------------------------------- -- line 1440 ---------------------------------------- . /// the inference variable is supposed to satisfy the relation . /// *for every value of the placeholder region*. To ensure that doesn't . /// happen, you can use `leak_check`. This is more clearly explained . /// by the [rustc dev guide]. . /// . /// [1]: https://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/ . /// [2]: https://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/ . /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/hrtb.html 10,412,000 ( 0.06%) #[derive(Clone, PartialEq, Eq, Hash, Copy, TyEncodable, TyDecodable, PartialOrd, Ord)] 2,914 ( 0.00%) pub enum RegionKind { . /// Region bound in a type or fn declaration which will be . /// substituted 'early' -- that is, at the same time when type . /// parameters are substituted. . ReEarlyBound(EarlyBoundRegion), . . /// Region bound in a function scope, which will be substituted when the . /// function is called. 334,458 ( 0.00%) ReLateBound(ty::DebruijnIndex, BoundRegion), . . /// When checking a function body, the types of all arguments and so forth . /// that refer to bound region parameters are modified to refer to free . /// region parameters. . ReFree(FreeRegion), . . /// Static data that has an "infinite" lifetime. Top in the region lattice. . ReStatic, -- line 1465 ---------------------------------------- -- line 1478 ---------------------------------------- . /// regions visible from `U`, but not less than regions not visible . /// from `U`. . ReEmpty(ty::UniverseIndex), . . /// Erased region, used by trait selection, in MIR and during codegen. . ReErased, . } . 31,442 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, PartialOrd, Ord)] . pub struct EarlyBoundRegion { 194,682 ( 0.00%) pub def_id: DefId, 185,765 ( 0.00%) pub index: u32, 180,150 ( 0.00%) pub name: Symbol, . } . . /// A **`const`** **v**ariable **ID**. . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] . pub struct ConstVid<'tcx> { 5,602 ( 0.00%) pub index: u32, 768 ( 0.00%) pub phantom: PhantomData<&'tcx ()>, . } . . rustc_index::newtype_index! { . /// A **region** (lifetime) **v**ariable **ID**. . pub struct RegionVid { . DEBUG_FORMAT = custom, . } . } -- line 1505 ---------------------------------------- -- line 1513 ---------------------------------------- . rustc_index::newtype_index! { . pub struct BoundVar { .. } . } . . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub struct BoundTy { . pub var: BoundVar, 10,641 ( 0.00%) pub kind: BoundTyKind, . } . 181,020 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub enum BoundTyKind { . Anon, . Param(Symbol), . } . . impl From for BoundTy { . fn from(var: BoundVar) -> Self { . BoundTy { var, kind: BoundTyKind::Anon } . } . } . . /// A `ProjectionPredicate` for an `ExistentialTraitRef`. . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 379 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct ExistentialProjection<'tcx> { 156 ( 0.00%) pub item_def_id: DefId, 396 ( 0.00%) pub substs: SubstsRef<'tcx>, 99 ( 0.00%) pub term: Term<'tcx>, . } . . pub type PolyExistentialProjection<'tcx> = Binder<'tcx, ExistentialProjection<'tcx>>; . . impl<'tcx> ExistentialProjection<'tcx> { . /// Extracts the underlying existential trait reference from this projection. . /// For example, if this is a projection of `exists T. ::Item == X`, . /// then this function would return an `exists T. T: Iterator` existential trait -- line 1551 ---------------------------------------- -- line 1585 ---------------------------------------- . item_def_id: projection_predicate.projection_ty.item_def_id, . substs: tcx.intern_substs(&projection_predicate.projection_ty.substs[1..]), . term: projection_predicate.term, . } . } . } . . impl<'tcx> PolyExistentialProjection<'tcx> { 30 ( 0.00%) pub fn with_self_ty( . &self, . tcx: TyCtxt<'tcx>, . self_ty: Ty<'tcx>, . ) -> ty::PolyProjectionPredicate<'tcx> { 30 ( 0.00%) self.map_bound(|p| p.with_self_ty(tcx, self_ty)) 36 ( 0.00%) } . . pub fn item_def_id(&self) -> DefId { 12 ( 0.00%) self.skip_binder().item_def_id 6 ( 0.00%) } . } . . /// Region utilities . impl RegionKind { . /// Is this region named by the user? . pub fn has_name(&self) -> bool { . match *self { . RegionKind::ReEarlyBound(ebr) => ebr.has_name(), -- line 1611 ---------------------------------------- -- line 1616 ---------------------------------------- . RegionKind::RePlaceholder(placeholder) => placeholder.name.is_named(), . RegionKind::ReEmpty(_) => false, . RegionKind::ReErased => false, . } . } . . #[inline] . pub fn is_late_bound(&self) -> bool { 13,432 ( 0.00%) matches!(*self, ty::ReLateBound(..)) . } . . #[inline] . pub fn is_placeholder(&self) -> bool { . matches!(*self, ty::RePlaceholder(..)) . } . . #[inline] . pub fn bound_at_or_above_binder(&self, index: ty::DebruijnIndex) -> bool { 320,864 ( 0.00%) match *self { . ty::ReLateBound(debruijn, _) => debruijn >= index, . _ => false, . } . } . . pub fn type_flags(&self) -> TypeFlags { . let mut flags = TypeFlags::empty(); . 651,111 ( 0.00%) match *self { . ty::ReVar(..) => { . flags = flags | TypeFlags::HAS_FREE_REGIONS; . flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS; . flags = flags | TypeFlags::HAS_RE_INFER; . } . ty::RePlaceholder(..) => { . flags = flags | TypeFlags::HAS_FREE_REGIONS; . flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS; -- line 1651 ---------------------------------------- -- line 1669 ---------------------------------------- . ty::ReErased => { . flags = flags | TypeFlags::HAS_RE_ERASED; . } . } . . debug!("type_flags({:?}) = {:?}", self, flags); . . flags 42,801 ( 0.00%) } . . /// Given an early-bound or free region, returns the `DefId` where it was bound. . /// For example, consider the regions in this snippet of code: . /// . /// ``` . /// impl<'a> Foo { . /// ^^ -- early bound, declared on an impl . /// -- line 1685 ---------------------------------------- -- line 1713 ---------------------------------------- . . #[inline(always)] . pub fn flags(&self) -> TypeFlags { . self.flags . } . . #[inline] . pub fn is_unit(&self) -> bool { 7,108 ( 0.00%) match self.kind() { 1,392 ( 0.00%) Tuple(ref tys) => tys.is_empty(), . _ => false, . } . } . . #[inline] . pub fn is_never(&self) -> bool { 120,440 ( 0.00%) matches!(self.kind(), Never) . } . . #[inline] . pub fn is_primitive(&self) -> bool { . self.kind().is_primitive() . } . . #[inline] -- line 1737 ---------------------------------------- -- line 1741 ---------------------------------------- . . #[inline] . pub fn is_ref(&self) -> bool { . matches!(self.kind(), Ref(..)) . } . . #[inline] . pub fn is_ty_var(&self) -> bool { 158,427 ( 0.00%) matches!(self.kind(), Infer(TyVar(_))) . } . . #[inline] . pub fn ty_vid(&self) -> Option { 141,566 ( 0.00%) match self.kind() { 30,149 ( 0.00%) &Infer(TyVar(vid)) => Some(vid), . _ => None, . } . } . . #[inline] . pub fn is_ty_infer(&self) -> bool { 135 ( 0.00%) matches!(self.kind(), Infer(_)) . } . . #[inline] . pub fn is_phantom_data(&self) -> bool { . if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false } . } . . #[inline] . pub fn is_bool(&self) -> bool { 24 ( 0.00%) *self.kind() == Bool . } . . /// Returns `true` if this type is a `str`. . #[inline] . pub fn is_str(&self) -> bool { . *self.kind() == Str . } . . #[inline] . pub fn is_param(&self, index: u32) -> bool { 179 ( 0.00%) match self.kind() { . ty::Param(ref data) => data.index == index, . _ => false, . } . } . . #[inline] . pub fn is_slice(&self) -> bool { . match self.kind() { . RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => matches!(ty.kind(), Slice(_) | Str), . _ => false, . } . } . . #[inline] . pub fn is_array(&self) -> bool { 165 ( 0.00%) matches!(self.kind(), Array(..)) . } . . #[inline] . pub fn is_simd(&self) -> bool { 12 ( 0.00%) match self.kind() { 5 ( 0.00%) Adt(def, _) => def.repr.simd(), . _ => false, . } . } . 190 ( 0.00%) pub fn sequence_element_type(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 380 ( 0.00%) match self.kind() { . Array(ty, _) | Slice(ty) => ty, . Str => tcx.mk_mach_uint(ty::UintTy::U8), . _ => bug!("`sequence_element_type` called on non-sequence value: {}", self), . } 190 ( 0.00%) } . 35 ( 0.00%) pub fn simd_size_and_type(&self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) { 10 ( 0.00%) match self.kind() { . Adt(def, substs) => { 10 ( 0.00%) assert!(def.repr.simd(), "`simd_size_and_type` called on non-SIMD type"); . let variant = def.non_enum_variant(); 20 ( 0.00%) let f0_ty = variant.fields[0].ty(tcx, substs); . 10 ( 0.00%) match f0_ty.kind() { . // If the first field is an array, we assume it is the only field and its . // elements are the SIMD components. . Array(f0_elem_ty, f0_len) => { . // FIXME(repr_simd): https://github.com/rust-lang/rust/pull/78863#discussion_r522784112 . // The way we evaluate the `N` in `[T; N]` here only works since we use . // `simd_size_and_type` post-monomorphization. It will probably start to ICE . // if we use it in generic code. See the `simd-array-trait` ui test. . (f0_len.eval_usize(tcx, ParamEnv::empty()) as u64, f0_elem_ty) . } . // Otherwise, the fields of this Adt are the SIMD components (and we assume they . // all have the same type). 10 ( 0.00%) _ => (variant.fields.len() as u64, f0_ty), . } . } . _ => bug!("`simd_size_and_type` called on invalid type"), . } 45 ( 0.00%) } . . #[inline] . pub fn is_region_ptr(&self) -> bool { 96 ( 0.00%) matches!(self.kind(), Ref(..)) . } . . #[inline] . pub fn is_mutable_ptr(&self) -> bool { . matches!( . self.kind(), . RawPtr(TypeAndMut { mutbl: hir::Mutability::Mut, .. }) . | Ref(_, _, hir::Mutability::Mut) -- line 1854 ---------------------------------------- -- line 1861 ---------------------------------------- . match self.kind() { . Ref(_, _, mutability) => Some(*mutability), . _ => None, . } . } . . #[inline] . pub fn is_unsafe_ptr(&self) -> bool { 17,183 ( 0.00%) matches!(self.kind(), RawPtr(_)) . } . . /// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer). . #[inline] . pub fn is_any_ptr(&self) -> bool { 42 ( 0.00%) self.is_region_ptr() || self.is_unsafe_ptr() || self.is_fn_ptr() . } . . #[inline] . pub fn is_box(&self) -> bool { 155,596 ( 0.00%) match self.kind() { 43,045 ( 0.00%) Adt(def, _) => def.is_box(), . _ => false, . } . } . . /// Panics if called on any type other than `Box`. 2,136 ( 0.00%) pub fn boxed_ty(&self) -> Ty<'tcx> { 2,136 ( 0.00%) match self.kind() { 5,340 ( 0.00%) Adt(def, substs) if def.is_box() => substs.type_at(0), . _ => bug!("`boxed_ty` is called on non-box type {:?}", self), . } 2,136 ( 0.00%) } . . /// A scalar type is one that denotes an atomic datum, with no sub-components. . /// (A RawPtr is scalar because it represents a non-managed pointer, so its . /// contents are abstract to rustc.) . #[inline] . pub fn is_scalar(&self) -> bool { 1,413 ( 0.00%) matches!( 3,165 ( 0.00%) self.kind(), . Bool | Char . | Int(_) . | Float(_) . | Uint(_) . | FnDef(..) . | FnPtr(_) . | RawPtr(_) . | Infer(IntVar(_) | FloatVar(_)) . ) . } . . /// Returns `true` if this type is a floating point type. . #[inline] . pub fn is_floating_point(&self) -> bool { 3,276 ( 0.00%) matches!(self.kind(), Float(_) | Infer(FloatVar(_))) . } . . #[inline] . pub fn is_trait(&self) -> bool { 1,537 ( 0.00%) matches!(self.kind(), Dynamic(..)) . } . . #[inline] . pub fn is_enum(&self) -> bool { 7,956 ( 0.00%) matches!(self.kind(), Adt(adt_def, _) if adt_def.is_enum()) . } . . #[inline] . pub fn is_union(&self) -> bool { 36,245 ( 0.00%) matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union()) . } . . #[inline] . pub fn is_closure(&self) -> bool { 6,392 ( 0.00%) matches!(self.kind(), Closure(..)) . } . . #[inline] . pub fn is_generator(&self) -> bool { 11,074 ( 0.00%) matches!(self.kind(), Generator(..)) . } . . #[inline] . pub fn is_integral(&self) -> bool { 17,671 ( 0.00%) matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_)) . } . . #[inline] . pub fn is_fresh_ty(&self) -> bool { . matches!(self.kind(), Infer(FreshTy(_))) . } . . #[inline] . pub fn is_fresh(&self) -> bool { 4,754 ( 0.00%) matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_))) . } . . #[inline] . pub fn is_char(&self) -> bool { . matches!(self.kind(), Char) . } . . #[inline] . pub fn is_numeric(&self) -> bool { . self.is_integral() || self.is_floating_point() . } . . #[inline] . pub fn is_signed(&self) -> bool { 992 ( 0.00%) matches!(self.kind(), Int(_)) . } . . #[inline] . pub fn is_ptr_sized_integral(&self) -> bool { 6,210 ( 0.00%) matches!(self.kind(), Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize)) . } . . #[inline] . pub fn has_concrete_skeleton(&self) -> bool { . !matches!(self.kind(), Param(_) | Infer(_) | Error(_)) . } . . /// Returns the type and mutability of `*ty`. . /// . /// The parameter `explicit` indicates if this is an *explicit* dereference. . /// Some types -- notably unsafe ptrs -- can only be dereferenced explicitly. 38,127 ( 0.00%) pub fn builtin_deref(&self, explicit: bool) -> Option> { 232,156 ( 0.00%) match self.kind() { 2,928 ( 0.00%) Adt(def, _) if def.is_box() => { 1,856 ( 0.00%) Some(TypeAndMut { ty: self.boxed_ty(), mutbl: hir::Mutability::Not }) . } 141,234 ( 0.00%) Ref(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl: *mutbl }), 3,932 ( 0.00%) RawPtr(mt) if explicit => Some(*mt), . _ => None, . } 76,254 ( 0.00%) } . . /// Returns the type of `ty[i]`. . pub fn builtin_index(&self) -> Option> { 300 ( 0.00%) match self.kind() { . Array(ty, _) | Slice(ty) => Some(ty), . _ => None, . } 66 ( 0.00%) } . 407,160 ( 0.00%) pub fn fn_sig(&self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> { 203,580 ( 0.00%) match self.kind() { 152,364 ( 0.00%) FnDef(def_id, substs) => tcx.fn_sig(*def_id).subst(tcx, substs), 535 ( 0.00%) FnPtr(f) => *f, . Error(_) => { . // ignore errors (#54954) . ty::Binder::dummy(FnSig::fake()) . } . Closure(..) => bug!( . "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`", . ), . _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self), . } 458,055 ( 0.00%) } . . #[inline] . pub fn is_fn(&self) -> bool { 19,047 ( 0.00%) matches!(self.kind(), FnDef(..) | FnPtr(_)) . } . . #[inline] . pub fn is_fn_ptr(&self) -> bool { . matches!(self.kind(), FnPtr(_)) . } . . #[inline] . pub fn is_impl_trait(&self) -> bool { . matches!(self.kind(), Opaque(..)) . } . . #[inline] . pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> { 14,851 ( 0.00%) match self.kind() { . Adt(adt, _) => Some(adt), . _ => None, . } . } . . /// Iterates over tuple fields. . /// Panics when called on anything but a tuple. 756 ( 0.00%) pub fn tuple_fields(&self) -> impl DoubleEndedIterator> { 6,722 ( 0.00%) match self.kind() { 4,459 ( 0.00%) Tuple(substs) => substs.iter().map(|field| field.expect_ty()), . _ => bug!("tuple_fields called on non-tuple"), . } 1,512 ( 0.00%) } . . /// Get the `i`-th element of a tuple. . /// Panics when called on anything but a tuple. 104 ( 0.00%) pub fn tuple_element_ty(&self, i: usize) -> Option> { 208 ( 0.00%) match self.kind() { 208 ( 0.00%) Tuple(substs) => substs.iter().nth(i).map(|field| field.expect_ty()), . _ => bug!("tuple_fields called on non-tuple"), . } 208 ( 0.00%) } . . /// If the type contains variants, returns the valid range of variant indices. . // . // FIXME: This requires the optimized MIR in the case of generators. . #[inline] . pub fn variant_range(&self, tcx: TyCtxt<'tcx>) -> Option> { . match self.kind() { . TyKind::Adt(adt, _) => Some(adt.variant_range()), -- line 2068 ---------------------------------------- -- line 2073 ---------------------------------------- . } . } . . /// If the type contains variants, returns the variant for `variant_index`. . /// Panics if `variant_index` is out of range. . // . // FIXME: This requires the optimized MIR in the case of generators. . #[inline] 43,600 ( 0.00%) pub fn discriminant_for_variant( . &self, . tcx: TyCtxt<'tcx>, . variant_index: VariantIdx, . ) -> Option> { 68,146 ( 0.00%) match self.kind() { 30,460 ( 0.00%) TyKind::Adt(adt, _) if adt.variants.is_empty() => { . // This can actually happen during CTFE, see . // https://github.com/rust-lang/rust/issues/89765. . None . } 15,230 ( 0.00%) TyKind::Adt(adt, _) if adt.is_enum() => { . Some(adt.discriminant_for_variant(tcx, variant_index)) . } . TyKind::Generator(def_id, substs, _) => { . Some(substs.as_generator().discriminant_for_variant(*def_id, tcx, variant_index)) . } . _ => None, . } 34,880 ( 0.00%) } . . /// Returns the type of the discriminant of this type. 67,980 ( 0.00%) pub fn discriminant_ty(&'tcx self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 33,990 ( 0.00%) match self.kind() { 54,384 ( 0.00%) ty::Adt(adt, _) if adt.is_enum() => adt.repr.discr_type().to_ty(tcx), . ty::Generator(_, substs, _) => substs.as_generator().discr_ty(tcx), . . ty::Param(_) | ty::Projection(_) | ty::Opaque(..) | ty::Infer(ty::TyVar(_)) => { . let assoc_items = tcx.associated_item_def_ids( . tcx.require_lang_item(hir::LangItem::DiscriminantKind, None), . ); . tcx.mk_projection(assoc_items[0], tcx.intern_substs(&[self.into()])) . } -- line 2113 ---------------------------------------- -- line 2135 ---------------------------------------- . | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8, . . ty::Bound(..) . | ty::Placeholder(_) . | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("`discriminant_ty` applied to unexpected type: {:?}", self) . } . } 54,384 ( 0.00%) } . . /// Returns the type of metadata for (potentially fat) pointers to this type. 378 ( 0.00%) pub fn ptr_metadata_ty( . &'tcx self, . tcx: TyCtxt<'tcx>, . normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>, . ) -> Ty<'tcx> { 378 ( 0.00%) let tail = tcx.struct_tail_with_normalize(self, normalize); 210 ( 0.00%) match tail.kind() { . // Sized types . ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) . | ty::Uint(_) . | ty::Int(_) . | ty::Bool . | ty::Float(_) . | ty::FnDef(..) . | ty::FnPtr(_) -- line 2160 ---------------------------------------- -- line 2170 ---------------------------------------- . | ty::Foreign(..) . // If returned by `struct_tail_without_normalization` this is a unit struct . // without any fields, or not a struct, and therefore is Sized. . | ty::Adt(..) . // If returned by `struct_tail_without_normalization` this is the empty tuple, . // a.k.a. unit type, which is Sized . | ty::Tuple(..) => tcx.types.unit, . 84 ( 0.00%) ty::Str | ty::Slice(_) => tcx.types.usize, . ty::Dynamic(..) => { . let dyn_metadata = tcx.lang_items().dyn_metadata().unwrap(); . tcx.type_of(dyn_metadata).subst(tcx, &[tail.into()]) . }, . . ty::Projection(_) . | ty::Param(_) . | ty::Opaque(..) . | ty::Infer(ty::TyVar(_)) . | ty::Bound(..) . | ty::Placeholder(..) . | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("`ptr_metadata_ty` applied to unexpected type: {:?}", tail) . } . } 336 ( 0.00%) } . . /// When we create a closure, we record its kind (i.e., what trait . /// it implements) into its `ClosureSubsts` using a type . /// parameter. This is kind of a phantom type, except that the . /// most convenient thing for us to are the integral types. This . /// function converts such a special type into the closure . /// kind. To go the other way, use . /// `tcx.closure_kind_ty(closure_kind)`. . /// . /// Note that during type checking, we use an inference variable . /// to represent the closure kind, because it has not yet been . /// inferred. Once upvar inference (in `rustc_typeck/src/check/upvar.rs`) . /// is complete, that type variable will be unified. 2,420 ( 0.00%) pub fn to_opt_closure_kind(&self) -> Option { 4,840 ( 0.00%) match self.kind() { 4,808 ( 0.00%) Int(int_ty) => match int_ty { . ty::IntTy::I8 => Some(ty::ClosureKind::Fn), . ty::IntTy::I16 => Some(ty::ClosureKind::FnMut), . ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce), . _ => bug!("cannot convert type `{:?}` to a closure kind", self), . }, . . // "Bound" types appear in canonical queries when the . // closure type is not yet known . Bound(..) | Infer(_) => None, . . Error(_) => Some(ty::ClosureKind::Fn), . . _ => bug!("cannot convert type `{:?}` to a closure kind", self), . } 2,420 ( 0.00%) } . . /// Fast path helper for testing if a type is `Sized`. . /// . /// Returning true means the type is known to be sized. Returning . /// `false` means nothing -- could be sized, might not be. . /// . /// Note that we could never rely on the fact that a type such as `[_]` is . /// trivially `!Sized` because we could be in a type environment with a . /// bound such as `[_]: Copy`. A function with such a bound obviously never . /// can be called, but that doesn't mean it shouldn't typecheck. This is why . /// this method doesn't return `Option`. 714,906 ( 0.00%) pub fn is_trivially_sized(&self, tcx: TyCtxt<'tcx>) -> bool { 476,604 ( 0.00%) match self.kind() { . ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) . | ty::Uint(_) . | ty::Int(_) . | ty::Bool . | ty::Float(_) . | ty::FnDef(..) . | ty::FnPtr(_) . | ty::RawPtr(..) -- line 2246 ---------------------------------------- -- line 2250 ---------------------------------------- . | ty::GeneratorWitness(..) . | ty::Array(..) . | ty::Closure(..) . | ty::Never . | ty::Error(_) => true, . . ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => false, . 6,513 ( 0.00%) ty::Tuple(tys) => tys.iter().all(|ty| ty.expect_ty().is_trivially_sized(tcx)), . 95,067 ( 0.00%) ty::Adt(def, _substs) => def.sized_constraint(tcx).is_empty(), . . ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => false, . . ty::Infer(ty::TyVar(_)) => false, . . ty::Bound(..) . | ty::Placeholder(..) . | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("`is_trivially_sized` applied to unexpected type: {:?}", self) . } . } 714,906 ( 0.00%) } . } . . /// Extra information about why we ended up with a particular variance. . /// This is only used to add more information to error messages, and . /// has no effect on soundness. While choosing the 'wrong' `VarianceDiagInfo` . /// may lead to confusing notes in error messages, it will never cause . /// a miscompilation or unsoundness. . /// . /// When in doubt, use `VarianceDiagInfo::default()` 135 ( 0.00%) #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] . pub enum VarianceDiagInfo<'tcx> { . /// No additional information - this is the default. . /// We will not add any additional information to error messages. . #[default] . None, . /// We switched our variance because a generic argument occurs inside . /// the invariant generic argument of another type. . Invariant { -- line 2290 ---------------------------------------- -- line 2295 ---------------------------------------- . /// (e.g. `0` for `*mut T`, `1` for `MyStruct<'CovariantParam, 'InvariantParam>`) . param_index: u32, . }, . } . . impl<'tcx> VarianceDiagInfo<'tcx> { . /// Mirrors `Variance::xform` - used to 'combine' the existing . /// and new `VarianceDiagInfo`s when our variance changes. 121,946 ( 0.00%) pub fn xform(self, other: VarianceDiagInfo<'tcx>) -> VarianceDiagInfo<'tcx> { . // For now, just use the first `VarianceDiagInfo::Invariant` that we see 182,919 ( 0.00%) match self { . VarianceDiagInfo::None => other, . VarianceDiagInfo::Invariant { .. } => self, . } 60,973 ( 0.00%) } . } 41,968,126 ( 0.24%) -------------------------------------------------------------------------------- -- 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 { 6,512,664 ( 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)); 385,001 ( 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::()); 130,758,290 ( 0.74%) 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" . ); . 906,594 ( 0.01%) self.stride += Group::WIDTH; 906,594 ( 0.01%) self.pos += self.stride; 770,083 ( 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. 361,542 ( 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. 783,285 ( 0.00%) return Some(if cap < 4 { 4 } else { 8 }); . } . . // Otherwise require 1/8 buckets to be empty (87.5% load) . // . // Be careful when modifying this, calculate_layout relies on the . // overflow check here. 144,684 ( 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,003,505 ( 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. 246,265 ( 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 = 739,632 ( 0.00%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 984,669 ( 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 { 10,362 ( 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 { 1,086 ( 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 { 415 ( 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 { 31,852 ( 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")] 76,609 ( 0.00%) pub unsafe fn erase_no_drop(&mut self, item: &Bucket) { 76,609 ( 0.00%) let index = self.bucket_index(item); . self.table.erase(index); 153,218 ( 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. 58,140 ( 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 { 95,078 ( 0.00%) self.erase_no_drop(&item); 360 ( 0.00%) item.read() . } . . /// Finds and removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] 2,106,811 ( 0.01%) pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option { . // Avoid `Option::map` because it bloats LLVM IR. 5,990 ( 0.00%) match self.find(hash, eq) { 43,662 ( 0.00%) Some(bucket) => Some(unsafe { self.remove(bucket) }), 517,832 ( 0.00%) None => None, . } 2,888,172 ( 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) { 34,430 ( 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,095,904 ( 0.01%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 633,572 ( 0.00%) if self . .reserve_rehash(additional, hasher, Fallibility::Infallible) . .is_err() . { . unsafe { hint::unreachable_unchecked() } . } . } . } . -- line 660 ---------------------------------------- -- line 671 ---------------------------------------- . } else { . Ok(()) . } . } . . /// Out-of-line slow path for `reserve` and `try_reserve`. . #[cold] . #[inline(never)] 1,436,706 ( 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,072,856 ( 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)] 7,392,780 ( 0.04%) pub fn insert(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> Bucket { . unsafe { . let mut index = self.table.find_insert_slot(hash); . . // We can avoid growing the table once we have reached our load . // factor if we are replacing a tombstone. This works since the . // number of EMPTY slots does not change in this case. 13,888 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 6,203,520 ( 0.04%) if unlikely(self.table.growth_left == 0 && special_is_empty(old_ctrl)) { . self.reserve(1, hasher); . index = self.table.find_insert_slot(hash); . } . . self.table.record_item_insert_at(index, old_ctrl, hash); . . let bucket = self.bucket(index); 2 ( 0.00%) bucket.write(value); . bucket . } 5,454,181 ( 0.03%) } . . /// Attempts to insert a new element without growing the table and return its raw bucket. . /// . /// Returns an `Err` containing the given element if inserting it would require growing the . /// table. . /// . /// This does not check if the given element already exists in the table. . #[cfg(feature = "raw")] -- line 749 ---------------------------------------- -- line 760 ---------------------------------------- . } . } . } . . /// Inserts a new element into the table, and returns a mutable reference to it. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 3,133,944 ( 0.02%) pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T { 318 ( 0.00%) unsafe { self.insert(hash, value, hasher).as_mut() } 2,350,458 ( 0.01%) } . . /// Inserts a new element into the table, without growing the table. . /// . /// There must be enough space in the table to insert the new element. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] . #[cfg(any(feature = "raw", feature = "rustc-internal-api"))] 21,354 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 1,016,527 ( 0.01%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 44,242 ( 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,199,895 ( 0.01%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 1,757,501 ( 0.01%) self.table.items += 1; . bucket 42,623 ( 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] 186,199 ( 0.00%) pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { 29,528 ( 0.00%) let result = self.table.find_inner(hash, &mut |index| unsafe { 70,212 ( 0.00%) eq(self.bucket(index).as_ref()) 11,533 ( 0.00%) }); . . // Avoid `Option::map` because it bloats LLVM IR. . match result { 4,137 ( 0.00%) Some(index) => Some(unsafe { self.bucket(index) }), . None => None, . } 211,368 ( 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. 91,344 ( 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] 23,744 ( 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. 96,438 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_mut() }), . None => None, . } 27,136 ( 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,452,936 ( 0.02%) self.len() == 0 . } . . /// Returns the number of buckets in the table. . #[inline] . pub fn buckets(&self) -> usize { . self.table.bucket_mask + 1 . } . . /// Returns an iterator over every element in the table. It is up to . /// the caller to ensure that the `RawTable` outlives the `RawIter`. . /// Because we cannot make the `next` method unsafe on the `RawIter` . /// struct, we have to make the `iter` method unsafe. . #[inline] . pub unsafe fn iter(&self) -> RawIter { 74 ( 0.00%) let data = Bucket::from_base_index(self.data_end(), 0); . RawIter { . iter: RawIterRange::new(self.table.ctrl.as_ptr(), data, self.table.buckets()), 394,234 ( 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(); 15,624 ( 0.00%) let allocation = self.into_allocation(); 11,718 ( 0.00%) RawIntoIter { 19,530 ( 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)> { 7,310 ( 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(( 1,137 ( 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 { 2,253,198 ( 0.01%) Self { . // Be careful to cast the entire slice to a raw pointer. . ctrl: unsafe { NonNull::new_unchecked(Group::static_empty() as *const _ as *mut u8) }, . bucket_mask: 0, . items: 0, . growth_left: 0, . alloc, . } . } . } . . impl RawTableInner { . #[cfg_attr(feature = "inline-more", inline)] 1,299,780 ( 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()); . } . 312,032 ( 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)); 713,682 ( 0.00%) Ok(Self { . ctrl, 299,801 ( 0.00%) bucket_mask: buckets - 1, . items: 0, . growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 945,818 ( 0.01%) } . . #[inline] 109,636 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 27,994 ( 0.00%) if capacity == 0 { 15,940 ( 0.00%) Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = . capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 589,231 ( 0.00%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; . result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 63,922 ( 0.00%) Ok(result) . } . } 109,636 ( 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] 363,712 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { . let index = self.find_insert_slot(hash); 363,712 ( 0.00%) let old_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . (index, old_ctrl) 727,424 ( 0.00%) } . . /// Searches for an empty or deleted bucket which is suitable for inserting . /// a new element. . /// . /// There must be at least 1 empty bucket in the table. . #[inline] . fn find_insert_slot(&self, hash: u64) -> usize { . let mut probe_seq = self.probe_seq(hash); . loop { . unsafe { . let group = Group::load(self.ctrl(probe_seq.pos)); 4,178,957 ( 0.02%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 12,183,916 ( 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,609,373 ( 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); . 362,120 ( 0.00%) loop { . let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 14,150,481 ( 0.08%) for bit in group.match_byte(h2_hash) { 27,983,552 ( 0.16%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 19,857,652 ( 0.11%) if likely(eq(index)) { . return Some(index); . } . } . 4,168,861 ( 0.02%) if likely(group.match_empty().any_bit_set()) { . return None; . } . . probe_seq.move_next(self.bucket_mask); . } . } . . #[allow(clippy::mut_mut)] . #[inline] . unsafe fn prepare_rehash_in_place(&mut self) { . // Bulk convert all full control bytes to DELETED, and all DELETED . // control bytes to EMPTY. This effectively frees up all buckets . // containing a DELETED entry. 21 ( 0.00%) for i in (0..self.buckets()).step_by(Group::WIDTH) { . let group = Group::load_aligned(self.ctrl(i)); . let group = group.convert_special_to_empty_and_full_to_deleted(); . group.store_aligned(self.ctrl(i)); . } . . // Fix up the trailing control bytes. See the comments in set_ctrl . // for the handling of tables smaller than the group width. 21 ( 0.00%) if self.buckets() < Group::WIDTH { . self.ctrl(0) . .copy_to(self.ctrl(Group::WIDTH), self.buckets()); . } else { . self.ctrl(0) . .copy_to(self.ctrl(self.buckets()), Group::WIDTH); . } . } . -- line 1220 ---------------------------------------- -- line 1225 ---------------------------------------- . Bucket::from_base_index(self.data_end(), index) . } . . #[inline] . unsafe fn bucket_ptr(&self, index: usize, size_of: usize) -> *mut u8 { . debug_assert_ne!(self.bucket_mask, 0); . debug_assert!(index < self.buckets()); . let base: *mut u8 = self.data_end().as_ptr(); 16,152,816 ( 0.09%) 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 { 76,518,619 ( 0.43%) 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) { 7,760,258 ( 0.04%) self.growth_left -= special_is_empty(old_ctrl) as usize; . self.set_ctrl_h2(index, hash); 6,198,072 ( 0.04%) 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; 228 ( 0.00%) probe_index(i) == probe_index(new_i) . } . . /// Sets a control byte to the hash, and possibly also the replicated control byte at . /// the end of the array. . #[inline] . unsafe fn set_ctrl_h2(&self, index: usize, hash: u64) { . self.set_ctrl(index, h2(hash)); . } -- line 1289 ---------------------------------------- -- 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] | . // --------------------------------------------- 11,868,195 ( 0.07%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 3,953,621 ( 0.02%) *self.ctrl(index) = ctrl; 3,954,689 ( 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,090,040 ( 0.01%) self.bucket_mask + 1 . } . . #[inline] . fn num_ctrl_bytes(&self) -> usize { 863,279 ( 0.00%) self.bucket_mask + 1 + Group::WIDTH . } . . #[inline] . fn is_empty_singleton(&self) -> bool { 4,023,542 ( 0.02%) self.bucket_mask == 0 . } . . #[allow(clippy::mut_mut)] . #[inline] . unsafe fn prepare_resize( . &self, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result, TryReserveError> { . debug_assert!(self.items <= capacity); . . // Allocate and initialize the new table. 17,517 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( . self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 402,821 ( 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_| { 175,953 ( 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. 351,924 ( 0.00%) let new_items = match self.items.checked_add(additional) { . Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 351,920 ( 0.00%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 752,895 ( 0.00%) if new_items <= full_capacity / 2 { . // Rehash in-place without re-allocating if we have plenty of spare . // capacity that is locked up due to DELETED entries. . self.rehash_in_place(hasher, layout.size, drop); 14 ( 0.00%) Ok(()) . } else { . // Otherwise, conservatively resize to at least the next size up . // to avoid churning deletes into frequent rehashes. . self.resize_inner( 175,953 ( 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> { 43,484 ( 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,452,809 ( 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); . 175,953 ( 0.00%) Ok(()) . } . . /// Rehashes the contents of the table in place (i.e. without changing the . /// allocation). . /// . /// If `hasher` panics then some the table's contents may be lost. . /// . /// This uses dynamic dispatch to reduce the amount of -- line 1470 ---------------------------------------- -- line 1496 ---------------------------------------- . } . self_.growth_left = bucket_mask_to_capacity(self_.bucket_mask) - self_.items; . }); . . // At this point, DELETED elements are elements that we haven't . // rehashed yet. Find them and re-insert them at their ideal . // position. . 'outer: for i in 0..guard.buckets() { 448 ( 0.00%) if *guard.ctrl(i) != DELETED { . continue; . } . . let i_p = guard.bucket_ptr(i, size_of); . . 'inner: loop { . // Hash the current item . let hash = hasher(*guard, i); -- line 1512 ---------------------------------------- -- line 1515 ---------------------------------------- . let new_i = guard.find_insert_slot(hash); . let new_i_p = guard.bucket_ptr(new_i, size_of); . . // Probing works by scanning through all of the control . // bytes in groups, which may not be aligned to the group . // size. If both the new and old position fall within the . // same unaligned group, then there is no benefit in moving . // it and we can just continue to the next item. 76 ( 0.00%) if likely(guard.is_in_same_group(i, new_i, hash)) { . guard.set_ctrl_h2(i, hash); . continue 'outer; . } . . // We are moving the current item to a new position. Write . // our H2 to the control byte of the new position. . let prev_ctrl = guard.replace_ctrl_h2(new_i, hash); . if prev_ctrl == EMPTY { -- line 1531 ---------------------------------------- -- line 1541 ---------------------------------------- . // swapped into the old slot. . debug_assert_eq!(prev_ctrl, DELETED); . ptr::swap_nonoverlapping(i_p, new_i_p, size_of); . continue 'inner; . } . } . } . 21 ( 0.00%) guard.growth_left = bucket_mask_to_capacity(guard.bucket_mask) - guard.items; . . mem::forget(guard); . } . . #[inline] . unsafe fn free_buckets(&mut self, table_layout: TableLayout) { . // Avoid `Option::unwrap_or_else` because it bloats LLVM IR. . let (layout, ctrl_offset) = match table_layout.calculate_layout_for(self.buckets()) { . Some(lco) => lco, . None => hint::unreachable_unchecked(), . }; . self.alloc.deallocate( 129,815 ( 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) { 52,624 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 59,807 ( 0.00%) self.items = 0; 52,837 ( 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))); 313,887 ( 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,255,548 ( 0.01%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 1,498,480 ( 0.01%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 1,255,548 ( 0.01%) self.items -= 1; . } . } . . impl Clone for RawTable { 2,912 ( 0.00%) fn clone(&self) -> Self { 461 ( 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) . } . } 3,276 ( 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; 166 ( 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)] 1,673,774 ( 0.01%) fn drop(&mut self) { 1,743,090 ( 0.01%) if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); . self.free_buckets(); . } . } 1,802,246 ( 0.01%) } . } . #[cfg(not(feature = "nightly"))] . impl Drop for RawTable { . #[cfg_attr(feature = "inline-more", inline)] . fn drop(&mut self) { . if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); -- line 1813 ---------------------------------------- -- line 1817 ---------------------------------------- . } . } . . impl IntoIterator for RawTable { . type Item = T; . type IntoIter = RawIntoIter; . . #[cfg_attr(feature = "inline-more", inline)] 15,624 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 19,530 ( 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 { 1,368,050 ( 0.01%) if let Some(index) = self.current_group.lowest_set_bit() { 157,273 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 268,434 ( 0.00%) return Some(self.data.next_n(index)); . } . 1,768,597 ( 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). 18,138 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); 26,484 ( 0.00%) self.data = self.data.next_n(Group::WIDTH); 26,747 ( 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) { 2,228 ( 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)] 183,689 ( 0.00%) fn next(&mut self) -> Option> { 383,456 ( 0.00%) if let Some(b) = self.iter.next() { 5,968,175 ( 0.03%) 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 . } 367,378 ( 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)] 4,838 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 33,980 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 590 ( 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)] 8,417 ( 0.00%) fn next(&mut self) -> Option { 4,995 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 20,551 ( 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)] 920 ( 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. 115 ( 0.00%) self.orig_table . .as_ptr() . .copy_from_nonoverlapping(&*self.table, 1); . } 920 ( 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 ---------------------------------------- 55,892,409 ( 0.32%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs -------------------------------------------------------------------------------- Ir -- line 108 ---------------------------------------- . suppress_errors: bool, . }, . } . . impl RegionckMode { . /// Indicates that the MIR borrowck will repeat these region . /// checks, so we should ignore errors if NLL is (unconditionally) . /// enabled. 780 ( 0.00%) pub fn for_item_body(tcx: TyCtxt<'_>) -> Self { . // FIXME(Centril): Once we actually remove `::Migrate` also make . // this always `true` and then proceed to eliminate the dead code. 780 ( 0.00%) match tcx.borrowck_mode() { . // If we're on Migrate mode, report AST region errors . BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false }, . . // If we're on MIR, don't report AST region errors as they should be reported by NLL . BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true }, . } 1,560 ( 0.00%) } . } . . /// This type contains all the things within `InferCtxt` that sit within a . /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot . /// operations are hot enough that we want only one call to `borrow_mut` per . /// call to `start_snapshot` and `rollback_to`. . pub struct InferCtxtInner<'tcx> { . /// Cache for projections. This cache is snapshotted along with the infcx. -- line 134 ---------------------------------------- -- line 202 ---------------------------------------- . /// type instantiations (`ty::Infer`) to the actual opaque . /// type (`ty::Opaque`). Used during fallback to map unconstrained . /// opaque type inference variables to their corresponding . /// opaque type. . pub opaque_types_vars: FxHashMap, Ty<'tcx>>, . } . . impl<'tcx> InferCtxtInner<'tcx> { 155,005 ( 0.00%) fn new() -> InferCtxtInner<'tcx> { 1,054,034 ( 0.01%) InferCtxtInner { . projection_cache: Default::default(), . type_variable_storage: type_variable::TypeVariableStorage::new(), . undo_log: InferCtxtUndoLogs::default(), . const_unification_storage: ut::UnificationTableStorage::new(), . int_unification_storage: ut::UnificationTableStorage::new(), . float_unification_storage: ut::UnificationTableStorage::new(), 93,003 ( 0.00%) region_constraint_storage: Some(RegionConstraintStorage::new()), . region_obligations: vec![], . opaque_types: Default::default(), . opaque_types_vars: Default::default(), . } 186,006 ( 0.00%) } . . #[inline] . pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] { . &self.region_obligations . } . . #[inline] . pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> { 20,950 ( 0.00%) self.projection_cache.with_log(&mut self.undo_log) . } . . #[inline] . fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> { 10,345,305 ( 0.06%) self.type_variable_storage.with_log(&mut self.undo_log) . } . . #[inline] . fn int_unification_table( . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::IntVid, . &mut ut::UnificationStorage, . &mut InferCtxtUndoLogs<'tcx>, . >, . > { 38,989 ( 0.00%) self.int_unification_storage.with_log(&mut self.undo_log) . } . . #[inline] . fn float_unification_table( . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::FloatVid, -- line 258 ---------------------------------------- -- line 268 ---------------------------------------- . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::ConstVid<'tcx>, . &mut ut::UnificationStorage>, . &mut InferCtxtUndoLogs<'tcx>, . >, . > { 8,960 ( 0.00%) self.const_unification_storage.with_log(&mut self.undo_log) . } . . #[inline] . pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> { 226,689 ( 0.00%) self.region_constraint_storage . .as_mut() . .expect("region constraints already solved") 276,096 ( 0.00%) .with_log(&mut self.undo_log) . } . } . . pub struct InferCtxt<'a, 'tcx> { . pub tcx: TyCtxt<'tcx>, . . /// The `DefId` of the item in whose context we are performing inference or typeck. . /// It is used to check whether an opaque type use is a defining use. -- line 292 ---------------------------------------- -- line 361 ---------------------------------------- . /// item we are type-checking, and just consider those names as . /// part of the root universe. So this would only get incremented . /// when we enter into a higher-ranked (`for<..>`) type or trait . /// bound. . universe: Cell, . } . . /// See the `error_reporting` module for more details. 470,056 ( 0.00%) #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)] . pub enum ValuePairs<'tcx> { . Types(ExpectedFound>), . Regions(ExpectedFound>), . Consts(ExpectedFound<&'tcx ty::Const<'tcx>>), . TraitRefs(ExpectedFound>), . PolyTraitRefs(ExpectedFound>), . } . -- line 377 ---------------------------------------- -- line 383 ---------------------------------------- . pub struct TypeTrace<'tcx> { . cause: ObligationCause<'tcx>, . values: ValuePairs<'tcx>, . } . . /// The origin of a `r1 <= r2` constraint. . /// . /// See `error_reporting` module for more details 424,443 ( 0.00%) #[derive(Clone, Debug)] . pub enum SubregionOrigin<'tcx> { . /// Arose from a subtyping relation 22,365 ( 0.00%) Subtype(Box>), . . /// When casting `&'a T` to an `&'b Trait` object, . /// relating `'a` to `'b` . RelateObjectBound(Span), . . /// Some type parameter was instantiated with the given type, . /// and that type must outlive some region. 5,348 ( 0.00%) RelateParamBound(Span, Ty<'tcx>, Option), . . /// The given region parameter was instantiated with a region . /// that must outlive some other region. . RelateRegionParamBound(Span), . . /// Creating a pointer `b` to contents of another reference . Reborrow(Span), . . /// Creating a pointer `b` to contents of an upvar . ReborrowUpvar(Span, ty::UpvarId), . . /// Data with type `Ty<'tcx>` was borrowed 4,811 ( 0.00%) DataBorrowed(Ty<'tcx>, Span), . . /// (&'a &'b T) where a >= b 4,266 ( 0.00%) ReferenceOutlivesReferent(Ty<'tcx>, Span), . . /// Comparing the signature and requirements of an impl method against . /// the containing trait. . CompareImplMethodObligation { span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId }, . . /// Comparing the signature and requirements of an impl associated type . /// against the containing trait . CompareImplTypeObligation { span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId }, -- line 426 ---------------------------------------- -- line 554 ---------------------------------------- . defining_use_anchor: Option, . } . . pub trait TyCtxtInferExt<'tcx> { . fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>; . } . . impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> { 31,001 ( 0.00%) fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> { 93,003 ( 0.00%) InferCtxtBuilder { tcx: self, defining_use_anchor: None, fresh_typeck_results: None } 31,001 ( 0.00%) } . } . . impl<'tcx> InferCtxtBuilder<'tcx> { . /// Used only by `rustc_typeck` during body type-checking/inference, . /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`. . /// Will also change the scope for opaque type defining use checks to the given owner. 19,512 ( 0.00%) pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self { 23,848 ( 0.00%) self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner))); 10,840 ( 0.00%) self.with_opaque_type_inference(table_owner) 15,176 ( 0.00%) } . . /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types, . /// you need to call this function. Otherwise the opaque type will be treated opaquely. . /// . /// It is only meant to be called in two places, for typeck . /// (via `with_fresh_in_progress_typeck_results`) and for the inference context used . /// in mir borrowck. 1,660 ( 0.00%) pub fn with_opaque_type_inference(mut self, defining_use_anchor: LocalDefId) -> Self { 830 ( 0.00%) self.defining_use_anchor = Some(defining_use_anchor); 5,996 ( 0.00%) self 2,490 ( 0.00%) } . . /// Given a canonical value `C` as a starting point, create an . /// inference context that contains each of the bound values . /// within instantiated as a fresh variable. The `f` closure is . /// invoked with the new infcx, along with the instantiated value . /// `V` and a substitution `S`. This substitution `S` maps from . /// the bound values in `C` to their instantiated values in `V` . /// (in other words, `S(C) = V`). 40,562 ( 0.00%) pub fn enter_with_canonical( . &mut self, . span: Span, . canonical: &Canonical<'tcx, T>, . f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R, . ) -> R . where . T: TypeFoldable<'tcx>, . { . self.enter(|infcx| { 57,018 ( 0.00%) let (value, subst) = 3,481 ( 0.00%) infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical); 84,672 ( 0.00%) f(infcx, value, subst) . }) 43,977 ( 0.00%) } . 187,416 ( 0.00%) pub fn enter(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R { 86,479 ( 0.00%) let InferCtxtBuilder { tcx, defining_use_anchor, ref fresh_typeck_results } = *self; . let in_progress_typeck_results = fresh_typeck_results.as_ref(); 1,319,941 ( 0.01%) f(InferCtxt { . tcx, . defining_use_anchor, . in_progress_typeck_results, 31,001 ( 0.00%) inner: RefCell::new(InferCtxtInner::new()), . lexical_region_resolutions: RefCell::new(None), . selection_cache: Default::default(), . evaluation_cache: Default::default(), . reported_trait_errors: Default::default(), . reported_closure_mismatch: Default::default(), . tainted_by_errors_flag: Cell::new(false), 31,001 ( 0.00%) err_count_on_creation: tcx.sess.err_count(), . in_snapshot: Cell::new(false), . skip_leak_check: Cell::new(false), . universe: Cell::new(ty::UniverseIndex::ROOT), . }) 201,506 ( 0.00%) } . } . . impl<'tcx, T> InferOk<'tcx, T> { . pub fn unit(self) -> InferOk<'tcx, ()> { . InferOk { value: (), obligations: self.obligations } . } . . /// Extracts `value`, registering any obligations into `fulfill_cx`. . pub fn into_value_registering_obligations( . self, . infcx: &InferCtxt<'_, 'tcx>, . fulfill_cx: &mut dyn TraitEngine<'tcx>, . ) -> T { 825 ( 0.00%) let InferOk { value, obligations } = self; 3,636 ( 0.00%) for obligation in obligations { 234 ( 0.00%) fulfill_cx.register_predicate_obligation(infcx, obligation); . } . value . } . } . . impl<'tcx> InferOk<'tcx, ()> { 41,347 ( 0.00%) pub fn into_obligations(self) -> PredicateObligations<'tcx> { 165,388 ( 0.00%) self.obligations 41,347 ( 0.00%) } . } . . #[must_use = "once you start a snapshot, you should always consume it"] . pub struct CombinedSnapshot<'a, 'tcx> { . undo_snapshot: Snapshot<'tcx>, . region_constraints_snapshot: RegionSnapshot, . universe: ty::UniverseIndex, . was_in_snapshot: bool, -- line 662 ---------------------------------------- -- line 674 ---------------------------------------- . let canonical = self.canonicalize_query((a, b), &mut OriginalQueryValues::default()); . debug!("canonical consts: {:?}", &canonical.value); . . self.tcx.try_unify_abstract_consts(canonical.value) . } . . pub fn is_in_snapshot(&self) -> bool { . self.in_snapshot.get() 73,043 ( 0.00%) } . 436,512 ( 0.00%) pub fn freshen>(&self, t: T) -> T { 491,076 ( 0.00%) t.fold_with(&mut self.freshener()) 491,076 ( 0.00%) } . . /// Returns the origin of the type variable identified by `vid`, or `None` . /// if this is not a type variable. . /// . /// No attempt is made to resolve `ty`. 400 ( 0.00%) pub fn type_var_origin(&'a self, ty: Ty<'tcx>) -> Option { 800 ( 0.00%) match *ty.kind() { 161 ( 0.00%) ty::Infer(ty::TyVar(vid)) => { 644 ( 0.00%) Some(*self.inner.borrow_mut().type_variables().var_origin(vid)) . } 39 ( 0.00%) _ => None, . } 800 ( 0.00%) } . 54,564 ( 0.00%) pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, false) 54,564 ( 0.00%) } . . /// Like `freshener`, but does not replace `'static` regions. 215,699 ( 0.00%) pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, true) 215,699 ( 0.00%) } . 3,508 ( 0.00%) pub fn unsolved_variables(&self) -> Vec> { 1,754 ( 0.00%) let mut inner = self.inner.borrow_mut(); 1,754 ( 0.00%) let mut vars: Vec> = inner . .type_variables() . .unsolved_variables() . .into_iter() 322 ( 0.00%) .map(|t| self.tcx.mk_ty_var(t)) . .collect(); . vars.extend( . (0..inner.int_unification_table().len()) . .map(|i| ty::IntVid { index: i as u32 }) 1,844 ( 0.00%) .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none()) 39 ( 0.00%) .map(|v| self.tcx.mk_int_var(v)), . ); . vars.extend( . (0..inner.float_unification_table().len()) . .map(|i| ty::FloatVid { index: i as u32 }) . .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none()) . .map(|v| self.tcx.mk_float_var(v)), . ); . vars 6,139 ( 0.00%) } . 121,768 ( 0.00%) fn combine_fields( . &'a self, . trace: TypeTrace<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> CombineFields<'a, 'tcx> { 487,452 ( 0.00%) CombineFields { . infcx: self, 1,218,630 ( 0.01%) trace, . cause: None, . param_env, . obligations: PredicateObligations::new(), . } 121,768 ( 0.00%) } . . /// Clear the "currently in a snapshot" flag, invoke the closure, . /// then restore the flag to its original value. This flag is a . /// debugging measure designed to detect cases where we start a . /// snapshot, create type variables, and register obligations . /// which may involve those type variables in the fulfillment cx, . /// potentially leaving "dangling type variables" behind. . /// In such cases, an assertion will fail when attempting to -- line 753 ---------------------------------------- -- line 755 ---------------------------------------- . /// better than grovelling through megabytes of `RUSTC_LOG` output. . /// . /// HOWEVER, in some cases the flag is unhelpful. In particular, we . /// sometimes create a "mini-fulfilment-cx" in which we enroll . /// obligations. As long as this fulfillment cx is fully drained . /// before we return, this is not a problem, as there won't be any . /// escaping obligations in the main cx. In those cases, you can . /// use this function. 96 ( 0.00%) pub fn save_and_restore_in_snapshot_flag(&self, func: F) -> R . where . F: FnOnce(&Self) -> R, . { . let flag = self.in_snapshot.replace(false); 42,204 ( 0.00%) let result = func(self); . self.in_snapshot.set(flag); . result 108 ( 0.00%) } . 599,156 ( 0.00%) fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> { . debug!("start_snapshot()"); . . let in_snapshot = self.in_snapshot.replace(true); . . let mut inner = self.inner.borrow_mut(); . 1,797,468 ( 0.01%) CombinedSnapshot { . undo_snapshot: inner.undo_log.start_snapshot(), . region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(), . universe: self.universe(), . was_in_snapshot: in_snapshot, . // Borrow typeck results "in progress" (i.e., during typeck) . // to ban writes from within a snapshot to them. 299,578 ( 0.00%) _in_progress_typeck_results: self . .in_progress_typeck_results . .map(|typeck_results| typeck_results.borrow()), . } 1,198,312 ( 0.01%) } . 908,391 ( 0.01%) #[instrument(skip(self, snapshot), level = "debug")] . fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 82,581 ( 0.00%) undo_snapshot, 82,581 ( 0.00%) region_constraints_snapshot, 82,581 ( 0.00%) universe, 82,581 ( 0.00%) was_in_snapshot, 165,162 ( 0.00%) _in_progress_typeck_results, . } = snapshot; . . self.in_snapshot.set(was_in_snapshot); . self.universe.set(universe); . . let mut inner = self.inner.borrow_mut(); 82,581 ( 0.00%) inner.rollback_to(undo_snapshot); . inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot); . } . 3,254,955 ( 0.02%) #[instrument(skip(self, snapshot), level = "debug")] . fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 216,997 ( 0.00%) undo_snapshot, . region_constraints_snapshot: _, . universe: _, 216,997 ( 0.00%) was_in_snapshot, 433,994 ( 0.00%) _in_progress_typeck_results, . } = snapshot; . . self.in_snapshot.set(was_in_snapshot); . . self.inner.borrow_mut().commit(undo_snapshot); . } . . /// Executes `f` and commit the bindings. 127,784 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 157,146 ( 0.00%) pub fn commit_unconditionally(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 14,286 ( 0.00%) let snapshot = self.start_snapshot(); 45,624 ( 0.00%) let r = f(&snapshot); 100,002 ( 0.00%) self.commit_from(snapshot); 88,100 ( 0.00%) r . } . . /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`. 1,362,810 ( 0.01%) #[instrument(skip(self, f), level = "debug")] 1,680,353 ( 0.01%) pub fn commit_if_ok(&self, f: F) -> Result . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result, . { 257,348 ( 0.00%) let snapshot = self.start_snapshot(); 765,599 ( 0.00%) let r = f(&snapshot); . debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok()); 263,976 ( 0.00%) match r { . Ok(_) => { 1,438,566 ( 0.01%) self.commit_from(snapshot); . } . Err(_) => { 316,482 ( 0.00%) self.rollback_to("commit_if_ok -- error", snapshot); . } . } 1,435,637 ( 0.01%) r . } . . /// Execute `f` then unroll any bindings it creates. 327,517 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 386,036 ( 0.00%) pub fn probe(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 95,039 ( 0.00%) let snapshot = self.start_snapshot(); 152,782 ( 0.00%) let r = f(&snapshot); 458,653 ( 0.00%) self.rollback_to("probe", snapshot); 136,784 ( 0.00%) r . } . . /// If `should_skip` is true, then execute `f` then unroll any bindings it creates. 207 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 276 ( 0.00%) pub fn probe_maybe_skip_leak_check(&self, should_skip: bool, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 46 ( 0.00%) let snapshot = self.start_snapshot(); 23 ( 0.00%) let was_skip_leak_check = self.skip_leak_check.get(); 46 ( 0.00%) if should_skip { . self.skip_leak_check.set(true); . } 92 ( 0.00%) let r = f(&snapshot); 207 ( 0.00%) self.rollback_to("probe", snapshot); . self.skip_leak_check.set(was_skip_leak_check); 276 ( 0.00%) r . } . . /// Scan the constraints produced since `snapshot` began and returns: . /// . /// - `None` -- if none of them involve "region outlives" constraints . /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder . /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders 18,432 ( 0.00%) pub fn region_constraints_added_in_snapshot( . &self, . snapshot: &CombinedSnapshot<'a, 'tcx>, . ) -> Option { 36,864 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() . .region_constraints_added_in_snapshot(&snapshot.undo_snapshot) 27,648 ( 0.00%) } . 8 ( 0.00%) pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) { 16 ( 0.00%) self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup); 12 ( 0.00%) } . 3,204 ( 0.00%) pub fn can_sub(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx> . where . T: at::ToTrace<'tcx>, . { . let origin = &ObligationCause::dummy(); . self.probe(|_| { . self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| { . // Ignore obligations, since we are unrolling . // everything anyway. . }) . }) 2,403 ( 0.00%) } . 16,392 ( 0.00%) pub fn can_eq(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx> . where . T: at::ToTrace<'tcx>, . { . let origin = &ObligationCause::dummy(); . self.probe(|_| { . self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| { . // Ignore obligations, since we are unrolling . // everything anyway. . }) . }) 12,294 ( 0.00%) } . 208,250 ( 0.00%) #[instrument(skip(self), level = "debug")] . pub fn sub_regions( . &self, . origin: SubregionOrigin<'tcx>, . a: ty::Region<'tcx>, . b: ty::Region<'tcx>, . ) { 187,425 ( 0.00%) self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b); . } . . /// Require that the region `r` be equal to one of the regions in . /// the set `regions`. 45 ( 0.00%) #[instrument(skip(self), level = "debug")] . pub fn member_constraint( . &self, . opaque_type_def_id: DefId, . definition_span: Span, . hidden_ty: Ty<'tcx>, . region: ty::Region<'tcx>, . in_regions: &Lrc>>, . ) { 45 ( 0.00%) self.inner.borrow_mut().unwrap_region_constraints().member_constraint( . opaque_type_def_id, . definition_span, . hidden_ty, . region, . in_regions, . ); . } . -- line 961 ---------------------------------------- -- line 969 ---------------------------------------- . /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up . /// actually requiring `a <: b`. This is of course a valid coercion, . /// but it's not as flexible as `FnCtxt::coerce` would be. . /// . /// (We may refactor this in the future, but there are a number of . /// practical obstacles. Among other things, `FnCtxt::coerce` presently . /// records adjustments that are required on the HIR in order to perform . /// the coercion, and we don't currently have a way to manage that.) 45 ( 0.00%) pub fn coerce_predicate( . &self, . cause: &ObligationCause<'tcx>, . param_env: ty::ParamEnv<'tcx>, . predicate: ty::PolyCoercePredicate<'tcx>, . ) -> Option> { 30 ( 0.00%) let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate { . a_is_expected: false, // when coercing from `a` to `b`, `b` is expected . a: p.a, . b: p.b, . }); 75 ( 0.00%) self.subtype_predicate(cause, param_env, subtype_predicate) 60 ( 0.00%) } . 30,276 ( 0.00%) pub fn subtype_predicate( . &self, . cause: &ObligationCause<'tcx>, . param_env: ty::ParamEnv<'tcx>, . predicate: ty::PolySubtypePredicate<'tcx>, . ) -> Option> { . // Check for two unresolved inference variables, in which case we can . // make no progress. This is partly a micro-optimization, but it's . // also an opportunity to "sub-unify" the variables. This isn't -- line 999 ---------------------------------------- -- line 1002 ---------------------------------------- . // earlier that they are sub-unified). . // . // Note that we can just skip the binders here because . // type variables can't (at present, at . // least) capture any of the things bound by this binder. . // . // Note that this sub here is not just for diagnostics - it has semantic . // effects as well. 2,523 ( 0.00%) let r_a = self.shallow_resolve(predicate.skip_binder().a); 2,523 ( 0.00%) let r_b = self.shallow_resolve(predicate.skip_binder().b); 19,878 ( 0.00%) match (r_a.kind(), r_b.kind()) { 4,902 ( 0.00%) (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => { . self.inner.borrow_mut().type_variables().sub(a_vid, b_vid); 4,902 ( 0.00%) return None; . } . _ => {} . } . . Some(self.commit_if_ok(|_snapshot| { 72 ( 0.00%) let ty::SubtypePredicate { a_is_expected, a, b } = . self.replace_bound_vars_with_placeholders(predicate); . 144 ( 0.00%) let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?; . . Ok(ok.unit()) . })) 22,707 ( 0.00%) } . 59,196 ( 0.00%) pub fn region_outlives_predicate( . &self, . cause: &traits::ObligationCause<'tcx>, . predicate: ty::PolyRegionOutlivesPredicate<'tcx>, . ) -> UnitResult<'tcx> { . self.commit_if_ok(|_snapshot| { . let ty::OutlivesPredicate(r_a, r_b) = . self.replace_bound_vars_with_placeholders(predicate); . let origin = SubregionOrigin::from_obligation_cause(cause, || { . RelateRegionParamBound(cause.span) . }); 49,330 ( 0.00%) self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b` . Ok(()) . }) 39,464 ( 0.00%) } . . /// Number of type variables created so far. 97 ( 0.00%) pub fn num_ty_vars(&self) -> usize { . self.inner.borrow_mut().type_variables().num_vars() 194 ( 0.00%) } . 61,032 ( 0.00%) pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid { 305,160 ( 0.00%) self.inner.borrow_mut().type_variables().new_var(self.universe(), origin) 91,548 ( 0.00%) } . 46,592 ( 0.00%) pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> { 206,394 ( 0.00%) self.tcx.mk_ty_var(self.next_ty_var_id(origin)) 69,888 ( 0.00%) } . 1,478 ( 0.00%) pub fn next_ty_var_in_universe( . &self, . origin: TypeVariableOrigin, . universe: ty::UniverseIndex, . ) -> Ty<'tcx> { 8,129 ( 0.00%) let vid = self.inner.borrow_mut().type_variables().new_var(universe, origin); 739 ( 0.00%) self.tcx.mk_ty_var(vid) 2,217 ( 0.00%) } . . pub fn next_const_var( . &self, . ty: Ty<'tcx>, . origin: ConstVariableOrigin, . ) -> &'tcx ty::Const<'tcx> { . self.tcx.mk_const_var(self.next_const_var_id(origin), ty) . } -- line 1074 ---------------------------------------- -- line 1090 ---------------------------------------- . pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> { . self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue { . origin, . val: ConstVariableValue::Unknown { universe: self.universe() }, . }) . } . . fn next_int_var_id(&self) -> IntVid { 3,965 ( 0.00%) self.inner.borrow_mut().int_unification_table().new_key(None) . } . 2,379 ( 0.00%) pub fn next_int_var(&self) -> Ty<'tcx> { . self.tcx.mk_int_var(self.next_int_var_id()) 3,172 ( 0.00%) } . . fn next_float_var_id(&self) -> FloatVid { . self.inner.borrow_mut().float_unification_table().new_key(None) . } . . pub fn next_float_var(&self) -> Ty<'tcx> { . self.tcx.mk_float_var(self.next_float_var_id()) . } . . /// Creates a fresh region variable with the next available index. . /// The variable will be created in the maximum universe created . /// thus far, allowing it to name any region created thus far. 31,341 ( 0.00%) pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> { 571,831 ( 0.00%) self.next_region_var_in_universe(origin, self.universe()) 62,682 ( 0.00%) } . . /// Creates a fresh region variable with the next available index . /// in the given universe; typically, you can use . /// `next_region_var` and just use the maximal universe. 232,376 ( 0.00%) pub fn next_region_var_in_universe( . &self, . origin: RegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { . let region_var = 1,510,444 ( 0.01%) self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin); 580,940 ( 0.00%) self.tcx.mk_region(ty::ReVar(region_var)) 348,564 ( 0.00%) } . . /// Return the universe that the region `r` was created in. For . /// most regions (e.g., `'static`, named regions from the user, . /// etc) this is the root universe U0. For inference variables or . /// placeholders, however, it will return the universe which which . /// they are associated. 37,002 ( 0.00%) pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex { . self.inner.borrow_mut().unwrap_region_constraints().universe(r) 55,503 ( 0.00%) } . . /// Number of region variables created so far. 6,690 ( 0.00%) pub fn num_region_vars(&self) -> usize { . self.inner.borrow_mut().unwrap_region_constraints().num_region_vars() 10,035 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 44,475 ( 0.00%) pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> { . self.next_region_var(RegionVariableOrigin::Nll(origin)) 88,950 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 357 ( 0.00%) pub fn next_nll_region_var_in_universe( . &self, . origin: NllRegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { 3,139 ( 0.00%) self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe) 714 ( 0.00%) } . 433,912 ( 0.00%) pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 238,857 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { . // Create a region inference variable for the given . // region parameter definition. 16,169 ( 0.00%) self.next_region_var(EarlyBoundRegion(span, param.name)).into() . } . GenericParamDefKind::Type { .. } => { . // Create a type inference variable for the given . // type parameter definition. The substitutions are . // for actual parameters that may be referred to by . // the default of this type parameter, if it exists. . // e.g., `struct Foo(...);` when . // used in a path such as `Foo::::new()` will . // use an inference variable for `C` with `[T, U]` . // as the substitutions for the default, `(T, U)`. 151,048 ( 0.00%) let ty_var_id = self.inner.borrow_mut().type_variables().new_var( . self.universe(), 188,810 ( 0.00%) TypeVariableOrigin { . kind: TypeVariableOriginKind::TypeParameterDefinition( 37,762 ( 0.00%) param.name, 37,762 ( 0.00%) Some(param.def_id), . ), . span, . }, . ); . 37,762 ( 0.00%) self.tcx.mk_ty_var(ty_var_id).into() . } . GenericParamDefKind::Const { .. } => { . let origin = ConstVariableOrigin { . kind: ConstVariableOriginKind::ConstParameterDefinition( . param.name, . param.def_id, . ), . span, . }; . let const_var_id = 3,388 ( 0.00%) self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue { . origin, . val: ConstVariableValue::Unknown { universe: self.universe() }, . }); 308 ( 0.00%) self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into() . } . } 2,464 ( 0.00%) } . . /// Given a set of generics defined on a type or impl, returns a substitution mapping each . /// type/region parameter to a fresh inference variable. 96,774 ( 0.00%) pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> { 450,293 ( 0.00%) InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param)) 64,516 ( 0.00%) } . . /// Returns `true` if errors have been reported since this infcx was . /// created. This is sometimes used as a heuristic to skip . /// reporting errors that often occur as a result of earlier . /// errors, but where it's hard to be 100% sure (e.g., unresolved . /// inference variables, regionck errors). 1,980 ( 0.00%) pub fn is_tainted_by_errors(&self) -> bool { . debug!( . "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \ . tainted_by_errors_flag={})", . self.tcx.sess.err_count(), . self.err_count_on_creation, . self.tainted_by_errors_flag.get() . ); . 69,492 ( 0.00%) if self.tcx.sess.err_count() > self.err_count_on_creation { . return true; // errors reported since this infcx was made . } . self.tainted_by_errors_flag.get() 2,970 ( 0.00%) } . . /// Set the "tainted by errors" flag to true. We call this when we . /// observe an error from a prior pass. . pub fn set_tainted_by_errors(&self) { . debug!("set_tainted_by_errors()"); . self.tainted_by_errors_flag.set(true) . } . . /// Process the region constraints and return any any errors that . /// result. After this, no more unification operations should be . /// done -- or the compiler will panic -- but it is legal to use . /// `resolve_vars_if_possible` as well as `fully_resolve`. 72,989 ( 0.00%) pub fn resolve_regions( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) -> Vec> { 198,113 ( 0.00%) let (var_infos, data) = { . let mut inner = self.inner.borrow_mut(); . let inner = &mut *inner; 10,427 ( 0.00%) assert!( 31,281 ( 0.00%) self.is_tainted_by_errors() || inner.region_obligations.is_empty(), . "region_obligations not empty: {:#?}", . inner.region_obligations . ); . inner . .region_constraint_storage . .take() . .expect("regions already resolved") . .with_log(&mut inner.undo_log) . .into_infos_and_data() 10,427 ( 0.00%) }; . . let region_rels = 10,427 ( 0.00%) &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map()); . 93,843 ( 0.00%) let (lexical_region_resolutions, errors) = 250,248 ( 0.00%) lexical_region_resolve::resolve(region_rels, var_infos, data, mode); . 41,708 ( 0.00%) let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions)); 10,427 ( 0.00%) assert!(old_value.is_none()); . . errors 93,843 ( 0.00%) } . . /// Process the region constraints and report any errors that . /// result. After this, no more unification operations should be . /// done -- or the compiler will panic -- but it is legal to use . /// `resolve_vars_if_possible` as well as `fully_resolve`. 104,270 ( 0.00%) pub fn resolve_regions_and_report_errors( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) { 20,854 ( 0.00%) let errors = self.resolve_regions(region_context, outlives_env, mode); . 31,281 ( 0.00%) if !self.is_tainted_by_errors() { . // As a heuristic, just skip reporting region errors . // altogether if other errors have been reported while . // this infcx was in use. This is totally hokey but . // otherwise we have a hard time separating legit region . // errors from silly ones. 20,854 ( 0.00%) self.report_region_errors(&errors); . } 52,135 ( 0.00%) } . . /// Obtains (and clears) the current set of region . /// constraints. The inference context is still usable: further . /// unifications will simply add new constraints. . /// . /// This method is not meant to be used with normal lexical region . /// resolution. Rather, it is used in the NLL mode as a kind of . /// interim hack: basically we run normal type-check and generate . /// region constraints as normal, but then we take them and . /// translate them into the form that the NLL solver . /// understands. See the NLL module for mode details. 30 ( 0.00%) pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx> { 10 ( 0.00%) assert!( . self.inner.borrow().region_obligations.is_empty(), . "region_obligations not empty: {:#?}", . self.inner.borrow().region_obligations . ); . 40 ( 0.00%) self.inner.borrow_mut().unwrap_region_constraints().take_and_reset_data() 50 ( 0.00%) } . . /// Gives temporary access to the region constraint data. . pub fn with_region_constraints( . &self, . op: impl FnOnce(&RegionConstraintData<'tcx>) -> R, . ) -> R { . let mut inner = self.inner.borrow_mut(); 18,668 ( 0.00%) op(inner.unwrap_region_constraints().data()) . } . . pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin { . let mut inner = self.inner.borrow_mut(); . let inner = &mut *inner; . inner . .region_constraint_storage . .as_mut() -- line 1335 ---------------------------------------- -- line 1338 ---------------------------------------- . .var_origin(vid) . } . . /// Takes ownership of the list of variable regions. This implies . /// that all the region constraints have already been taken, and . /// hence that `resolve_regions_and_report_errors` can never be . /// called. This is used only during NLL processing to "hand off" ownership . /// of the set of region variables into the NLL region context. 4,125 ( 0.00%) pub fn take_region_var_origins(&self) -> VarInfos { . let mut inner = self.inner.borrow_mut(); 15,675 ( 0.00%) let (var_infos, data) = inner . .region_constraint_storage . .take() . .expect("regions already resolved") . .with_log(&mut inner.undo_log) 825 ( 0.00%) .into_infos_and_data(); 825 ( 0.00%) assert!(data.is_empty()); . var_infos 6,600 ( 0.00%) } . . pub fn ty_to_string(&self, t: Ty<'tcx>) -> String { . self.resolve_vars_if_possible(t).to_string() . } . . /// If `TyVar(vid)` resolves to a type, return that type. Else, return the . /// universe index of `TyVar(vid)`. 22,580 ( 0.00%) pub fn probe_ty_var(&self, vid: TyVid) -> Result, ty::UniverseIndex> { . use self::type_variable::TypeVariableValue; . 67,740 ( 0.00%) match self.inner.borrow_mut().type_variables().probe(vid) { . TypeVariableValue::Known { value } => Ok(value), . TypeVariableValue::Unknown { universe } => Err(universe), . } 79,030 ( 0.00%) } . . /// Resolve any type variables found in `value` -- but only one . /// level. So, if the variable `?X` is bound to some type . /// `Foo`, then this would return `Foo` (but `?Y` may . /// itself be bound to a type). . /// . /// Useful when you only need to inspect the outermost level of . /// the type and don't care about nested types (or perhaps you . /// will be resolving them as well, e.g. in a loop). . pub fn shallow_resolve(&self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { 503,079 ( 0.00%) value.fold_with(&mut ShallowResolver { infcx: self }) . } . 51,840 ( 0.00%) pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid { . self.inner.borrow_mut().type_variables().root_var(var) 77,760 ( 0.00%) } . . /// Where possible, replaces type/const variables in . /// `value` with their final value. Note that region variables . /// are unaffected. If a type/const variable has not been unified, it . /// is left as is. This is an idempotent operation that does . /// not affect inference state in any way and so you can do it . /// at will. 7,024 ( 0.00%) pub fn resolve_vars_if_possible(&self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { 523,179 ( 0.00%) if !value.needs_infer() { 300,473 ( 0.00%) return value; // Avoid duplicated subst-folding. . } 596,943 ( 0.00%) let mut r = resolve::OpportunisticVarResolver::new(self); 760,898 ( 0.00%) value.fold_with(&mut r) 8,619 ( 0.00%) } . . /// Returns the first unresolved variable contained in `T`. In the . /// process of visiting `T`, this will resolve (where possible) . /// type variables in `T`, but it never constructs the final, . /// resolved type, so it's more efficient than . /// `resolve_vars_if_possible()`. . pub fn unresolved_type_vars(&self, value: &T) -> Option<(Ty<'tcx>, Option)> . where -- line 1415 ---------------------------------------- -- line 1490 ---------------------------------------- . expected: &'tcx ty::Const<'tcx>, . actual: &'tcx ty::Const<'tcx>, . err: TypeError<'tcx>, . ) -> DiagnosticBuilder<'tcx> { . let trace = TypeTrace::consts(cause, true, expected, actual); . self.report_and_explain_type_error(trace, &err) . } . 52,578 ( 0.00%) pub fn replace_bound_vars_with_fresh_vars( . &self, . span: Span, . lbrct: LateBoundRegionConversionTime, . value: ty::Binder<'tcx, T>, . ) -> (T, BTreeMap>) . where . T: TypeFoldable<'tcx>, . { . let fld_r = 279,943 ( 0.00%) |br: ty::BoundRegion| self.next_region_var(LateBoundRegion(span, br.kind, lbrct)); . let fld_t = |_| { . self.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::MiscVariable, . span, . }) . }; . let fld_c = |_, ty| { . self.next_const_var( . ty, . ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span }, . ) . }; 290,718 ( 0.00%) self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c) 35,052 ( 0.00%) } . . /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method. 6,704 ( 0.00%) pub fn verify_generic_bound( . &self, . origin: SubregionOrigin<'tcx>, . kind: GenericKind<'tcx>, . a: ty::Region<'tcx>, . bound: VerifyBound<'tcx>, . ) { . debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound); . 2,514 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() 14,246 ( 0.00%) .verify_generic_bound(origin, kind, a, bound); 5,866 ( 0.00%) } . . /// Obtains the latest type of the given closure; this may be a . /// closure in the current function, in which case its . /// `ClosureKind` may not yet be known. 1,714 ( 0.00%) pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option { 3,428 ( 0.00%) let closure_kind_ty = closure_substs.as_closure().kind_ty(); . let closure_kind_ty = self.shallow_resolve(closure_kind_ty); 2,571 ( 0.00%) closure_kind_ty.to_opt_closure_kind() . } . . /// Clears the selection, evaluation, and projection caches. This is useful when . /// repeatedly attempting to select an `Obligation` while changing only . /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing. . pub fn clear_caches(&self) { . self.selection_cache.clear(); . self.evaluation_cache.clear(); . self.inner.borrow_mut().projection_cache().clear(); . } . . pub fn universe(&self) -> ty::UniverseIndex { 903,406 ( 0.01%) self.universe.get() 335,313 ( 0.00%) } . . /// Creates and return a fresh universe that extends all previous . /// universes. Updates `self.universe` to that new universe. 610 ( 0.00%) pub fn create_next_universe(&self) -> ty::UniverseIndex { 810 ( 0.00%) let u = self.universe.get().next_universe(); . self.universe.set(u); . u 610 ( 0.00%) } . . /// Resolves and evaluates a constant. . /// . /// The constant can be located on a trait like `::C`, in which case the given . /// substitutions and environment are used to resolve the constant. Alternatively if the . /// constant has generic parameters in scope the substitutions are used to evaluate the value of . /// the constant. For example in `fn foo() { let _ = [0; bar::()]; }` the repeat count . /// constant `bar::()` requires a substitution for `T`, if the substitution for `T` is still -- line 1576 ---------------------------------------- -- line 1606 ---------------------------------------- . // variables, thus we don't need to substitute back the original values. . self.tcx.const_eval_resolve(param_env_erased, unevaluated, span) . } . . /// If `typ` is a type variable of some kind, resolve it one level . /// (but do not resolve types found in the result). If `typ` is . /// not a type variable, just return it unmodified. . // FIXME(eddyb) inline into `ShallowResolver::visit_ty`. 6,003,088 ( 0.03%) fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> { 3,361,756 ( 0.02%) match *typ.kind() { . ty::Infer(ty::TyVar(v)) => { . // Not entirely obvious: if `typ` is a type variable, . // it can be resolved to an int/float variable, which . // can then be recursively resolved, hence the . // recursion. Note though that we prevent type . // variables from unifying to other type variables . // directly (though they may be embedded . // structurally), and we prevent cycles in any case, . // so this recursion should always be of very limited . // depth. . // . // Note: if these two lines are combined into one we get . // dynamic borrow errors on `self.inner`. 1,859,608 ( 0.01%) let known = self.inner.borrow_mut().type_variables().probe(v).known(); . known.map_or(typ, |t| self.shallow_resolve_ty(t)) . } . 26,040 ( 0.00%) ty::Infer(ty::IntVar(v)) => self . .inner . .borrow_mut() . .int_unification_table() . .probe_value(v) 9,660 ( 0.00%) .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . . ty::Infer(ty::FloatVar(v)) => self . .inner . .borrow_mut() . .float_unification_table() . .probe_value(v) . .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . . _ => typ, . } 6,753,474 ( 0.04%) } . . /// `ty_or_const_infer_var_changed` is equivalent to one of these two: . /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`) . /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`) . /// . /// However, `ty_or_const_infer_var_changed` is more efficient. It's always . /// inlined, despite being large, because it has only two call sites that . /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on` -- line 1659 ---------------------------------------- -- line 1662 ---------------------------------------- . #[inline(always)] . pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool { . match infer_var { . TyOrConstInferVar::Ty(v) => { . use self::type_variable::TypeVariableValue; . . // If `inlined_probe` returns a `Known` value, it never equals . // `ty::Infer(ty::TyVar(v))`. 46,719,444 ( 0.26%) match self.inner.borrow_mut().type_variables().inlined_probe(v) { . TypeVariableValue::Unknown { .. } => false, . TypeVariableValue::Known { .. } => true, . } . } . . TyOrConstInferVar::TyInt(v) => { . // If `inlined_probe_value` returns a value it's always a . // `ty::Int(_)` or `ty::UInt(_)`, which never matches a . // `ty::Infer(_)`. 20,294 ( 0.00%) self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some() . } . . TyOrConstInferVar::TyFloat(v) => { . // If `probe_value` returns a value it's always a . // `ty::Float(_)`, which never matches a `ty::Infer(_)`. . // . // Not `inlined_probe_value(v)` because this call site is colder. . self.inner.borrow_mut().float_unification_table().probe_value(v).is_some() -- line 1688 ---------------------------------------- -- line 1716 ---------------------------------------- . /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`. . Const(ConstVid<'tcx>), . } . . impl<'tcx> TyOrConstInferVar<'tcx> { . /// Tries to extract an inference variable from a type or a constant, returns `None` . /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and . /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`). 25,305 ( 0.00%) pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option { . match arg.unpack() { . GenericArgKind::Type(ty) => Self::maybe_from_ty(ty), . GenericArgKind::Const(ct) => Self::maybe_from_const(ct), . GenericArgKind::Lifetime(_) => None, . } 25,305 ( 0.00%) } . . /// Tries to extract an inference variable from a type, returns `None` . /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`). 4,890 ( 0.00%) pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option { 271,129 ( 0.00%) match *ty.kind() { 59,894 ( 0.00%) ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)), 444 ( 0.00%) ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)), . ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)), . _ => None, . } 4,890 ( 0.00%) } . . /// Tries to extract an inference variable from a constant, returns `None` . /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`). . pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option { . match ct.val { . ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)), . _ => None, . } -- line 1749 ---------------------------------------- -- line 1755 ---------------------------------------- . } . . impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { . self.infcx.tcx . } . . fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { 1,097,531 ( 0.01%) self.infcx.shallow_resolve_ty(ty) . } . 3,608 ( 0.00%) fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 2,696 ( 0.00%) if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct { 2,230 ( 0.00%) self.infcx . .inner . .borrow_mut() . .const_unification_table() 1,338 ( 0.00%) .probe_value(*vid) . .val . .known() . .unwrap_or(ct) . } else { . ct . } 4,510 ( 0.00%) } . } . . impl<'tcx> TypeTrace<'tcx> { . pub fn span(&self) -> Span { 2,366 ( 0.00%) self.cause.span . } . . pub fn types( . cause: &ObligationCause<'tcx>, . a_is_expected: bool, . a: Ty<'tcx>, . b: Ty<'tcx>, . ) -> TypeTrace<'tcx> { -- line 1792 ---------------------------------------- -- line 1800 ---------------------------------------- . b: &'tcx ty::Const<'tcx>, . ) -> TypeTrace<'tcx> { . TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) } . } . } . . impl<'tcx> SubregionOrigin<'tcx> { . pub fn span(&self) -> Span { 5,915 ( 0.00%) match *self { 1,183 ( 0.00%) Subtype(ref a) => a.span(), . RelateObjectBound(a) => a, . RelateParamBound(a, ..) => a, . RelateRegionParamBound(a) => a, . Reborrow(a) => a, . ReborrowUpvar(a, _) => a, . DataBorrowed(_, a) => a, . ReferenceOutlivesReferent(_, a) => a, . CompareImplMethodObligation { span, .. } => span, -- line 1817 ---------------------------------------- -- line 1818 ---------------------------------------- . CompareImplTypeObligation { span, .. } => span, . } . } . . pub fn from_obligation_cause(cause: &traits::ObligationCause<'tcx>, default: F) -> Self . where . F: FnOnce() -> Self, . { 63,169 ( 0.00%) match *cause.code() { 8,223 ( 0.00%) traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => { 41,115 ( 0.00%) SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span) . } . . traits::ObligationCauseCode::CompareImplMethodObligation { . impl_item_def_id, . trait_item_def_id, . } => SubregionOrigin::CompareImplMethodObligation { . span: cause.span, . impl_item_def_id, -- line 1836 ---------------------------------------- 32,852,077 ( 0.19%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_transform/src/simplify.rs -------------------------------------------------------------------------------- Ir -- line 38 ---------------------------------------- . use std::convert::TryInto; . . pub struct SimplifyCfg { . label: String, . } . . impl SimplifyCfg { . pub fn new(label: &str) -> Self { 43,369 ( 0.00%) SimplifyCfg { label: format!("SimplifyCfg-{}", label) } . } . } . 52,030 ( 0.00%) pub fn simplify_cfg<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { 20,812 ( 0.00%) CfgSimplifier::new(body).simplify(); 15,609 ( 0.00%) remove_dead_blocks(tcx, body); . . // FIXME: Should probably be moved into some kind of pass manager . body.basic_blocks_mut().raw.shrink_to_fit(); 13,720 ( 0.00%) } . . impl<'tcx> MirPass<'tcx> for SimplifyCfg { 3,621 ( 0.00%) fn name(&self) -> Cow<'_, str> { 10,863 ( 0.00%) Cow::Borrowed(&self.label) 3,621 ( 0.00%) } . 3,621 ( 0.00%) fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { . debug!("SimplifyCfg({:?}) - simplifying {:?}", self.label, body.source); 10,406 ( 0.00%) simplify_cfg(tcx, body); . } . } . . pub struct CfgSimplifier<'a, 'tcx> { . basic_blocks: &'a mut IndexVec>, . pred_count: IndexVec, . } . . impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> { 36,421 ( 0.00%) pub fn new(body: &'a mut Body<'tcx>) -> Self { 10,406 ( 0.00%) let mut pred_count = IndexVec::from_elem(0u32, body.basic_blocks()); . . // we can't use mir.predecessors() here because that counts . // dead blocks, which we don't want to. 15,609 ( 0.00%) pred_count[START_BLOCK] = 1; . 701,756 ( 0.00%) for (_, data) in traversal::preorder(body) { 463,881 ( 0.00%) if let Some(ref term) = data.terminator { 677,299 ( 0.00%) for &tgt in term.successors() { 1,067,090 ( 0.01%) pred_count[tgt] += 1; . } . } . } . . let basic_blocks = body.basic_blocks_mut(); . 20,812 ( 0.00%) CfgSimplifier { basic_blocks, pred_count } 41,624 ( 0.00%) } . 41,624 ( 0.00%) pub fn simplify(mut self) { 5,203 ( 0.00%) self.strip_nops(); . . // Vec of the blocks that should be merged. We store the indices here, instead of the . // statements itself to avoid moving the (relatively) large statements twice. . // We do not push the statements directly into the target block (`bb`) as that is slower . // due to additional reallocations . let mut merged_blocks = Vec::new(); . loop { . let mut changed = false; . 12,318 ( 0.00%) for bb in self.basic_blocks.indices() { 535,638 ( 0.00%) if self.pred_count[bb] == 0 { . continue; . } . . debug!("simplifying {:?}", bb); . . let mut terminator = . self.basic_blocks[bb].terminator.take().expect("invalid terminator state"); . 582,114 ( 0.00%) for successor in terminator.successors_mut() { . self.collapse_goto_chain(successor, &mut changed); . } . . let mut inner_changed = true; . merged_blocks.clear(); 606,854 ( 0.00%) while inner_changed { . inner_changed = false; . inner_changed |= self.simplify_branch(&mut terminator); 206,408 ( 0.00%) inner_changed |= self.merge_successor(&mut merged_blocks, &mut terminator); 619,224 ( 0.00%) changed |= inner_changed; . } . . let statements_to_merge = 216,576 ( 0.00%) merged_blocks.iter().map(|&i| self.basic_blocks[i].statements.len()).sum(); . 19,986 ( 0.00%) if statements_to_merge > 0 { . let mut statements = std::mem::take(&mut self.basic_blocks[bb].statements); . statements.reserve(statements_to_merge); 9,258 ( 0.00%) for &from in &merged_blocks { 18,516 ( 0.00%) statements.append(&mut self.basic_blocks[from].statements); . } 71,838 ( 0.00%) self.basic_blocks[bb].statements = statements; . } . 6,015,178 ( 0.03%) self.basic_blocks[bb].terminator = Some(terminator); . } . 12,318 ( 0.00%) if !changed { . break; . } . } 41,624 ( 0.00%) } . . /// This function will return `None` if . /// * the block has statements . /// * the block has a terminator other than `goto` . /// * the block has no terminator (meaning some other part of the current optimization stole it) . fn take_terminator_if_simple_goto(&mut self, bb: BasicBlock) -> Option> { 2,058,623 ( 0.01%) match self.basic_blocks[bb] { . BasicBlockData { . ref statements, . terminator: . ref mut terminator @ Some(Terminator { kind: TerminatorKind::Goto { .. }, .. }), . .. 86,965 ( 0.00%) } if statements.is_empty() => terminator.take(), . // if `terminator` is None, this means we are in a loop. In that . // case, let all the loop collapse to its entry. . _ => None, . } . } . . /// Collapse a goto chain starting from `start` . fn collapse_goto_chain(&mut self, start: &mut BasicBlock, changed: &mut bool) { . // Using `SmallVec` here, because in some logs on libcore oli-obk saw many single-element . // goto chains. We should probably benchmark different sizes. . let mut terminators: SmallVec<[_; 1]> = Default::default(); 826,677 ( 0.00%) let mut current = *start; 1,178,747 ( 0.01%) while let Some(terminator) = self.take_terminator_if_simple_goto(current) { 37,060 ( 0.00%) let target = match terminator { 18,530 ( 0.00%) Terminator { kind: TerminatorKind::Goto { target }, .. } => target, . _ => unreachable!(), . }; 352,070 ( 0.00%) terminators.push((current, terminator)); . current = target; . } . let last = current; 275,559 ( 0.00%) *start = last; 277,950 ( 0.00%) while let Some((current, mut terminator)) = terminators.pop() { 37,060 ( 0.00%) let target = match terminator { . Terminator { kind: TerminatorKind::Goto { ref mut target }, .. } => target, . _ => unreachable!(), . }; 37,060 ( 0.00%) *changed |= *target != last; 37,060 ( 0.00%) *target = last; . debug!("collapsing goto chain from {:?} to {:?}", current, target); . 37,060 ( 0.00%) if self.pred_count[current] == 1 { . // This is the last reference to current, so the pred-count to . // to target is moved into the current block. . self.pred_count[current] = 0; . } else { 6,868 ( 0.00%) self.pred_count[*target] += 1; 5,151 ( 0.00%) self.pred_count[current] -= 1; . } 611,490 ( 0.00%) self.basic_blocks[current].terminator = Some(terminator); . } . } . . // merge a block with 1 `goto` predecessor to its parent . fn merge_successor( . &mut self, . merged_blocks: &mut Vec, . terminator: &mut Terminator<'tcx>, . ) -> bool { 512,923 ( 0.00%) let target = match terminator.kind { 254,604 ( 0.00%) TerminatorKind::Goto { target } if self.pred_count[target] == 1 => target, . _ => return false, . }; . . debug!("merging block {:?} into {:?}", target, terminator); 259,187 ( 0.00%) *terminator = match self.basic_blocks[target].terminator.take() { . Some(terminator) => terminator, . None => { . // unreachable loop - this should not be possible, as we . // don't strand blocks, but handle it correctly. . return false; . } . }; . . merged_blocks.push(target); 33,807 ( 0.00%) self.pred_count[target] = 0; . . true . } . . // turn a branch with all successors identical to a goto . fn simplify_branch(&mut self, terminator: &mut Terminator<'tcx>) -> bool { 619,224 ( 0.00%) match terminator.kind { . TerminatorKind::SwitchInt { .. } => {} . _ => return false, . }; . . let first_succ = { 129,168 ( 0.00%) if let Some(&first_succ) = terminator.successors().next() { 64,584 ( 0.00%) if terminator.successors().all(|s| *s == first_succ) { 9,900 ( 0.00%) let count = terminator.successors().count(); 19,800 ( 0.00%) self.pred_count[first_succ] -= (count - 1) as u32; . first_succ . } else { . return false; . } . } else { . return false; . } . }; . . debug!("simplifying branch {:?}", terminator); 19,800 ( 0.00%) terminator.kind = TerminatorKind::Goto { target: first_succ }; . true . } . . fn strip_nops(&mut self) { . for blk in self.basic_blocks.iter_mut() { 715,022 ( 0.00%) blk.statements.retain(|stmt| !matches!(stmt.kind, StatementKind::Nop)) . } . } . } . 62,200 ( 0.00%) pub fn remove_dead_blocks<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { 6,220 ( 0.00%) let reachable = traversal::reachable_as_bitset(body); . let num_blocks = body.basic_blocks().len(); 12,440 ( 0.00%) if num_blocks == reachable.count() { . return; . } . . let basic_blocks = body.basic_blocks_mut(); . let mut replacements: Vec<_> = (0..num_blocks).map(BasicBlock::new).collect(); . let mut used_blocks = 0; 116,135 ( 0.00%) for alive_index in reachable.iter() { . let alive_index = alive_index.index(); 116,135 ( 0.00%) replacements[alive_index] = BasicBlock::new(used_blocks); 232,270 ( 0.00%) if alive_index != used_blocks { . // Swap the next alive block data with the current available slot. Since . // alive_index is non-decreasing this is a valid operation. . basic_blocks.raw.swap(alive_index, used_blocks); . } 116,135 ( 0.00%) used_blocks += 1; . } . 15,508 ( 0.00%) if tcx.sess.instrument_coverage() { . save_unreachable_coverage(basic_blocks, used_blocks); . } . . basic_blocks.raw.truncate(used_blocks); . . for block in basic_blocks { 232,270 ( 0.00%) for target in block.terminator_mut().successors_mut() { 626,940 ( 0.00%) *target = replacements[target.index()]; . } . } 49,760 ( 0.00%) } . . /// Some MIR transforms can determine at compile time that a sequences of . /// statements will never be executed, so they can be dropped from the MIR. . /// For example, an `if` or `else` block that is guaranteed to never be executed . /// because its condition can be evaluated at compile time, such as by const . /// evaluation: `if false { ... }`. . /// . /// Those statements are bypassed by redirecting paths in the CFG around the -- line 305 ---------------------------------------- -- line 363 ---------------------------------------- . })), . }) . } . } . . pub struct SimplifyLocals; . . impl<'tcx> MirPass<'tcx> for SimplifyLocals { 1,582 ( 0.00%) fn is_enabled(&self, sess: &rustc_session::Session) -> bool { 2,373 ( 0.00%) sess.mir_opt_level() > 0 1,582 ( 0.00%) } . 791 ( 0.00%) fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { . trace!("running SimplifyLocals on {:?}", body.source); 791 ( 0.00%) simplify_locals(body, tcx); . } . } . 5,537 ( 0.00%) pub fn simplify_locals<'tcx>(body: &mut Body<'tcx>, tcx: TyCtxt<'tcx>) { . // First, we're going to get a count of *actual* uses for every `Local`. . let mut used_locals = UsedLocals::new(body); . . // Next, we're going to remove any `Local` with zero actual uses. When we remove those . // `Locals`, we're also going to subtract any uses of other `Locals` from the `used_locals` . // count. For example, if we removed `_2 = discriminant(_1)`, then we'll subtract one from . // `use_counts[_1]`. That in turn might make `_1` unused, so we loop until we hit a . // fixedpoint where there are no more unused locals. -- line 389 ---------------------------------------- -- line 390 ---------------------------------------- . remove_unused_definitions(&mut used_locals, body); . . // Finally, we'll actually do the work of shrinking `body.local_decls` and remapping the `Local`s. . let map = make_local_map(&mut body.local_decls, &used_locals); . . // Only bother running the `LocalUpdater` if we actually found locals to remove. . if map.iter().any(Option::is_none) { . // Update references to all vars and tmps now 1,500 ( 0.00%) let mut updater = LocalUpdater { map, tcx }; . updater.visit_body(body); . . body.local_decls.shrink_to_fit(); . } 6,328 ( 0.00%) } . . /// Construct the mapping while swapping out unused stuff out from the `vec`. . fn make_local_map( . local_decls: &mut IndexVec, . used_locals: &UsedLocals, . ) -> IndexVec> { 1,582 ( 0.00%) let mut map: IndexVec> = IndexVec::from_elem(None, &*local_decls); . let mut used = Local::new(0); . 791 ( 0.00%) for alive_index in local_decls.indices() { . // `is_used` treats the `RETURN_PLACE` and arguments as used. 30,731 ( 0.00%) if !used_locals.is_used(alive_index) { . continue; . } . 24,432 ( 0.00%) map[alive_index] = Some(used); 24,432 ( 0.00%) if alive_index != used { . local_decls.swap(alive_index, used); . } . used.increment_by(1); . } . local_decls.truncate(used.index()); . map . } . -- line 428 ---------------------------------------- -- line 431 ---------------------------------------- . increment: bool, . arg_count: u32, . use_count: IndexVec, . } . . impl UsedLocals { . /// Determines which locals are used & unused in the given body. . fn new(body: &Body<'_>) -> Self { 5,537 ( 0.00%) let mut this = Self { . increment: true, 791 ( 0.00%) arg_count: body.arg_count.try_into().unwrap(), 2,373 ( 0.00%) use_count: IndexVec::from_elem(0, &body.local_decls), . }; . this.visit_body(body); . this . } . . /// Checks if local is used. . /// . /// Return place and arguments are always considered used. . fn is_used(&self, local: Local) -> bool { . trace!("is_used({:?}): use_count: {:?}", local, self.use_count[local]); 169,247 ( 0.00%) local.as_u32() <= self.arg_count || self.use_count[local] != 0 . } . . /// Updates the use counts to reflect the removal of given statement. . fn statement_removed(&mut self, statement: &Statement<'_>) { 3,001 ( 0.00%) self.increment = false; . . // The location of the statement is irrelevant. . let location = Location { block: START_BLOCK, statement_index: 0 }; 15,005 ( 0.00%) self.visit_statement(statement, location); . } . . /// Visits a left-hand side of an assignment. 136,590 ( 0.00%) fn visit_lhs(&mut self, place: &Place<'_>, location: Location) { 109,272 ( 0.00%) if place.is_indirect() { . // A use, not a definition. . self.visit_place(place, PlaceContext::MutatingUse(MutatingUseContext::Store), location); . } else { . // A definition. The base local itself is not visited, so this occurrence is not counted . // toward its use count. There might be other locals still, used in an indexing . // projection. . self.super_projection( . place.as_ref(), . PlaceContext::MutatingUse(MutatingUseContext::Projection), . location, . ); . } 109,272 ( 0.00%) } . } . . impl<'tcx> Visitor<'tcx> for UsedLocals { 136,590 ( 0.00%) fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) { 136,590 ( 0.00%) match statement.kind { . StatementKind::CopyNonOverlapping(..) . | StatementKind::Retag(..) . | StatementKind::Coverage(..) . | StatementKind::FakeRead(..) . | StatementKind::AscribeUserType(..) => { . self.super_statement(statement, location); . } . . StatementKind::Nop => {} . . StatementKind::StorageLive(_local) | StatementKind::StorageDead(_local) => {} . 24,920 ( 0.00%) StatementKind::Assign(box (ref place, ref rvalue)) => { 74,760 ( 0.00%) self.visit_lhs(place, location); . self.visit_rvalue(rvalue, location); . } . . StatementKind::SetDiscriminant { ref place, variant_index: _ } => { 16,786 ( 0.00%) self.visit_lhs(place, location); . } . } 53,150 ( 0.00%) } . . fn visit_local(&mut self, local: &Local, _ctx: PlaceContext, _location: Location) { 116,807 ( 0.00%) if self.increment { 132,624 ( 0.00%) self.use_count[*local] += 1; . } else { 7,500 ( 0.00%) assert_ne!(self.use_count[*local], 0); 2,500 ( 0.00%) self.use_count[*local] -= 1; . } . } . } . . /// Removes unused definitions. Updates the used locals to reflect the changes made. . fn remove_unused_definitions(used_locals: &mut UsedLocals, body: &mut Body<'_>) { . // The use counts are updated as we remove the statements. A local might become unused . // during the retain operation, leading to a temporary inconsistency (storage statements or . // definitions referencing the local might remain). For correctness it is crucial that this . // computation reaches a fixed point. . . let mut modified = true; 12,637 ( 0.00%) while modified { 984 ( 0.00%) modified = false; . . for data in body.basic_blocks_mut() { . // Remove unnecessary StorageLive and StorageDead annotations. 95,048 ( 0.00%) data.statements.retain(|statement| { 226,572 ( 0.00%) let keep = match &statement.kind { . StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => { . used_locals.is_used(*local) . } 65,900 ( 0.00%) StatementKind::Assign(box (place, _)) => used_locals.is_used(place.local), . . StatementKind::SetDiscriminant { ref place, .. } => { 7,218 ( 0.00%) used_locals.is_used(place.local) . } . _ => true, . }; . 33,828 ( 0.00%) if !keep { . trace!("removing statement {:?}", statement); 3,001 ( 0.00%) modified = true; . used_locals.statement_removed(statement); . } . . keep . }); . } . } . } -- line 555 ---------------------------------------- -- line 556 ---------------------------------------- . . struct LocalUpdater<'tcx> { . map: IndexVec>, . tcx: TyCtxt<'tcx>, . } . . impl<'tcx> MutVisitor<'tcx> for LocalUpdater<'tcx> { . fn tcx(&self) -> TyCtxt<'tcx> { 2 ( 0.00%) self.tcx . } . . fn visit_local(&mut self, l: &mut Local, _: PlaceContext, _: Location) { 121,930 ( 0.00%) *l = self.map[*l].unwrap(); . } . } 2,787,722 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/pattern/usefulness.rs -------------------------------------------------------------------------------- Ir -- line 308 ---------------------------------------- . /// not. E.g., `struct Foo { _private: ! }` cannot be seen to be empty . /// outside its module and should not be matchable with an empty match statement. . crate module: DefId, . crate param_env: ty::ParamEnv<'tcx>, . crate pattern_arena: &'p TypedArena>, . } . . impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> { 110 ( 0.00%) pub(super) fn is_uninhabited(&self, ty: Ty<'tcx>) -> bool { 66,755 ( 0.00%) if self.tcx.features().exhaustive_patterns { . self.tcx.is_ty_uninhabited_from(self.module, ty, self.param_env) . } else { . false . } 110 ( 0.00%) } . . /// Returns whether the given type is an enum from another crate declared `#[non_exhaustive]`. . pub(super) fn is_foreign_non_exhaustive_enum(&self, ty: Ty<'tcx>) -> bool { 60,936 ( 0.00%) match ty.kind() { . ty::Adt(def, ..) => { 56,920 ( 0.00%) def.is_enum() && def.is_variant_list_non_exhaustive() && !def.did.is_local() . } . _ => false, . } . } . } . . #[derive(Copy, Clone)] . pub(super) struct PatCtxt<'a, 'p, 'tcx> { -- line 336 ---------------------------------------- -- line 349 ---------------------------------------- . impl<'a, 'p, 'tcx> fmt::Debug for PatCtxt<'a, 'p, 'tcx> { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . f.debug_struct("PatCtxt").field("ty", &self.ty).finish() . } . } . . /// A row of a matrix. Rows of len 1 are very common, which is why `SmallVec[_; 2]` . /// works well. 47,104 ( 0.00%) #[derive(Clone)] . struct PatStack<'p, 'tcx> { . pats: SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>, . } . . impl<'p, 'tcx> PatStack<'p, 'tcx> { 7,660 ( 0.00%) fn from_pattern(pat: &'p DeconstructedPat<'p, 'tcx>) -> Self { . Self::from_vec(smallvec![pat]) 7,660 ( 0.00%) } . . fn from_vec(vec: SmallVec<[&'p DeconstructedPat<'p, 'tcx>; 2]>) -> Self { 24,028 ( 0.00%) PatStack { pats: vec } . } . . fn is_empty(&self) -> bool { 1,233,232 ( 0.01%) self.pats.is_empty() . } . . fn len(&self) -> usize { . self.pats.len() . } . . fn head(&self) -> &'p DeconstructedPat<'p, 'tcx> { 8,816,160 ( 0.05%) self.pats[0] . } . . fn iter(&self) -> impl Iterator> { . self.pats.iter().copied() . } . . // Recursively expand the first pattern into its subpatterns. Only useful if the pattern is an . // or-pattern. Panics if `self` is empty. . fn expand_or_pat<'a>(&'a self) -> impl Iterator> + Captures<'a> { . self.head().iter_fields().map(move |pat| { 1,437 ( 0.00%) let mut new_patstack = PatStack::from_pattern(pat); . new_patstack.pats.extend_from_slice(&self.pats[1..]); . new_patstack . }) . } . . /// This computes `S(self.head().ctor(), self)`. See top of the file for explanations. . /// . /// Structure patterns with a partial wild pattern (Foo { a: 42, .. }) have their missing -- line 399 ---------------------------------------- -- line 402 ---------------------------------------- . /// This is roughly the inverse of `Constructor::apply`. . fn pop_head_constructor( . &self, . cx: &MatchCheckCtxt<'p, 'tcx>, . ctor: &Constructor<'tcx>, . ) -> PatStack<'p, 'tcx> { . // We pop the head pattern and push the new fields extracted from the arguments of . // `self.head()`. 2,389,716 ( 0.01%) let mut new_fields: SmallVec<[_; 2]> = self.head().specialize(cx, ctor); . new_fields.extend_from_slice(&self.pats[1..]); 2,389,716 ( 0.01%) PatStack::from_vec(new_fields) . } . } . . /// Pretty-printing for matrix row. . impl<'p, 'tcx> fmt::Debug for PatStack<'p, 'tcx> { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(f, "+")?; . for pat in self.iter() { . write!(f, " {:?} +", pat)?; . } . Ok(()) . } . } . . /// A 2D matrix. 296 ( 0.00%) #[derive(Clone)] . pub(super) struct Matrix<'p, 'tcx> { 222 ( 0.00%) patterns: Vec>, . } . . impl<'p, 'tcx> Matrix<'p, 'tcx> { . fn empty() -> Self { 75,902 ( 0.00%) Matrix { patterns: vec![] } . } . . /// Number of columns of this matrix. `None` is the matrix is empty. . pub(super) fn column_count(&self) -> Option { . self.patterns.get(0).map(|r| r.len()) . } . . /// Pushes a new row to the matrix. If the row starts with an or-pattern, this recursively . /// expands it. 5,229,630 ( 0.03%) fn push(&mut self, row: PatStack<'p, 'tcx>) { 1,155,268 ( 0.01%) if !row.is_empty() && row.head().is_or_pat() { . self.patterns.extend(row.expand_or_pat()); . } else { 2,323,988 ( 0.01%) self.patterns.push(row); . } 4,648,560 ( 0.03%) } . . /// Iterate over the first component of each row . fn heads<'a>( . &'a self, . ) -> impl Iterator> + Clone + Captures<'a> { . self.patterns.iter().map(|r| r.head()) . } . -- line 459 ---------------------------------------- -- line 460 ---------------------------------------- . /// This computes `S(constructor, self)`. See top of the file for explanations. . fn specialize_constructor( . &self, . pcx: PatCtxt<'_, 'p, 'tcx>, . ctor: &Constructor<'tcx>, . ) -> Matrix<'p, 'tcx> { . let mut matrix = Matrix::empty(); . for row in &self.patterns { 1,273,447 ( 0.01%) if ctor.is_covered_by(pcx, row.head().ctor()) { . let new_row = row.pop_head_constructor(pcx.cx, ctor); 3,440,508 ( 0.02%) matrix.push(new_row); . } . } . matrix . } . } . . /// Pretty-printer for matrices of patterns, example: . /// -- line 478 ---------------------------------------- -- line 522 ---------------------------------------- . NoWitnesses { useful: bool }, . /// Carries a list of witnesses of non-exhaustiveness. If empty, indicates that the whole . /// pattern is unreachable. . WithWitnesses(Vec>), . } . . impl<'p, 'tcx> Usefulness<'p, 'tcx> { . fn new_useful(preference: ArmType) -> Self { 15,226 ( 0.00%) match preference { . // A single (empty) witness of reachability. 39 ( 0.00%) FakeExtraWildcard => WithWitnesses(vec![Witness(vec![])]), . RealArm => NoWitnesses { useful: true }, . } . } . . fn new_not_useful(preference: ArmType) -> Self { 55,866 ( 0.00%) match preference { 14,664 ( 0.00%) FakeExtraWildcard => WithWitnesses(vec![]), 62,260 ( 0.00%) RealArm => NoWitnesses { useful: false }, . } . } . . fn is_useful(&self) -> bool { 63,192 ( 0.00%) match self { 13,732 ( 0.00%) Usefulness::NoWitnesses { useful } => *useful, . Usefulness::WithWitnesses(witnesses) => !witnesses.is_empty(), . } . } . . /// Combine usefulnesses from two branches. This is an associative operation. 171,472 ( 0.00%) fn extend(&mut self, other: Self) { 269,456 ( 0.00%) match (&mut *self, other) { 61,992 ( 0.00%) (WithWitnesses(_), WithWitnesses(o)) if o.is_empty() => {} 195 ( 0.00%) (WithWitnesses(s), WithWitnesses(o)) if s.is_empty() => *self = WithWitnesses(o), . (WithWitnesses(s), WithWitnesses(o)) => s.extend(o), . (NoWitnesses { useful: s_useful }, NoWitnesses { useful: o_useful }) => { 70,770 ( 0.00%) *s_useful = *s_useful || o_useful . } . _ => unreachable!(), . } 195,968 ( 0.00%) } . . /// After calculating usefulness after a specialization, call this to reconstruct a usefulness . /// that makes sense for the matrix pre-specialization. This new usefulness can then be merged . /// with the results of specializing with the other constructors. . fn apply_constructor( . self, . pcx: PatCtxt<'_, 'p, 'tcx>, . matrix: &Matrix<'p, 'tcx>, // used to compute missing ctors . ctor: &Constructor<'tcx>, . ) -> Self { 48,022 ( 0.00%) match self { 136,690 ( 0.00%) NoWitnesses { .. } => self, 113,612 ( 0.00%) WithWitnesses(ref witnesses) if witnesses.is_empty() => self, 45 ( 0.00%) WithWitnesses(witnesses) => { 30 ( 0.00%) let new_witnesses = if let Constructor::Missing { .. } = ctor { . // We got the special `Missing` constructor, so each of the missing constructors . // gives a new pattern that is not caught by the match. We list those patterns. 26 ( 0.00%) let new_patterns = if pcx.is_non_exhaustive { . // Here we don't want the user to try to list all variants, we want them to add . // a wildcard, so we only suggest that. . vec![DeconstructedPat::wildcard(pcx.ty)] . } else { 104 ( 0.00%) let mut split_wildcard = SplitWildcard::new(pcx); 104 ( 0.00%) split_wildcard.split(pcx, matrix.heads().map(DeconstructedPat::ctor)); . . // This lets us know if we skipped any variants because they are marked . // `doc(hidden)` or they are unstable feature gate (only stdlib types). 13 ( 0.00%) let mut hide_variant_show_wild = false; . // Construct for each missing constructor a "wild" version of this . // constructor, that matches everything that can be built with . // it. For example, if `ctor` is a `Constructor::Variant` for . // `Option::Some`, we get the pattern `Some(_)`. . let mut new: Vec> = split_wildcard . .iter_missing(pcx) . .filter_map(|missing_ctor| { . // Check if this variant is marked `doc(hidden)` 2,735 ( 0.00%) if missing_ctor.is_doc_hidden_variant(pcx) 3,829 ( 0.00%) || missing_ctor.is_unstable_variant(pcx) . { . hide_variant_show_wild = true; . return None; . } 6,017 ( 0.00%) Some(DeconstructedPat::wild_from_ctor(pcx, missing_ctor.clone())) . }) . .collect(); . 26 ( 0.00%) if hide_variant_show_wild { . new.push(DeconstructedPat::wildcard(pcx.ty)); . } . 52 ( 0.00%) new . }; . . witnesses . .into_iter() . .flat_map(|witness| { . new_patterns.iter().map(move |pat| { . Witness( . witness -- line 621 ---------------------------------------- -- line 626 ---------------------------------------- . .collect(), . ) . }) . }) . .collect() . } else { . witnesses . .into_iter() 24 ( 0.00%) .map(|witness| witness.apply_constructor(pcx, &ctor)) . .collect() . }; 90 ( 0.00%) WithWitnesses(new_witnesses) . } . } . } . } . . #[derive(Copy, Clone, Debug)] . enum ArmType { . FakeExtraWildcard, -- line 645 ---------------------------------------- -- line 679 ---------------------------------------- . /// `Witness(vec![Pair(Some(_), true)])` . /// . /// The final `Pair(Some(_), true)` is then the resulting witness. . #[derive(Debug)] . crate struct Witness<'p, 'tcx>(Vec>); . . impl<'p, 'tcx> Witness<'p, 'tcx> { . /// Asserts that the witness contains a single pattern, and returns it. 2,188 ( 0.00%) fn single_pattern(self) -> DeconstructedPat<'p, 'tcx> { 2,188 ( 0.00%) assert_eq!(self.0.len(), 1); . self.0.into_iter().next().unwrap() 2,735 ( 0.00%) } . . /// Constructs a partial witness for a pattern given a list of . /// patterns expanded by the specialization step. . /// . /// When a pattern P is discovered to be useful, this function is used bottom-up . /// to reconstruct a complete witness, e.g., a pattern P' that covers a subset . /// of values, V, where each value in that set is not covered by any previously . /// used patterns and is covered by the pattern P'. Examples: . /// . /// left_ty: tuple of 3 elements . /// pats: [10, 20, _] => (10, 20, _) . /// . /// left_ty: struct X { a: (bool, &'static str), b: usize} . /// pats: [(false, "foo"), 42] => X { a: (false, "foo"), b: 42 } 22 ( 0.00%) fn apply_constructor(mut self, pcx: PatCtxt<'_, 'p, 'tcx>, ctor: &Constructor<'tcx>) -> Self { . let pat = { 2 ( 0.00%) let len = self.0.len(); 14 ( 0.00%) let arity = ctor.arity(pcx); 6 ( 0.00%) let pats = self.0.drain((len - arity)..).rev(); 2 ( 0.00%) let fields = Fields::from_iter(pcx.cx, pats); 2 ( 0.00%) DeconstructedPat::new(ctor.clone(), fields, pcx.ty, DUMMY_SP) . }; . . self.0.push(pat); . 6 ( 0.00%) self 16 ( 0.00%) } . } . . /// Report that a match of a `non_exhaustive` enum marked with `non_exhaustive_omitted_patterns` . /// is not exhaustive enough. . /// . /// NB: The partner lint for structs lives in `compiler/rustc_typeck/src/check/pat.rs`. . fn lint_non_exhaustive_omitted_patterns<'p, 'tcx>( . cx: &MatchCheckCtxt<'p, 'tcx>, -- line 725 ---------------------------------------- -- line 760 ---------------------------------------- . /// This is used both for reachability checking (if a pattern isn't useful in . /// relation to preceding patterns, it is not reachable) and exhaustiveness . /// checking (if a wildcard pattern is useful in relation to a matrix, the . /// matrix isn't exhaustive). . /// . /// `is_under_guard` is used to inform if the pattern has a guard. If it . /// has one it must not be inserted into the matrix. This shouldn't be . /// relied on for soundness. 604,282 ( 0.00%) #[instrument( . level = "debug", . skip(cx, matrix, witness_preference, hir_id, is_under_guard, is_top_level) 284,368 ( 0.00%) )] . fn is_useful<'p, 'tcx>( . cx: &MatchCheckCtxt<'p, 'tcx>, . matrix: &Matrix<'p, 'tcx>, . v: &PatStack<'p, 'tcx>, . witness_preference: ArmType, . hir_id: HirId, . is_under_guard: bool, . is_top_level: bool, -- line 779 ---------------------------------------- -- line 781 ---------------------------------------- . debug!("matrix,v={:?}{:?}", matrix, v); . let Matrix { patterns: rows, .. } = matrix; . . // The base case. We are pattern-matching on () and the return value is . // based on whether our matrix has a row or not. . // NOTE: This could potentially be optimized by checking rows.is_empty() . // first and then, if v is non-empty, the return value is based on whether . // the type of the tuple we're checking is inhabited or not. 35,546 ( 0.00%) if v.is_empty() { 14,482 ( 0.00%) let ret = if rows.is_empty() { . Usefulness::new_useful(witness_preference) . } else { . Usefulness::new_not_useful(witness_preference) . }; . debug!(?ret); 101,374 ( 0.00%) return ret; . } . . debug_assert!(rows.iter().all(|r| r.len() == v.len())); . . let ty = v.head().ty(); . let is_non_exhaustive = cx.is_foreign_non_exhaustive_enum(ty); 105,320 ( 0.00%) let pcx = PatCtxt { cx, ty, span: v.head().span(), is_top_level, is_non_exhaustive }; . . // If the first pattern is an or-pattern, expand it. . let mut ret = Usefulness::new_not_useful(witness_preference); 21,064 ( 0.00%) if v.head().is_or_pat() { . debug!("expanding or-pattern"); . // We try each or-pattern branch in turn. . let mut matrix = matrix.clone(); 970 ( 0.00%) for v in v.expand_or_pat() { . let usefulness = ensure_sufficient_stack(|| { 7,760 ( 0.00%) is_useful(cx, &matrix, &v, witness_preference, hir_id, is_under_guard, false) . }); 7,275 ( 0.00%) ret.extend(usefulness); . // If pattern has a guard don't add it to the matrix. 970 ( 0.00%) if !is_under_guard { . // We push the already-seen patterns into the matrix in order to detect redundant . // branches like `Some(_) | Some(0)`. 3,353 ( 0.00%) matrix.push(v); . } . } . } else { . let v_ctor = v.head().ctor(); 42,599 ( 0.00%) if let Constructor::IntRange(ctor_range) = &v_ctor { . // Lint on likely incorrect range patterns (#63987) 3,095 ( 0.00%) ctor_range.lint_overlapping_range_endpoints( 3,095 ( 0.00%) pcx, . matrix.heads(), . matrix.column_count().unwrap_or(0), . hir_id, . ) . } . // We split the head constructor of `v`. 167,920 ( 0.00%) let split_ctors = v_ctor.split(pcx, matrix.heads().map(DeconstructedPat::ctor)); 41,980 ( 0.00%) let is_non_exhaustive_and_wild = is_non_exhaustive && v_ctor.is_wildcard(); . // For each constructor, we compute whether there's a value that starts with it that would . // witness the usefulness of `v`. . let start_matrix = &matrix; 644,962 ( 0.00%) for ctor in split_ctors { . debug!("specialize({:?})", ctor); . // We cache the result of `Fields::wildcards` because it is used a lot. 120,055 ( 0.00%) let spec_matrix = start_matrix.specialize_constructor(pcx, &ctor); . let v = v.pop_head_constructor(cx, &ctor); . let usefulness = ensure_sufficient_stack(|| { 336,154 ( 0.00%) is_useful(cx, &spec_matrix, &v, witness_preference, hir_id, is_under_guard, false) . }); 264,121 ( 0.00%) let usefulness = usefulness.apply_constructor(pcx, start_matrix, &ctor); . . // When all the conditions are met we have a match with a `non_exhaustive` enum . // that has the potential to trigger the `non_exhaustive_omitted_patterns` lint. . // To understand the workings checkout `Constructor::split` and `SplitWildcard::new/into_ctors` 72,018 ( 0.00%) if is_non_exhaustive_and_wild . // We check that the match has a wildcard pattern and that that wildcard is useful, . // meaning there are variants that are covered by the wildcard. Without the check . // for `witness_preference` the lint would trigger on `if let NonExhaustiveEnum::A = foo {}` . && usefulness.is_useful() && matches!(witness_preference, RealArm) . && matches!( . &ctor, . Constructor::Missing { nonexhaustive_enum_missing_real_variants: true } . ) -- line 861 ---------------------------------------- -- line 877 ---------------------------------------- . .cloned() . .map(|missing_ctor| DeconstructedPat::wild_from_ctor(pcx, missing_ctor)) . .collect::>() . }; . . lint_non_exhaustive_omitted_patterns(pcx.cx, pcx.ty, pcx.span, hir_id, patterns); . } . 168,077 ( 0.00%) ret.extend(usefulness); . } . } . 28,381 ( 0.00%) if ret.is_useful() { . v.head().set_reachable(); . } . . debug!(?ret); 84,256 ( 0.00%) ret . } . . /// The arm of a match expression. . #[derive(Clone, Copy)] . crate struct MatchArm<'p, 'tcx> { . /// The pattern must have been lowered through `check_match::MatchVisitor::lower_pattern`. . crate pat: &'p DeconstructedPat<'p, 'tcx>, . crate hir_id: HirId, -- line 902 ---------------------------------------- -- line 923 ---------------------------------------- . crate non_exhaustiveness_witnesses: Vec>, . } . . /// The entrypoint for the usefulness algorithm. Computes whether a match is exhaustive and which . /// of its arms are reachable. . /// . /// Note: the input patterns must have been lowered through . /// `check_match::MatchVisitor::lower_pattern`. 42,559 ( 0.00%) crate fn compute_match_usefulness<'p, 'tcx>( . cx: &MatchCheckCtxt<'p, 'tcx>, . arms: &[MatchArm<'p, 'tcx>], . scrut_hir_id: HirId, . scrut_ty: Ty<'tcx>, . ) -> UsefulnessReport<'p, 'tcx> { . let mut matrix = Matrix::empty(); . let arm_usefulness: Vec<_> = arms . .iter() . .copied() . .map(|arm| { 21,543 ( 0.00%) let v = PatStack::from_pattern(arm.pat); 107,715 ( 0.00%) is_useful(cx, &matrix, &v, RealArm, arm.hir_id, arm.has_guard, true); 21,543 ( 0.00%) if !arm.has_guard { 50,211 ( 0.00%) matrix.push(v); . } 7,181 ( 0.00%) let reachability = if arm.pat.is_reachable() { 21,543 ( 0.00%) Reachability::Reachable(arm.pat.unreachable_spans()) . } else { . Reachability::Unreachable . }; 14,362 ( 0.00%) (arm, reachability) 14,354 ( 0.00%) }) . .collect(); . 3,869 ( 0.00%) let wild_pattern = cx.pattern_arena.alloc(DeconstructedPat::wildcard(scrut_ty)); . let v = PatStack::from_pattern(wild_pattern); 46,428 ( 0.00%) let usefulness = is_useful(cx, &matrix, &v, FakeExtraWildcard, scrut_hir_id, false, true); 7,738 ( 0.00%) let non_exhaustiveness_witnesses = match usefulness { 3,829 ( 0.00%) WithWitnesses(pats) => pats.into_iter().map(|w| w.single_pattern()).collect(), . NoWitnesses { .. } => bug!(), . }; 30,952 ( 0.00%) UsefulnessReport { arm_usefulness, non_exhaustiveness_witnesses } 34,821 ( 0.00%) } 117,520 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_index/src/bit_set.rs -------------------------------------------------------------------------------- Ir -- line 30 ---------------------------------------- . // Both start and end are inclusive. . let start = match range.start_bound().cloned() { . Bound::Included(start) => start.index(), . Bound::Excluded(start) => start.index() + 1, . Bound::Unbounded => 0, . }; . let end = match range.end_bound().cloned() { . Bound::Included(end) => end.index(), 15 ( 0.00%) Bound::Excluded(end) => end.index().checked_sub(1)?, . Bound::Unbounded => domain - 1, . }; 30 ( 0.00%) assert!(end < domain); 30 ( 0.00%) if start > end { . return None; . } . Some((start, end)) . } . . macro_rules! bit_relations_inherent_impls { . () => { . /// Sets `self = self | other` and returns `true` if `self` changed . /// (i.e., if new bits were added). 1,589,812 ( 0.01%) pub fn union(&mut self, other: &Rhs) -> bool . where . Self: BitRelations, . { . >::union(self, other) 1,291,158 ( 0.01%) } . . /// Sets `self = self - other` and returns `true` if `self` changed. . /// (i.e., if any bits were removed). 493,995 ( 0.00%) pub fn subtract(&mut self, other: &Rhs) -> bool . where . Self: BitRelations, . { . >::subtract(self, other) 493,995 ( 0.00%) } . . /// Sets `self = self & other` and return `true` if `self` changed. . /// (i.e., if any bits were removed). . pub fn intersect(&mut self, other: &Rhs) -> bool . where . Self: BitRelations, . { . >::intersect(self, other) -- line 74 ---------------------------------------- -- line 92 ---------------------------------------- . domain_size: usize, . words: Vec, . marker: PhantomData, . } . . impl BitSet { . /// Gets the domain size. . pub fn domain_size(&self) -> usize { 1,035 ( 0.00%) self.domain_size . } . } . . impl BitSet { . /// Creates a new, empty bitset with a given `domain_size`. . #[inline] . pub fn new_empty(domain_size: usize) -> BitSet { . let num_words = num_words(domain_size); 223,373 ( 0.00%) BitSet { domain_size, words: vec![0; num_words], marker: PhantomData } . } . . /// Creates a new, filled bitset with a given `domain_size`. . #[inline] . pub fn new_filled(domain_size: usize) -> BitSet { . let num_words = num_words(domain_size); 10,100 ( 0.00%) let mut result = BitSet { domain_size, words: vec![!0; num_words], marker: PhantomData }; . result.clear_excess_bits(); . result . } . . /// Clear all elements. . #[inline] . pub fn clear(&mut self) { . for word in &mut self.words { 7,438 ( 0.00%) *word = 0; . } . } . . /// Clear excess bits in the final word. . fn clear_excess_bits(&mut self) { 1,745 ( 0.00%) let num_bits_in_final_word = self.domain_size % WORD_BITS; 7,530 ( 0.00%) if num_bits_in_final_word > 0 { 5,781 ( 0.00%) let mask = (1 << num_bits_in_final_word) - 1; 13,305 ( 0.00%) let final_word_idx = self.words.len() - 1; 3,762 ( 0.00%) self.words[final_word_idx] &= mask; . } . } . . /// Count the number of set bits in the set. . pub fn count(&self) -> usize { . self.words.iter().map(|e| e.count_ones() as usize).sum() . } . . /// Returns `true` if `self` contains `elem`. . #[inline] . pub fn contains(&self, elem: T) -> bool { 3,193,205 ( 0.02%) assert!(elem.index() < self.domain_size); . let (word_index, mask) = word_index_and_mask(elem); 3,434,701 ( 0.02%) (self.words[word_index] & mask) != 0 . } . . /// Is `self` is a (non-strict) superset of `other`? . #[inline] . pub fn superset(&self, other: &BitSet) -> bool { . assert_eq!(self.domain_size, other.domain_size); . self.words.iter().zip(&other.words).all(|(a, b)| (a & b) == *b) . } . . /// Is the set empty? . #[inline] . pub fn is_empty(&self) -> bool { 43 ( 0.00%) self.words.iter().all(|a| *a == 0) . } . . /// Insert `elem`. Returns whether the set has changed. . #[inline] . pub fn insert(&mut self, elem: T) -> bool { 4,438,060 ( 0.03%) assert!(elem.index() < self.domain_size); . let (word_index, mask) = word_index_and_mask(elem); . let word_ref = &mut self.words[word_index]; 1,731,554 ( 0.01%) let word = *word_ref; 3,463,108 ( 0.02%) let new_word = word | mask; 2,189,824 ( 0.01%) *word_ref = new_word; 1,851,654 ( 0.01%) new_word != word . } . . #[inline] . pub fn insert_range(&mut self, elems: impl RangeBounds) { . let Some((start, end)) = inclusive_start_end(elems, self.domain_size) else { . return; . }; . -- line 182 ---------------------------------------- -- line 199 ---------------------------------------- . } else { . self.words[start_word_index] |= end_mask | (end_mask - start_mask); . } . } . . /// Sets all bits to true. . pub fn insert_all(&mut self) { . for word in &mut self.words { 3,490 ( 0.00%) *word = !0; . } . self.clear_excess_bits(); . } . . /// Returns `true` if the set has changed. . #[inline] . pub fn remove(&mut self, elem: T) -> bool { 1,272,745 ( 0.01%) assert!(elem.index() < self.domain_size); . let (word_index, mask) = word_index_and_mask(elem); . let word_ref = &mut self.words[word_index]; 114,150 ( 0.00%) let word = *word_ref; 1,378,597 ( 0.01%) let new_word = word & !mask; 682,632 ( 0.00%) *word_ref = new_word; 228,300 ( 0.00%) new_word != word . } . . /// Gets a slice of the underlying words. . pub fn words(&self) -> &[Word] { . &self.words . } . . /// Iterates over the indices of set bits in a sorted order. -- line 229 ---------------------------------------- -- line 273 ---------------------------------------- . not_already |= (self.words[current_index] ^ new_bit_mask) != 0; . // Any bits in the tail? Note `clear_excess_bits` before. . not_already |= self.words[current_index + 1..].iter().any(|&x| x != 0); . . not_already . } . . fn last_set_in(&self, range: impl RangeBounds) -> Option { 15 ( 0.00%) let (start, end) = inclusive_start_end(range, self.domain_size)?; . let (start_word_index, _) = word_index_and_mask(start); . let (end_word_index, end_mask) = word_index_and_mask(end); . 75 ( 0.00%) let end_word = self.words[end_word_index] & (end_mask | (end_mask - 1)); 30 ( 0.00%) if end_word != 0 { 36 ( 0.00%) let pos = max_bit(end_word) + WORD_BITS * end_word_index; 24 ( 0.00%) if start <= pos { . return Some(T::new(pos)); . } . } . . // We exclude end_word_index from the range here, because we don't want . // to limit ourselves to *just* the last word: the bits set it in may be . // after `end`, so it may not work out. . if let Some(offset) = 3 ( 0.00%) self.words[start_word_index..end_word_index].iter().rposition(|&w| w != 0) . { 6 ( 0.00%) let word_idx = start_word_index + offset; 3 ( 0.00%) let start_word = self.words[word_idx]; 15 ( 0.00%) let pos = max_bit(start_word) + WORD_BITS * word_idx; 6 ( 0.00%) if start <= pos { . return Some(T::new(pos)); . } . } . . None . } . . bit_relations_inherent_impls! {} . } . . // dense REL dense . impl BitRelations> for BitSet { . fn union(&mut self, other: &BitSet) -> bool { 895,962 ( 0.01%) assert_eq!(self.domain_size, other.domain_size); 6,493,243 ( 0.04%) bitwise(&mut self.words, &other.words, |a, b| a | b) . } . . fn subtract(&mut self, other: &BitSet) -> bool { . assert_eq!(self.domain_size, other.domain_size); 20,422 ( 0.00%) bitwise(&mut self.words, &other.words, |a, b| a & !b) . } . . fn intersect(&mut self, other: &BitSet) -> bool { . assert_eq!(self.domain_size, other.domain_size); . bitwise(&mut self.words, &other.words, |a, b| a & b) . } . } . . // Applies a function to mutate a bitset, and returns true if any . // of the applications return true . fn sequential_update( . mut self_update: impl FnMut(T) -> bool, . it: impl Iterator, . ) -> bool { . let mut changed = false; 184,195 ( 0.00%) for elem in it { 552,585 ( 0.00%) changed |= self_update(elem); . } . changed 393,926 ( 0.00%) } . . // Optimization of intersection for SparseBitSet that's generic . // over the RHS . fn sparse_intersect( . set: &mut SparseBitSet, . other_contains: impl Fn(&T) -> bool, . ) -> bool { . let size = set.elems.len(); -- line 350 ---------------------------------------- -- line 413 ---------------------------------------- . HybridBitSet::Dense(dense) => dense.intersect(other), . } . } . } . . // dense REL hybrid . impl BitRelations> for BitSet { . fn union(&mut self, other: &HybridBitSet) -> bool { 395,196 ( 0.00%) assert_eq!(self.domain_size, other.domain_size()); 197,598 ( 0.00%) match other { . HybridBitSet::Sparse(sparse) => { . sequential_update(|elem| self.insert(elem), sparse.iter().cloned()) . } . HybridBitSet::Dense(dense) => self.union(dense), . } . } . . fn subtract(&mut self, other: &HybridBitSet) -> bool { 395,196 ( 0.00%) assert_eq!(self.domain_size, other.domain_size()); 197,598 ( 0.00%) match other { . HybridBitSet::Sparse(sparse) => { . sequential_update(|elem| self.remove(elem), sparse.iter().cloned()) . } . HybridBitSet::Dense(dense) => self.subtract(dense), . } . } . . fn intersect(&mut self, other: &HybridBitSet) -> bool { -- line 440 ---------------------------------------- -- line 455 ---------------------------------------- . HybridBitSet::Dense(dense) => self.intersect(dense), . } . } . } . . // hybrid REL hybrid . impl BitRelations> for HybridBitSet { . fn union(&mut self, other: &HybridBitSet) -> bool { 36,498 ( 0.00%) assert_eq!(self.domain_size(), other.domain_size()); 12,166 ( 0.00%) match self { . HybridBitSet::Sparse(_) => { 12,166 ( 0.00%) match other { . HybridBitSet::Sparse(other_sparse) => { . // Both sets are sparse. Add the elements in . // `other_sparse` to `self` one at a time. This . // may or may not cause `self` to be densified. . let mut changed = false; . for elem in other_sparse.iter() { 36,792 ( 0.00%) changed |= self.insert(*elem); . } . changed . } . . HybridBitSet::Dense(other_dense) => self.union(other_dense), . } . } . -- line 481 ---------------------------------------- -- line 511 ---------------------------------------- . } . } . . impl Clone for BitSet { . fn clone(&self) -> Self { . BitSet { domain_size: self.domain_size, words: self.words.clone(), marker: PhantomData } . } . 1,789,865 ( 0.01%) fn clone_from(&mut self, from: &Self) { 1,079,545 ( 0.01%) if self.domain_size != from.domain_size { . self.words.resize(from.domain_size, 0); . self.domain_size = from.domain_size; . } . . self.words.copy_from_slice(&from.words); . } . } . -- line 528 ---------------------------------------- -- line 599 ---------------------------------------- . } . } . } . . impl<'a, T: Idx> Iterator for BitIter<'a, T> { . type Item = T; . fn next(&mut self) -> Option { . loop { 2,672,187 ( 0.02%) if self.word != 0 { . // Get the position of the next set bit in the current word, . // then clear the bit. . let bit_pos = self.word.trailing_zeros() as usize; . let bit = 1 << bit_pos; . self.word ^= bit; 558,720 ( 0.00%) return Some(T::new(bit_pos + self.offset)); . } . . // Move onto the next word. `wrapping_add()` is needed to handle . // the degenerate initial value given to `offset` in `new()`. . let word = self.iter.next()?; 998,699 ( 0.01%) self.word = *word; . self.offset = self.offset.wrapping_add(WORD_BITS); . } . } . } . . #[inline] . fn bitwise(out_vec: &mut [Word], in_vec: &[Word], op: Op) -> bool . where . Op: Fn(Word, Word) -> Word, . { 1,197,156 ( 0.01%) assert_eq!(out_vec.len(), in_vec.len()); . let mut changed = 0; 587,765 ( 0.00%) for (out_elem, in_elem) in iter::zip(out_vec, in_vec) { 6,798,207 ( 0.04%) let old_val = *out_elem; 6,058,744 ( 0.03%) let new_val = op(old_val, *in_elem); 6,503,111 ( 0.04%) *out_elem = new_val; . // This is essentially equivalent to a != with changed being a bool, but . // in practice this code gets auto-vectorized by the compiler for most . // operators. Using != here causes us to generate quite poor code as the . // compiler tries to go back to a boolean on each loop iteration. 13,596,819 ( 0.08%) changed |= old_val ^ new_val; . } . changed != 0 . } . . const SPARSE_MAX: usize = 8; . . /// A fixed-size bitset type with a sparse representation and a maximum of . /// `SPARSE_MAX` elements. The elements are stored as a sorted `ArrayVec` with . /// no duplicates. . /// . /// This type is used by `HybridBitSet`; do not use directly. . #[derive(Clone, Debug)] . pub struct SparseBitSet { 179,232 ( 0.00%) domain_size: usize, . elems: ArrayVec, . } . . impl SparseBitSet { . fn new_empty(domain_size: usize) -> Self { . SparseBitSet { domain_size, elems: ArrayVec::new() } . } . . fn len(&self) -> usize { 482,432 ( 0.00%) self.elems.len() . } . . fn is_empty(&self) -> bool { . self.elems.len() == 0 . } . . fn contains(&self, elem: T) -> bool { 5,835 ( 0.00%) assert!(elem.index() < self.domain_size); . self.elems.contains(&elem) . } . . fn insert(&mut self, elem: T) -> bool { 481,618 ( 0.00%) assert!(elem.index() < self.domain_size); 207,739 ( 0.00%) let changed = if let Some(i) = self.elems.iter().position(|&e| e.index() >= elem.index()) { 82,465 ( 0.00%) if self.elems[i] == elem { . // `elem` is already in the set. . false . } else { . // `elem` is smaller than one or more existing elements. . self.elems.insert(i, elem); . true . } . } else { . // `elem` is larger than all existing elements. . self.elems.push(elem); . true . }; 481,618 ( 0.00%) assert!(self.len() <= SPARSE_MAX); . changed . } . . fn remove(&mut self, elem: T) -> bool { 398,040 ( 0.00%) assert!(elem.index() < self.domain_size); . if let Some(i) = self.elems.iter().position(|&e| e == elem) { 108,612 ( 0.00%) self.elems.remove(i); . true . } else { . false . } . } . . fn to_dense(&self) -> BitSet { . let mut dense = BitSet::new_empty(self.domain_size); . for elem in self.elems.iter() { 3,136 ( 0.00%) dense.insert(*elem); . } . dense . } . . fn iter(&self) -> slice::Iter<'_, T> { 35,574 ( 0.00%) self.elems.iter() . } . . bit_relations_inherent_impls! {} . } . . impl SparseBitSet { . fn last_set_in(&self, range: impl RangeBounds) -> Option { . let mut last_leq = None; -- line 723 ---------------------------------------- -- line 738 ---------------------------------------- . /// number of elements, but a large `domain_size`, and are cleared frequently. . /// . /// `T` is an index type, typically a newtyped `usize` wrapper, but it can also . /// just be `usize`. . /// . /// All operations that involve an element will panic if the element is equal . /// to or greater than the domain size. All operations that involve two bitsets . /// will panic if the bitsets have differing domain sizes. 1,635,696 ( 0.01%) #[derive(Clone)] . pub enum HybridBitSet { . Sparse(SparseBitSet), . Dense(BitSet), . } . . impl fmt::Debug for HybridBitSet { . fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result { . match self { -- line 754 ---------------------------------------- -- line 755 ---------------------------------------- . Self::Sparse(b) => b.fmt(w), . Self::Dense(b) => b.fmt(w), . } . } . } . . impl HybridBitSet { . pub fn new_empty(domain_size: usize) -> Self { 2,204 ( 0.00%) HybridBitSet::Sparse(SparseBitSet::new_empty(domain_size)) . } . . pub fn domain_size(&self) -> usize { . match self { . HybridBitSet::Sparse(sparse) => sparse.domain_size, . HybridBitSet::Dense(dense) => dense.domain_size, . } . } . . pub fn clear(&mut self) { . let domain_size = self.domain_size(); 21,980 ( 0.00%) *self = HybridBitSet::new_empty(domain_size); . } . . pub fn contains(&self, elem: T) -> bool { 9,228 ( 0.00%) match self { . HybridBitSet::Sparse(sparse) => sparse.contains(elem), . HybridBitSet::Dense(dense) => dense.contains(elem), . } . } . . pub fn superset(&self, other: &HybridBitSet) -> bool { . match (self, other) { . (HybridBitSet::Dense(self_dense), HybridBitSet::Dense(other_dense)) => { -- line 787 ---------------------------------------- -- line 799 ---------------------------------------- . HybridBitSet::Sparse(sparse) => sparse.is_empty(), . HybridBitSet::Dense(dense) => dense.is_empty(), . } . } . . /// Returns the previous element present in the bitset from `elem`, . /// inclusively of elem. That is, will return `Some(elem)` if elem is in the . /// bitset. 35,604 ( 0.00%) pub fn last_set_in(&self, range: impl RangeBounds) -> Option . where . T: Ord, . { 35,604 ( 0.00%) match self { . HybridBitSet::Sparse(sparse) => sparse.last_set_in(range), . HybridBitSet::Dense(dense) => dense.last_set_in(range), . } 53,406 ( 0.00%) } . 2,189,637 ( 0.01%) pub fn insert(&mut self, elem: T) -> bool { . // No need to check `elem` against `self.domain_size` here because all . // the match cases check it, one way or another. 486,586 ( 0.00%) match self { 482,432 ( 0.00%) HybridBitSet::Sparse(sparse) if sparse.len() < SPARSE_MAX => { . // The set is sparse and has space for `elem`. . sparse.insert(elem) . } . HybridBitSet::Sparse(sparse) if sparse.contains(elem) => { . // The set is sparse and does not have space for `elem`, but . // that doesn't matter because `elem` is already present. . false . } . HybridBitSet::Sparse(sparse) => { . // The set is sparse and full. Convert to a dense set. . let mut dense = sparse.to_dense(); . let changed = dense.insert(elem); 392 ( 0.00%) assert!(changed); 2,352 ( 0.00%) *self = HybridBitSet::Dense(dense); . changed . } . HybridBitSet::Dense(dense) => dense.insert(elem), . } 1,946,344 ( 0.01%) } . . pub fn insert_range(&mut self, elems: impl RangeBounds) { . // No need to check `elem` against `self.domain_size` here because all . // the match cases check it, one way or another. . let start = match elems.start_bound().cloned() { . Bound::Included(start) => start.index(), . Bound::Excluded(start) => start.index() + 1, . Bound::Unbounded => 0, -- line 848 ---------------------------------------- -- line 879 ---------------------------------------- . match self { . HybridBitSet::Sparse(_) => { . *self = HybridBitSet::Dense(BitSet::new_filled(domain_size)); . } . HybridBitSet::Dense(dense) => dense.insert_all(), . } . } . 198,266 ( 0.00%) pub fn remove(&mut self, elem: T) -> bool { . // Note: we currently don't bother going from Dense back to Sparse. 398,452 ( 0.00%) match self { . HybridBitSet::Sparse(sparse) => sparse.remove(elem), . HybridBitSet::Dense(dense) => dense.remove(elem), . } 396,532 ( 0.00%) } . . /// Converts to a dense set, consuming itself in the process. . pub fn to_dense(self) -> BitSet { . match self { . HybridBitSet::Sparse(sparse) => sparse.to_dense(), . HybridBitSet::Dense(dense) => dense, . } . } . . pub fn iter(&self) -> HybridIter<'_, T> { 8,152 ( 0.00%) match self { 15,715 ( 0.00%) HybridBitSet::Sparse(sparse) => HybridIter::Sparse(sparse.iter()), . HybridBitSet::Dense(dense) => HybridIter::Dense(dense.iter()), . } . } . . bit_relations_inherent_impls! {} . } . . pub enum HybridIter<'a, T: Idx> { -- line 913 ---------------------------------------- -- line 935 ---------------------------------------- . /// to or greater than the domain size. . #[derive(Clone, Debug, PartialEq)] . pub struct GrowableBitSet { . bit_set: BitSet, . } . . impl GrowableBitSet { . /// Ensure that the set can hold at least `min_domain_size` elements. 398,538 ( 0.00%) pub fn ensure(&mut self, min_domain_size: usize) { 113,868 ( 0.00%) if self.bit_set.domain_size < min_domain_size { 2,370 ( 0.00%) self.bit_set.domain_size = min_domain_size; . } . . let min_num_words = num_words(min_domain_size); 227,736 ( 0.00%) if self.bit_set.words.len() < min_num_words { . self.bit_set.words.resize(min_num_words, 0) . } 341,604 ( 0.00%) } . . pub fn new_empty() -> GrowableBitSet { 9,432 ( 0.00%) GrowableBitSet { bit_set: BitSet::new_empty(0) } . } . . pub fn with_capacity(capacity: usize) -> GrowableBitSet { 8 ( 0.00%) GrowableBitSet { bit_set: BitSet::new_empty(capacity) } . } . . /// Returns `true` if the set has changed. . #[inline] . pub fn insert(&mut self, elem: T) -> bool { 266,526 ( 0.00%) self.ensure(elem.index() + 1); . self.bit_set.insert(elem) . } . . /// Returns `true` if the set has changed. . #[inline] . pub fn remove(&mut self, elem: T) -> bool { 111 ( 0.00%) self.ensure(elem.index() + 1); . self.bit_set.remove(elem) . } . . #[inline] . pub fn is_empty(&self) -> bool { . self.bit_set.is_empty() . } . . #[inline] . pub fn contains(&self, elem: T) -> bool { . let (word_index, mask) = word_index_and_mask(elem); 13,050 ( 0.00%) self.bit_set.words.get(word_index).map_or(false, |word| (word & mask) != 0) . } . } . . /// A fixed-size 2D bit matrix type with a dense representation. . /// . /// `R` and `C` are index types used to identify rows and columns respectively; . /// typically newtyped `usize` wrappers, but they can also just be `usize`. . /// -- line 992 ---------------------------------------- -- line 1001 ---------------------------------------- . } . . impl BitMatrix { . /// Creates a new `rows x columns` matrix, initially empty. . pub fn new(num_rows: usize, num_columns: usize) -> BitMatrix { . // For every element, we need one bit for every other . // element. Round up to an even number of words. . let words_per_row = num_words(num_columns); 10,812 ( 0.00%) BitMatrix { . num_rows, . num_columns, 6,354 ( 0.00%) words: vec![0; num_rows * words_per_row], . marker: PhantomData, . } . } . . /// Creates a new matrix, with `row` used as the value for every row. . pub fn from_row_n(row: &BitSet, num_rows: usize) -> BitMatrix { . let num_columns = row.domain_size(); . let words_per_row = num_words(num_columns); -- line 1020 ---------------------------------------- -- line 1029 ---------------------------------------- . . pub fn rows(&self) -> impl Iterator { . (0..self.num_rows).map(R::new) . } . . /// The range of bits for a given row. . fn range(&self, row: R) -> (usize, usize) { . let words_per_row = num_words(self.num_columns); 148,330 ( 0.00%) let start = row.index() * words_per_row; 125,900 ( 0.00%) (start, start + words_per_row) . } . . /// Sets the cell at `(row, column)` to true. Put another way, insert . /// `column` to the bitset for `row`. . /// . /// Returns `true` if this changed the matrix. . pub fn insert(&mut self, row: R, column: C) -> bool { 79,822 ( 0.00%) assert!(row.index() < self.num_rows && column.index() < self.num_columns); . let (start, _) = self.range(row); . let (word_index, mask) = word_index_and_mask(column); . let words = &mut self.words[..]; 81,040 ( 0.00%) let word = words[start + word_index]; 32,416 ( 0.00%) let new_word = word | mask; 16,208 ( 0.00%) words[start + word_index] = new_word; 32,416 ( 0.00%) word != new_word . } . . /// Do the bits from `row` contain `column`? Put another way, is . /// the matrix cell at `(row, column)` true? Put yet another way, . /// if the matrix represents (transitive) reachability, can . /// `row` reach `column`? 6,222 ( 0.00%) pub fn contains(&self, row: R, column: C) -> bool { 31,110 ( 0.00%) assert!(row.index() < self.num_rows && column.index() < self.num_columns); . let (start, _) = self.range(row); . let (word_index, mask) = word_index_and_mask(column); 31,110 ( 0.00%) (self.words[start + word_index] & mask) != 0 12,444 ( 0.00%) } . . /// Returns those indices that are true in rows `a` and `b`. This . /// is an *O*(*n*) operation where *n* is the number of elements . /// (somewhat independent from the actual size of the . /// intersection, in particular). . pub fn intersect_rows(&self, row1: R, row2: R) -> Vec { . assert!(row1.index() < self.num_rows && row2.index() < self.num_rows); . let (row1_start, row1_end) = self.range(row1); -- line 1073 ---------------------------------------- -- line 1090 ---------------------------------------- . . /// Adds the bits from row `read` to the bits from row `write`, and . /// returns `true` if anything changed. . /// . /// This is used when computing transitive reachability because if . /// you have an edge `write -> read`, because in that case . /// `write` can reach everything that `read` can (and . /// potentially more). 14,990 ( 0.00%) pub fn union_rows(&mut self, read: R, write: R) -> bool { 81,040 ( 0.00%) assert!(read.index() < self.num_rows && write.index() < self.num_rows); 16,208 ( 0.00%) let (read_start, read_end) = self.range(read); . let (write_start, write_end) = self.range(write); . let words = &mut self.words[..]; . let mut changed = false; . for (read_index, write_index) in iter::zip(read_start..read_end, write_start..write_end) { 90,784 ( 0.00%) let word = words[write_index]; 48,624 ( 0.00%) let new_word = word | words[read_index]; 16,208 ( 0.00%) words[write_index] = new_word; 82,258 ( 0.00%) changed |= word != new_word; . } . changed 44,970 ( 0.00%) } . . /// Adds the bits from `with` to the bits from row `write`, and . /// returns `true` if anything changed. . pub fn union_row_with(&mut self, with: &BitSet, write: R) -> bool { . assert!(write.index() < self.num_rows); . assert_eq!(with.domain_size(), self.num_columns); . let (write_start, write_end) = self.range(write); . let mut changed = false; -- line 1119 ---------------------------------------- -- line 1209 ---------------------------------------- . /// Creates a new empty sparse bit matrix with no rows or columns. . pub fn new(num_columns: usize) -> Self { . Self { num_columns, rows: IndexVec::new() } . } . . fn ensure_row(&mut self, row: R) -> &mut HybridBitSet { . // Instantiate any missing rows up to and including row `row` with an empty HybridBitSet. . // Then replace row `row` with a full HybridBitSet if necessary. 10,193 ( 0.00%) self.rows.get_or_insert_with(row, || HybridBitSet::new_empty(self.num_columns)) . } . . /// Sets the cell at `(row, column)` to true. Put another way, insert . /// `column` to the bitset for `row`. . /// . /// Returns `true` if this changed the matrix. . pub fn insert(&mut self, row: R, column: C) -> bool { 9,830 ( 0.00%) self.ensure_row(row).insert(column) . } . . /// Sets the cell at `(row, column)` to false. Put another way, delete . /// `column` from the bitset for `row`. Has no effect if `row` does not . /// exist. . /// . /// Returns `true` if this changed the matrix. . pub fn remove(&mut self, row: R, column: C) -> bool { -- line 1233 ---------------------------------------- -- line 1255 ---------------------------------------- . . /// Adds the bits from row `read` to the bits from row `write`, and . /// returns `true` if anything changed. . /// . /// This is used when computing transitive reachability because if . /// you have an edge `write -> read`, because in that case . /// `write` can reach everything that `read` can (and . /// potentially more). 940,912 ( 0.01%) pub fn union_rows(&mut self, read: R, write: R) -> bool { 134,416 ( 0.00%) if read == write || self.row(read).is_none() { . return false; . } . . self.ensure_row(write); 66,913 ( 0.00%) if let (Some(read_row), Some(write_row)) = self.rows.pick2_mut(read, write) { . write_row.union(read_row) . } else { . unreachable!() . } 1,209,744 ( 0.01%) } . . /// Insert all bits in the given row. . pub fn insert_all_into_row(&mut self, row: R) { . self.ensure_row(row).insert_all(); . } . . pub fn rows(&self) -> impl Iterator { . self.rows.indices() -- line 1282 ---------------------------------------- -- line 1284 ---------------------------------------- . . /// Iterates through all the columns set to true in a given row of . /// the matrix. . pub fn iter<'a>(&'a self, row: R) -> impl Iterator + 'a { . self.row(row).into_iter().flat_map(|r| r.iter()) . } . . pub fn row(&self, row: R) -> Option<&HybridBitSet> { 302,337 ( 0.00%) if let Some(Some(row)) = self.rows.get(row) { Some(row) } else { None } . } . . /// Interescts `row` with `set`. `set` can be either `BitSet` or . /// `HybridBitSet`. Has no effect if `row` does not exist. . /// . /// Returns true if the row was changed. . pub fn intersect_row(&mut self, row: R, set: &Set) -> bool . where -- line 1300 ---------------------------------------- -- line 1329 ---------------------------------------- . HybridBitSet: BitRelations, . { . self.ensure_row(row).union(set) . } . } . . #[inline] . fn num_words(domain_size: T) -> usize { 1,007,663 ( 0.01%) (domain_size.index() + WORD_BITS - 1) / WORD_BITS . } . . #[inline] . fn word_index_and_mask(elem: T) -> (usize, Word) { . let elem = elem.index(); 8,527,241 ( 0.05%) let word_index = elem / WORD_BITS; 1,074,000 ( 0.01%) let mask = 1 << (elem % WORD_BITS); . (word_index, mask) . } . . #[inline] . fn max_bit(word: Word) -> usize { 6 ( 0.00%) WORD_BITS - 1 - word.leading_zeros() as usize . } . . /// Integral type used to represent the bit set. . pub trait FiniteBitSetTy: . BitAnd . + BitAndAssign . + BitOrAssign . + Clone -- line 1358 ---------------------------------------- 4,675,810 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 294 ---------------------------------------- . #[allow(deprecated)] . impl From for CollectionAllocErr { . fn from(_: LayoutErr) -> Self { . CollectionAllocErr::CapacityOverflow . } . } . . fn infallible(result: Result) -> T { 3,400,544 ( 0.02%) match result { . Ok(x) => x, . Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"), . Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout), . } . } . . /// FIXME: use `Layout::array` when we require a Rust version where it’s stable . /// https://github.com/rust-lang/rust/issues/55724 -- line 310 ---------------------------------------- -- line 422 ---------------------------------------- . #[cfg(feature = "union")] . impl SmallVecData { . #[inline] . unsafe fn inline(&self) -> *const A::Item { . self.inline.as_ptr() as *const A::Item . } . #[inline] . unsafe fn inline_mut(&mut self) -> *mut A::Item { 213,706 ( 0.00%) self.inline.as_mut_ptr() as *mut A::Item . } . #[inline] . fn from_inline(inline: MaybeUninit) -> SmallVecData { . SmallVecData { . inline: core::mem::ManuallyDrop::new(inline), . } . } . #[inline] . unsafe fn into_inline(self) -> MaybeUninit { . core::mem::ManuallyDrop::into_inner(self.inline) . } . #[inline] . unsafe fn heap(&self) -> (*mut A::Item, usize) { 29,270 ( 0.00%) self.heap . } . #[inline] . unsafe fn heap_mut(&mut self) -> &mut (*mut A::Item, usize) { . &mut self.heap . } . #[inline] . fn from_heap(ptr: *mut A::Item, len: usize) -> SmallVecData { . SmallVecData { heap: (ptr, len) } -- line 452 ---------------------------------------- -- line 557 ---------------------------------------- . #[inline] . pub fn new() -> SmallVec { . // Try to detect invalid custom implementations of `Array`. Hopefully, . // this check should be optimized away entirely for valid ones. . assert!( . mem::size_of::() == A::size() * mem::size_of::() . && mem::align_of::() >= mem::align_of::() . ); 2,000,620 ( 0.01%) SmallVec { . capacity: 0, . data: SmallVecData::from_inline(MaybeUninit::uninit()), . } . } . . /// Construct an empty vector with enough capacity pre-allocated to store at least `n` . /// elements. . /// -- line 573 ---------------------------------------- -- line 597 ---------------------------------------- . /// . /// let vec = vec![1, 2, 3, 4, 5]; . /// let small_vec: SmallVec<[_; 3]> = SmallVec::from_vec(vec); . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub fn from_vec(mut vec: Vec) -> SmallVec { 5,222 ( 0.00%) if vec.capacity() <= Self::inline_capacity() { . unsafe { . let mut data = SmallVecData::::from_inline(MaybeUninit::uninit()); . let len = vec.len(); . vec.set_len(0); . ptr::copy_nonoverlapping(vec.as_ptr(), data.inline_mut(), len); . . SmallVec { . capacity: len, . data, . } . } . } else { . let (ptr, cap, len) = (vec.as_mut_ptr(), vec.capacity(), vec.len()); . mem::forget(vec); . 8,070 ( 0.00%) SmallVec { . capacity: cap, . data: SmallVecData::from_heap(ptr, len), . } . } . } . . /// Constructs a new `SmallVec` on the stack from an `A` without . /// copying elements. -- line 629 ---------------------------------------- -- line 635 ---------------------------------------- . /// let small_vec: SmallVec<_> = SmallVec::from_buf(buf); . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub fn from_buf(buf: A) -> SmallVec { . SmallVec { . capacity: A::size(), 27,629 ( 0.00%) data: SmallVecData::from_inline(MaybeUninit::new(buf)), . } . } . . /// Constructs a new `SmallVec` on the stack from an `A` without . /// copying elements. Also sets the length, which must be less or . /// equal to the size of `buf`. . /// . /// ```rust -- line 651 ---------------------------------------- -- line 653 ---------------------------------------- . /// . /// let buf = [1, 2, 3, 4, 5, 0, 0, 0]; . /// let small_vec: SmallVec<_> = SmallVec::from_buf_and_len(buf, 5); . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec { 75,324 ( 0.00%) assert!(len <= A::size()); 225,972 ( 0.00%) unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) } . } . . /// Constructs a new `SmallVec` on the stack from an `A` without . /// copying elements. Also sets the length. The user is responsible . /// for ensuring that `len <= A::size()`. . /// . /// ```rust . /// use smallvec::SmallVec; -- line 670 ---------------------------------------- -- line 674 ---------------------------------------- . /// let small_vec: SmallVec<_> = unsafe { . /// SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), 5) . /// }; . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit, len: usize) -> SmallVec { 37,662 ( 0.00%) SmallVec { . capacity: len, . data: SmallVecData::from_inline(buf), . } . } . . /// Sets the length of a vector. . /// . /// This will explicitly set the size of the vector, without actually . /// modifying its buffers, so it is up to the caller to ensure that the . /// vector is actually the specified size. . pub unsafe fn set_len(&mut self, new_len: usize) { . let (_, len_ptr, _) = self.triple_mut(); 861,520 ( 0.00%) *len_ptr = new_len; . } . . /// The maximum number of elements this vector can hold inline . #[inline] . fn inline_capacity() -> usize { . if mem::size_of::() > 0 { 296 ( 0.00%) A::size() . } else { . // For zero-size items code like `ptr.add(offset)` always returns the same pointer. . // Therefore all items are at the same address, . // and any array size has capacity for infinitely many items. . // The capacity is limited by the bit width of the length field. . // . // `Vec` also does this: . // https://github.com/rust-lang/rust/blob/1.44.0/src/liballoc/raw_vec.rs#L186 -- line 710 ---------------------------------------- -- line 725 ---------------------------------------- . #[inline] . pub fn len(&self) -> usize { . self.triple().1 . } . . /// Returns `true` if the vector is empty . #[inline] . pub fn is_empty(&self) -> bool { 756,791 ( 0.00%) self.len() == 0 . } . . /// The number of items the vector can hold without reallocating . #[inline] . pub fn capacity(&self) -> usize { . self.triple().2 . } . . /// Returns a tuple with (data ptr, len, capacity) . /// Useful to get all SmallVec properties with a single check of the current storage variant. . #[inline] . fn triple(&self) -> (*const A::Item, usize, usize) { . unsafe { 28,962,126 ( 0.16%) if self.spilled() { . let (ptr, len) = self.data.heap(); . (ptr, len, self.capacity) . } else { . (self.data.inline(), self.capacity, Self::inline_capacity()) . } . } . } . . /// Returns a tuple with (data ptr, len ptr, capacity) . #[inline] . fn triple_mut(&mut self) -> (*mut A::Item, &mut usize, usize) { . unsafe { 26,593,337 ( 0.15%) if self.spilled() { 150,102 ( 0.00%) let &mut (ptr, ref mut len_ptr) = self.data.heap_mut(); . (ptr, len_ptr, self.capacity) . } else { . ( . self.data.inline_mut(), . &mut self.capacity, . Self::inline_capacity(), . ) . } . } . } . . /// Returns `true` if the data has spilled into a separate heap-allocated buffer. . #[inline] . pub fn spilled(&self) -> bool { 36,049,641 ( 0.20%) self.capacity > Self::inline_capacity() . } . . /// Creates a draining iterator that removes the specified range in the vector . /// and yields the removed items. . /// . /// Note 1: The element range is removed even if the iterator is only . /// partially consumed or not consumed at all. . /// -- line 784 ---------------------------------------- -- line 821 ---------------------------------------- . iter: range_slice.iter(), . vec: NonNull::from(self), . } . } . } . . /// Append an item to the vector. . #[inline] 269,175 ( 0.00%) pub fn push(&mut self, value: A::Item) { . unsafe { . let (mut ptr, mut len, cap) = self.triple_mut(); 2,513,057 ( 0.01%) if *len == cap { 1,742 ( 0.00%) self.reserve(1); 43,154 ( 0.00%) let &mut (heap_ptr, ref mut heap_len) = self.data.heap_mut(); . ptr = heap_ptr; . len = heap_len; . } 35,368 ( 0.00%) ptr::write(ptr.add(*len), value); 4,810,628 ( 0.03%) *len += 1; . } 215,340 ( 0.00%) } . . /// Remove an item from the end of the vector and return it, or None if empty. . #[inline] . pub fn pop(&mut self) -> Option { . unsafe { . let (ptr, len_ptr, _) = self.triple_mut(); 1,225,735 ( 0.01%) if *len_ptr == 0 { . return None; . } 245,727 ( 0.00%) let last_index = *len_ptr - 1; 246,068 ( 0.00%) *len_ptr = last_index; 224,050 ( 0.00%) Some(ptr::read(ptr.add(last_index))) . } 101 ( 0.00%) } . . /// Moves all the elements of `other` into `self`, leaving `other` empty. . /// . /// # Example . /// . /// ``` . /// # use smallvec::{SmallVec, smallvec}; . /// let mut v0: SmallVec<[u8; 16]> = smallvec![1, 2, 3]; -- line 863 ---------------------------------------- -- line 879 ---------------------------------------- . /// or if the capacity computation overflows `usize`. . pub fn grow(&mut self, new_cap: usize) { . infallible(self.try_grow(new_cap)) . } . . /// Re-allocate to set the capacity to `max(new_cap, inline_size())`. . /// . /// Panics if `new_cap` is less than the vector's length 15,605 ( 0.00%) pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> { . unsafe { 1,403 ( 0.00%) let (ptr, &mut len, cap) = self.triple_mut(); . let unspilled = !self.spilled(); 70,542 ( 0.00%) assert!(new_cap >= len); 70,542 ( 0.00%) if new_cap <= self.inline_size() { . if unspilled { . return Ok(()); . } . self.data = SmallVecData::from_inline(MaybeUninit::uninit()); . ptr::copy_nonoverlapping(ptr, self.data.inline_mut(), len); . self.capacity = len; . deallocate(ptr, cap); 70,542 ( 0.00%) } else if new_cap != cap { 63,787 ( 0.00%) let layout = layout_array::(new_cap)?; . debug_assert!(layout.size() > 0); . let new_alloc; 35,271 ( 0.00%) if unspilled { . new_alloc = NonNull::new(alloc::alloc::alloc(layout)) . .ok_or(CollectionAllocErr::AllocErr { layout })? . .cast() . .as_ptr(); . ptr::copy_nonoverlapping(ptr, new_alloc, len); . } else { . // This should never fail since the same succeeded . // when previously allocating `ptr`. 14,360 ( 0.00%) let old_layout = layout_array::(cap)?; . . let new_ptr = alloc::alloc::realloc(ptr as *mut u8, old_layout, layout.size()); . new_alloc = NonNull::new(new_ptr) . .ok_or(CollectionAllocErr::AllocErr { layout })? . .cast() . .as_ptr(); . } 70,542 ( 0.00%) self.data = SmallVecData::from_heap(new_alloc, len); 93,048 ( 0.00%) self.capacity = new_cap; . } . Ok(()) . } 17,008 ( 0.00%) } . . /// Reserve capacity for `additional` more elements to be inserted. . /// . /// May reserve more space to avoid frequent reallocations. . /// . /// Panics if the capacity computation overflows `usize`. . #[inline] 691,251 ( 0.00%) pub fn reserve(&mut self, additional: usize) { 4,062,716 ( 0.02%) infallible(self.try_reserve(additional)) 774,320 ( 0.00%) } . . /// Reserve capacity for `additional` more elements to be inserted. . /// . /// May reserve more space to avoid frequent reallocations. 12,641,349 ( 0.07%) pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> { . // prefer triple_mut() even if triple() would work . // so that the optimizer removes duplicated calls to it . // from callers like insert() 21,405 ( 0.00%) let (_, &mut len, cap) = self.triple_mut(); 10,102,538 ( 0.06%) if cap - len >= additional { . return Ok(()); . } . let new_cap = len . .checked_add(additional) . .and_then(usize::checked_next_power_of_two) . .ok_or(CollectionAllocErr::CapacityOverflow)?; 3,563 ( 0.00%) self.try_grow(new_cap) 15,294,573 ( 0.09%) } . . /// Reserve the minimum capacity for `additional` more elements to be inserted. . /// . /// Panics if the new capacity overflows `usize`. . pub fn reserve_exact(&mut self, additional: usize) { . infallible(self.try_reserve_exact(additional)) . } . . /// Reserve the minimum capacity for `additional` more elements to be inserted. . pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> { . let (_, &mut len, cap) = self.triple_mut(); 288,083 ( 0.00%) if cap - len >= additional { . return Ok(()); . } . let new_cap = len . .checked_add(additional) . .ok_or(CollectionAllocErr::CapacityOverflow)?; 434 ( 0.00%) self.try_grow(new_cap) 434 ( 0.00%) } . . /// Shrink the capacity of the vector as much as possible. . /// . /// When possible, this will move data from an external heap buffer to the vector's inline . /// storage. . pub fn shrink_to_fit(&mut self) { . if !self.spilled() { . return; -- line 981 ---------------------------------------- -- line 999 ---------------------------------------- . /// If `len` is greater than or equal to the vector's current length, this has no . /// effect. . /// . /// This does not re-allocate. If you want the vector's capacity to shrink, call . /// `shrink_to_fit` after truncating. . pub fn truncate(&mut self, len: usize) { . unsafe { . let (ptr, len_ptr, _) = self.triple_mut(); 116,548 ( 0.00%) while len < *len_ptr { . let last_index = *len_ptr - 1; . *len_ptr = last_index; . ptr::drop_in_place(ptr.add(last_index)); . } . } . } . . /// Extracts a slice containing the entire vector. -- line 1015 ---------------------------------------- -- line 1044 ---------------------------------------- . pub fn clear(&mut self) { . self.truncate(0); . } . . /// Remove and return the element at position `index`, shifting all elements after it to the . /// left. . /// . /// Panics if `index` is out of bounds. 2,476 ( 0.00%) pub fn remove(&mut self, index: usize) -> A::Item { . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 11,547 ( 0.00%) let len = *len_ptr; 49,656 ( 0.00%) assert!(index < len); 73,660 ( 0.00%) *len_ptr = len - 1; . ptr = ptr.add(index); . let item = ptr::read(ptr); 33,104 ( 0.00%) ptr::copy(ptr.add(1), ptr, len - index - 1); . item . } 3,095 ( 0.00%) } . . /// Insert an element at position `index`, shifting all elements after it to the right. . /// . /// Panics if `index` is out of bounds. 190,199 ( 0.00%) pub fn insert(&mut self, index: usize, element: A::Item) { . self.reserve(1); . . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 17,349 ( 0.00%) let len = *len_ptr; 34,640 ( 0.00%) assert!(index <= len); 69,280 ( 0.00%) *len_ptr = len + 1; . ptr = ptr.add(index); 34,640 ( 0.00%) ptr::copy(ptr, ptr.add(1), len - index); . ptr::write(ptr, element); . } 121,038 ( 0.00%) } . . /// Insert multiple elements at position `index`, shifting all following elements toward the . /// back. . pub fn insert_many>(&mut self, index: usize, iterable: I) { . let mut iter = iterable.into_iter(); . if index == self.len() { . return self.extend(iter); . } -- line 1088 ---------------------------------------- -- line 1201 ---------------------------------------- . } . } . . /// Retains only the elements specified by the predicate. . /// . /// In other words, remove all elements `e` such that `f(&e)` returns `false`. . /// This method operates in place and preserves the order of the retained . /// elements. 263,565 ( 0.00%) pub fn retain bool>(&mut self, mut f: F) { . let mut del = 0; . let len = self.len(); . for i in 0..len { 133,636 ( 0.00%) if !f(&mut self[i]) { 42 ( 0.00%) del += 1; 38,952 ( 0.00%) } else if del > 0 { 45 ( 0.00%) self.swap(i - del, i); . } . } 58,570 ( 0.00%) self.truncate(len - del); 234,280 ( 0.00%) } . . /// Removes consecutive duplicate elements. . pub fn dedup(&mut self) . where . A::Item: PartialEq, . { . self.dedup_by(|a, b| a == b); . } -- line 1228 ---------------------------------------- -- line 1418 ---------------------------------------- . capacity: len, . data: SmallVecData::from_inline(unsafe { . let mut data: MaybeUninit = MaybeUninit::uninit(); . ptr::copy_nonoverlapping( . slice.as_ptr(), . data.as_mut_ptr() as *mut A::Item, . len, . ); 2,531 ( 0.00%) data . }), . } . } else { . let mut b = slice.to_vec(); . let (ptr, cap) = (b.as_mut_ptr(), b.capacity()); . mem::forget(b); . SmallVec { . capacity: cap, -- line 1434 ---------------------------------------- -- line 1436 ---------------------------------------- . } . } . } . . /// Copy elements from a slice into the vector at position `index`, shifting any following . /// elements toward the back. . /// . /// For slices of `Copy` types, this is more efficient than `insert`. 7,916,639 ( 0.04%) pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) { . self.reserve(slice.len()); . . let len = self.len(); 2,040,495 ( 0.01%) assert!(index <= len); . . unsafe { . let slice_ptr = slice.as_ptr(); . let ptr = self.as_mut_ptr().add(index); . ptr::copy(ptr, ptr.add(slice.len()), len - index); . ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len()); 1,360,330 ( 0.01%) self.set_len(len + slice.len()); . } 5,441,320 ( 0.03%) } . . /// Copy elements from a slice and append them to the vector. . /// . /// For slices of `Copy` types, this is more efficient than `extend`. . #[inline] . pub fn extend_from_slice(&mut self, slice: &[A::Item]) { . let len = self.len(); 1,421,982 ( 0.01%) self.insert_from_slice(len, slice); . } . } . . impl SmallVec . where . A::Item: Clone, . { . /// Resizes the vector so that its length is equal to `len`. -- line 1473 ---------------------------------------- -- line 1489 ---------------------------------------- . /// Creates a `SmallVec` with `n` copies of `elem`. . /// ``` . /// use smallvec::SmallVec; . /// . /// let v = SmallVec::<[char; 128]>::from_elem('d', 2); . /// assert_eq!(v, SmallVec::from_buf(['d', 'd'])); . /// ``` . pub fn from_elem(elem: A::Item, n: usize) -> Self { 15,368 ( 0.00%) if n > Self::inline_capacity() { . vec![elem; n].into() . } else { . let mut v = SmallVec::::new(); . unsafe { . let (ptr, len_ptr, _) = v.triple_mut(); . let mut local_len = SetLenOnDrop::new(len_ptr); . . for i in 0..n { . ::core::ptr::write(ptr.add(i), elem.clone()); . local_len.increment_len(1); . } . } 22,815 ( 0.00%) v . } . } . } . . impl ops::Deref for SmallVec { . type Target = [A::Item]; . #[inline] . fn deref(&self) -> &[A::Item] { -- line 1518 ---------------------------------------- -- line 1522 ---------------------------------------- . } . } . } . . impl ops::DerefMut for SmallVec { . #[inline] . fn deref_mut(&mut self) -> &mut [A::Item] { . unsafe { 112,035 ( 0.00%) let (ptr, &mut len, _) = self.triple_mut(); . slice::from_raw_parts_mut(ptr, len) . } . } . } . . impl AsRef<[A::Item]> for SmallVec { . #[inline] . fn as_ref(&self) -> &[A::Item] { -- line 1538 ---------------------------------------- -- line 1716 ---------------------------------------- . SmallVec::extend_from_slice(self, other) . } . } . . impl FromIterator for SmallVec { . #[inline] . fn from_iter>(iterable: I) -> SmallVec { . let mut v = SmallVec::new(); 3,629,101 ( 0.02%) v.extend(iterable); . v . } . } . . impl Extend for SmallVec { 12,262,384 ( 0.07%) fn extend>(&mut self, iterable: I) { 488,927 ( 0.00%) let mut iter = iterable.into_iter(); . let (lower_size_bound, _) = iter.size_hint(); 140,679 ( 0.00%) self.reserve(lower_size_bound); . . unsafe { . let (ptr, len_ptr, cap) = self.triple_mut(); . let mut len = SetLenOnDrop::new(len_ptr); 5,855,931 ( 0.03%) while len.get() < cap { 573,063 ( 0.00%) if let Some(out) = iter.next() { 8 ( 0.00%) ptr::write(ptr.add(len.get()), out); . len.increment_len(1); . } else { . return; . } . } . } . 457,008 ( 0.00%) for elem in iter { 202,645 ( 0.00%) self.push(elem); . } 10,158,735 ( 0.06%) } . } . . impl fmt::Debug for SmallVec . where . A::Item: fmt::Debug, . { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . f.debug_list().entries(self.iter()).finish() -- line 1759 ---------------------------------------- -- line 1764 ---------------------------------------- . #[inline] . fn default() -> SmallVec { . SmallVec::new() . } . } . . #[cfg(feature = "may_dangle")] . unsafe impl<#[may_dangle] A: Array> Drop for SmallVec { 2,104,366 ( 0.01%) fn drop(&mut self) { . unsafe { 5,626,066 ( 0.03%) if self.spilled() { . let (ptr, len) = self.data.heap(); . Vec::from_raw_parts(ptr, len, self.capacity); . } else { . ptr::drop_in_place(&mut self[..]); . } . } 2,417,698 ( 0.01%) } . } . . #[cfg(not(feature = "may_dangle"))] . impl Drop for SmallVec { . fn drop(&mut self) { . unsafe { . if self.spilled() { . let (ptr, len) = self.data.heap(); -- line 1789 ---------------------------------------- -- line 1888 ---------------------------------------- . A::Item: Clone, . { . fn clone(&self) -> IntoIter { . SmallVec::from(self.as_slice()).into_iter() . } . } . . impl Drop for IntoIter { 3,895 ( 0.00%) fn drop(&mut self) { 316,949 ( 0.00%) for _ in self {} 3,656 ( 0.00%) } . } . . impl Iterator for IntoIter { . type Item = A::Item; . . #[inline] . fn next(&mut self) -> Option { 1,243,851 ( 0.01%) if self.current == self.end { . None . } else { . unsafe { . let current = self.current; 636,586 ( 0.00%) self.current += 1; 20,459 ( 0.00%) Some(ptr::read(self.data.as_ptr().add(current))) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 31,205 ( 0.00%) let size = self.end - self.current; . (size, Some(size)) . } . } . . impl DoubleEndedIterator for IntoIter { . #[inline] . fn next_back(&mut self) -> Option { . if self.current == self.end { -- line 1927 ---------------------------------------- -- line 1955 ---------------------------------------- . impl IntoIterator for SmallVec { . type IntoIter = IntoIter; . type Item = A::Item; . fn into_iter(mut self) -> Self::IntoIter { . unsafe { . // Set SmallVec len to zero as `IntoIter` drop handles dropping of the elements . let len = self.len(); . self.set_len(0); 74,274 ( 0.00%) IntoIter { 689,068 ( 0.00%) data: self, . current: 0, . end: len, . } . } . } . } . . impl<'a, A: Array> IntoIterator for &'a SmallVec { -- line 1972 ---------------------------------------- -- line 2000 ---------------------------------------- . len: &'a mut usize, . local_len: usize, . } . . impl<'a> SetLenOnDrop<'a> { . #[inline] . fn new(len: &'a mut usize) -> Self { . SetLenOnDrop { 1,317,105 ( 0.01%) local_len: *len, . len, . } . } . . #[inline] . fn get(&self) -> usize { . self.local_len . } . . #[inline] . fn increment_len(&mut self, increment: usize) { 973,464 ( 0.01%) self.local_len += increment; . } . } . . impl<'a> Drop for SetLenOnDrop<'a> { . #[inline] . fn drop(&mut self) { 1,353,135 ( 0.01%) *self.len = self.local_len; . } . } . . #[cfg(feature = "const_new")] . impl SmallVec<[T; N]> { . /// Construct an empty vector. . /// . /// This is a `const` version of [`SmallVec::new`] that is enabled by the feature `const_new`, with the limitation that it only works for arrays. -- line 2035 ---------------------------------------- 16,481,997 ( 0.09%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/select/mod.rs -------------------------------------------------------------------------------- Ir -- line 208 ---------------------------------------- . /// There is no built-in impl. There may be some other . /// candidate (a where-clause or user-defined impl). . None, . /// It is unknown whether there is an impl. . Ambiguous, . } . . impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { 522,150 ( 0.00%) pub fn new(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> { 2,651,905 ( 0.02%) SelectionContext { . infcx, 364,228 ( 0.00%) freshener: infcx.freshener_keep_static(), . intercrate: false, . intercrate_ambiguity_causes: None, . allow_negative_impls: false, . query_mode: TraitQueryMode::Standard, . } 435,125 ( 0.00%) } . . pub fn intercrate(infcx: &'cx InferCtxt<'cx, 'tcx>) -> SelectionContext<'cx, 'tcx> { 368 ( 0.00%) SelectionContext { . infcx, 46 ( 0.00%) freshener: infcx.freshener_keep_static(), . intercrate: true, . intercrate_ambiguity_causes: None, . allow_negative_impls: false, . query_mode: TraitQueryMode::Standard, . } . } . . pub fn with_negative( -- line 238 ---------------------------------------- -- line 245 ---------------------------------------- . freshener: infcx.freshener_keep_static(), . intercrate: false, . intercrate_ambiguity_causes: None, . allow_negative_impls, . query_mode: TraitQueryMode::Standard, . } . } . 28,896 ( 0.00%) pub fn with_query_mode( . infcx: &'cx InferCtxt<'cx, 'tcx>, . query_mode: TraitQueryMode, . ) -> SelectionContext<'cx, 'tcx> { . debug!(?query_mode, "with_query_mode"); 57,792 ( 0.00%) SelectionContext { . infcx, 3,612 ( 0.00%) freshener: infcx.freshener_keep_static(), . intercrate: false, . intercrate_ambiguity_causes: None, . allow_negative_impls: false, . query_mode, . } 21,672 ( 0.00%) } . . /// Enables tracking of intercrate ambiguity causes. These are . /// used in coherence to give improved diagnostics. We don't do . /// this until we detect a coherence error because it can lead to . /// false overflow results (#47139) and because it costs . /// computation time. . pub fn enable_tracking_intercrate_ambiguity_causes(&mut self) { . assert!(self.intercrate); -- line 274 ---------------------------------------- -- line 281 ---------------------------------------- . /// was enabled and disables tracking at the same time. If . /// tracking is not enabled, just returns an empty vector. . pub fn take_intercrate_ambiguity_causes(&mut self) -> Vec { . assert!(self.intercrate); . self.intercrate_ambiguity_causes.take().unwrap_or_default() . } . . pub fn infcx(&self) -> &'cx InferCtxt<'cx, 'tcx> { 47,442,274 ( 0.27%) self.infcx 78,272 ( 0.00%) } . . pub fn tcx(&self) -> TyCtxt<'tcx> { 798,736 ( 0.00%) self.infcx.tcx . } . . pub fn is_intercrate(&self) -> bool { 80,146 ( 0.00%) self.intercrate . } . . /////////////////////////////////////////////////////////////////////////// . // Selection . // . // The selection phase tries to identify *how* an obligation will . // be resolved. For example, it will identify which impl or . // parameter bound is to be used. The process can be inconclusive -- line 305 ---------------------------------------- -- line 309 ---------------------------------------- . // 1. If no applicable impl or parameter bound can be found. . // 2. If the output type parameters in the obligation do not match . // those specified by the impl/bound. For example, if the obligation . // is `Vec: Iterable`, but the impl specifies . // `impl Iterable for Vec`, than an error would result. . . /// Attempts to satisfy the obligation. If successful, this will affect the surrounding . /// type environment by performing unification. 352,429 ( 0.00%) #[instrument(level = "debug", skip(self))] 453,123 ( 0.00%) pub fn select( . &mut self, . obligation: &TraitObligation<'tcx>, . ) -> SelectionResult<'tcx, Selection<'tcx>> { 370,911 ( 0.00%) let candidate = match self.select_from_obligation(obligation) { . Err(SelectionError::Overflow) => { . // In standard mode, overflow must have been caught and reported . // earlier. . assert!(self.query_mode == TraitQueryMode::Canonical); . return Err(SelectionError::Overflow); . } . Err(SelectionError::Ambiguous(_)) => { . return Ok(None); . } . Err(e) => { 122,024 ( 0.00%) return Err(e); . } . Ok(None) => { 46,209 ( 0.00%) return Ok(None); . } 154,218 ( 0.00%) Ok(Some(candidate)) => candidate, . }; . 260,142 ( 0.00%) match self.confirm_candidate(obligation, candidate) { . Err(SelectionError::Overflow) => { . assert!(self.query_mode == TraitQueryMode::Canonical); . Err(SelectionError::Overflow) . } 20,228 ( 0.00%) Err(e) => Err(e), . Ok(candidate) => { . debug!(?candidate, "confirmed"); 289,764 ( 0.00%) Ok(Some(candidate)) . } . } . } . 503,470 ( 0.00%) crate fn select_from_obligation( . &mut self, . obligation: &TraitObligation<'tcx>, . ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> { . debug_assert!(!obligation.predicate.has_escaping_bound_vars()); . . let pec = &ProvisionalEvaluationCache::default(); . let stack = self.push_stack(TraitObligationStackList::empty(pec), obligation); . 100,694 ( 0.00%) self.candidate_from_obligation(&stack) 453,123 ( 0.00%) } . . /////////////////////////////////////////////////////////////////////////// . // EVALUATION . // . // Tests whether an obligation can be selected or whether an impl . // can be applied to particular types. It skips the "confirmation" . // step and hence completely ignores output type parameters. . // -- line 372 ---------------------------------------- -- line 374 ---------------------------------------- . // we can be sure it does not. . . /// Evaluates whether the obligation `obligation` can be satisfied (by any means). . pub fn predicate_may_hold_fatal(&mut self, obligation: &PredicateObligation<'tcx>) -> bool { . debug!(?obligation, "predicate_may_hold_fatal"); . . // This fatal query is a stopgap that should only be used in standard mode, . // where we do not expect overflow to be propagated. 46 ( 0.00%) assert!(self.query_mode == TraitQueryMode::Standard); . 230 ( 0.00%) self.evaluate_root_obligation(obligation) . .expect("Overflow should be caught earlier in standard query mode") . .may_apply() . } . . /// Evaluates whether the obligation `obligation` can be satisfied . /// and returns an `EvaluationResult`. This is meant for the . /// *initial* call. 7,224 ( 0.00%) pub fn evaluate_root_obligation( . &mut self, . obligation: &PredicateObligation<'tcx>, . ) -> Result { . self.evaluation_probe(|this| { 10,974 ( 0.00%) this.evaluate_predicate_recursively( . TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()), . obligation.clone(), . ) . }) 7,224 ( 0.00%) } . . fn evaluation_probe( . &mut self, . op: impl FnOnce(&mut Self) -> Result, . ) -> Result { 66,438 ( 0.00%) self.infcx.probe(|snapshot| -> Result { 7,316 ( 0.00%) let result = op(self)?; . 64,512 ( 0.00%) match self.infcx.leak_check(true, snapshot) { . Ok(()) => {} . Err(_) => return Ok(EvaluatedToErr), . } . 46,080 ( 0.00%) match self.infcx.region_constraints_added_in_snapshot(snapshot) { . None => Ok(result), . Some(_) => Ok(result.max(EvaluatedToOkModuloRegions)), . } . }) . } . . /// Evaluates the predicates in `predicates` recursively. Note that . /// this applies projections in the predicates, and therefore . /// is run within an inference probe. 100,540 ( 0.00%) #[instrument(skip(self, stack), level = "debug")] . fn evaluate_predicates_recursively<'o, I>( . &mut self, . stack: TraitObligationStackList<'o, 'tcx>, . predicates: I, . ) -> Result . where . I: IntoIterator> + std::fmt::Debug, . { . let mut result = EvaluatedToOk; 57,997 ( 0.00%) for obligation in predicates { 14,284 ( 0.00%) let eval = self.evaluate_predicate_recursively(stack, obligation.clone())?; 7,142 ( 0.00%) if let EvaluatedToErr = eval { . // fast-path - EvaluatedToErr is the top of the lattice, . // so we don't need to look on the other predicates. . return Ok(EvaluatedToErr); . } else { . result = cmp::max(result, eval); . } . } . Ok(result) . } . 72,290 ( 0.00%) #[instrument( . level = "debug", . skip(self, previous_stack), . fields(previous_stack = ?previous_stack.head()) 65,061 ( 0.00%) )] . fn evaluate_predicate_recursively<'o>( . &mut self, . previous_stack: TraitObligationStackList<'o, 'tcx>, . obligation: PredicateObligation<'tcx>, . ) -> Result { . // `previous_stack` stores a `TraitObligation`, while `obligation` is . // a `PredicateObligation`. These are distinct types, so we can't . // use any `Option` combinator method that would force them to be . // the same. 14,458 ( 0.00%) match previous_stack.head() { 6,926 ( 0.00%) Some(h) => self.check_recursion_limit(&obligation, h.obligation)?, 3,766 ( 0.00%) None => self.check_recursion_limit(&obligation, &obligation)?, . } . 43,374 ( 0.00%) let result = ensure_sufficient_stack(|| { 7,229 ( 0.00%) let bound_predicate = obligation.predicate.kind(); 72,290 ( 0.00%) match bound_predicate.skip_binder() { . ty::PredicateKind::Trait(t) => { . let t = bound_predicate.rebind(t); . debug_assert!(!t.has_escaping_bound_vars()); . let obligation = obligation.with(t); 104,715 ( 0.00%) self.evaluate_trait_predicate_recursively(previous_stack, obligation) . } . . ty::PredicateKind::Subtype(p) => { . let p = bound_predicate.rebind(p); . // Does this code ever run? 90 ( 0.00%) match self.infcx.subtype_predicate(&obligation.cause, obligation.param_env, p) { . Some(Ok(InferOk { mut obligations, .. })) => { . self.add_depth(obligations.iter_mut(), obligation.recursion_depth); . self.evaluate_predicates_recursively( . previous_stack, . obligations.into_iter(), . ) . } . Some(Err(_)) => Ok(EvaluatedToErr), -- line 489 ---------------------------------------- -- line 522 ---------------------------------------- . None => Ok(EvaluatedToAmbig), . }, . . ty::PredicateKind::TypeOutlives(pred) => { . // A global type with no late-bound regions can only . // contain the "'static" lifetime (any other lifetime . // would either be late-bound or local), so it is guaranteed . // to outlive any other lifetime 12 ( 0.00%) if pred.0.is_global() && !pred.0.has_late_bound_regions() { . Ok(EvaluatedToOk) . } else { . Ok(EvaluatedToOkModuloRegions) . } . } . . ty::PredicateKind::RegionOutlives(..) => { . // We do not consider region relationships when evaluating trait matches. -- line 538 ---------------------------------------- -- line 545 ---------------------------------------- . } else { . Ok(EvaluatedToErr) . } . } . . ty::PredicateKind::Projection(data) => { . let data = bound_predicate.rebind(data); . let project_obligation = obligation.with(data); 984 ( 0.00%) match project::poly_project_and_unify_type(self, &project_obligation) { 785 ( 0.00%) Ok(Ok(Some(mut subobligations))) => { . 'compute_res: { . // If we've previously marked this projection as 'complete', thne . // use the final cached result (either `EvaluatedToOk` or . // `EvaluatedToOkModuloRegions`), and skip re-evaluating the . // sub-obligations. 628 ( 0.00%) if let Some(key) = 1,413 ( 0.00%) ProjectionCacheKey::from_poly_projection_predicate(self, data) . { 1,200 ( 0.00%) if let Some(cached_res) = self . .infcx . .inner . .borrow_mut() . .projection_cache() . .is_complete(key) . { . break 'compute_res Ok(cached_res); . } . } . 306 ( 0.00%) self.add_depth( . subobligations.iter_mut(), 306 ( 0.00%) obligation.recursion_depth, . ); 306 ( 0.00%) let res = self.evaluate_predicates_recursively( 459 ( 0.00%) previous_stack, 765 ( 0.00%) subobligations, . ); 612 ( 0.00%) if let Ok(res) = res { 306 ( 0.00%) if res == EvaluatedToOk || res == EvaluatedToOkModuloRegions { 600 ( 0.00%) if let Some(key) = 150 ( 0.00%) ProjectionCacheKey::from_poly_projection_predicate( 1,050 ( 0.00%) self, data, . ) . { . // If the result is something that we can cache, then mark this . // entry as 'complete'. This will allow us to skip evaluating the . // suboligations at all the next time we evaluate the projection . // predicate. 1,001 ( 0.00%) self.infcx . .inner . .borrow_mut() . .projection_cache() . .complete(key, res); . } . } . } . res -- line 601 ---------------------------------------- -- line 603 ---------------------------------------- . } . Ok(Ok(None)) => Ok(EvaluatedToAmbig), . Ok(Err(project::InProgress)) => Ok(EvaluatedToRecur), . Err(_) => Ok(EvaluatedToErr), . } . } . . ty::PredicateKind::ClosureKind(_, closure_substs, kind) => { 365 ( 0.00%) match self.infcx.closure_kind(closure_substs) { . Some(closure_kind) => { 219 ( 0.00%) if closure_kind.extends(kind) { . Ok(EvaluatedToOk) . } else { . Ok(EvaluatedToErr) . } . } . None => Ok(EvaluatedToAmbig), . } . } -- line 621 ---------------------------------------- -- line 693 ---------------------------------------- . } . } . } . } . ty::PredicateKind::TypeWellFormedFromEnv(..) => { . bug!("TypeWellFormedFromEnv is only used for chalk") . } . } 7,229 ( 0.00%) }); . . debug!("finished: {:?} from {:?}", result, obligation); . . result . } . 146,601 ( 0.00%) #[instrument(skip(self, previous_stack), level = "debug")] . fn evaluate_trait_predicate_recursively<'o>( . &mut self, . previous_stack: TraitObligationStackList<'o, 'tcx>, . mut obligation: TraitObligation<'tcx>, . ) -> Result { 13,962 ( 0.00%) if !self.intercrate . && obligation.is_global() . && obligation.param_env.caller_bounds().iter().all(|bound| bound.needs_subst()) . { . // If a param env has no global bounds, global obligations do not . // depend on its particular value in order to work, so we can clear . // out the param env and get better caching. . debug!("in global"); 8,772 ( 0.00%) obligation.param_env = obligation.param_env.without_caller_bounds(); . } . . let stack = self.push_stack(previous_stack, &obligation); . let mut fresh_trait_pred = stack.fresh_trait_pred; 13,962 ( 0.00%) let mut param_env = obligation.param_env; . . fresh_trait_pred = fresh_trait_pred.map_bound(|mut pred| { 6,981 ( 0.00%) pred.remap_constness(self.tcx(), &mut param_env); 83,772 ( 0.00%) pred . }); . . debug!(?fresh_trait_pred); . 8,390 ( 0.00%) if let Some(result) = self.check_evaluation_cache(param_env, fresh_trait_pred) { . debug!(?result, "CACHE HIT"); . return Ok(result); . } . . if let Some(result) = stack.cache().get_provisional(fresh_trait_pred) { . debug!(?result, "PROVISIONAL CACHE HIT"); . stack.update_reached_depth(result.reached_depth); . return Ok(result.result); -- line 744 ---------------------------------------- -- line 748 ---------------------------------------- . // stack. If so, we don't want to insert the result into the . // main cache (it is cycle dependent) nor the provisional . // cache (which is meant for things that have completed but . // for a "backedge" -- this result *is* the backedge). . if let Some(cycle_result) = self.check_evaluation_cycle(&stack) { . return Ok(cycle_result); . } . 37,953 ( 0.00%) let (result, dep_node) = self.in_task(|this| this.evaluate_stack(&stack)); 4,217 ( 0.00%) let result = result?; . 21,085 ( 0.00%) if !result.must_apply_modulo_regions() { . stack.cache().on_failure(stack.dfn); . } . 4,217 ( 0.00%) let reached_depth = stack.reached_depth.get(); 8,434 ( 0.00%) if reached_depth >= stack.depth { . debug!(?result, "CACHE MISS"); 80,123 ( 0.00%) self.insert_evaluation_cache(param_env, fresh_trait_pred, dep_node, result); . . stack.cache().on_completion( 8,434 ( 0.00%) stack.dfn, . |fresh_trait_pred, provisional_result, provisional_dep_node| { . // Create a new `DepNode` that has dependencies on: . // * The `DepNode` for the original evaluation that resulted in a provisional cache . // entry being crated . // * The `DepNode` for the *current* evaluation, which resulted in us completing . // provisional caches entries and inserting them into the evaluation cache . // . // This ensures that when a query reads this entry from the evaluation cache, -- line 777 ---------------------------------------- -- line 835 ---------------------------------------- . /// `self.freshener`, we can be sure that (a) this will not . /// affect the inferencer state and (b) that if we see two . /// fresh regions with the same index, they refer to the same . /// unbound type variable. . fn check_evaluation_cycle( . &mut self, . stack: &TraitObligationStack<'_, 'tcx>, . ) -> Option { 10 ( 0.00%) if let Some(cycle_depth) = stack . .iter() . .skip(1) // Skip top-most frame. . .find(|prev| { 2,266 ( 0.00%) stack.obligation.param_env == prev.obligation.param_env . && stack.fresh_trait_pred == prev.fresh_trait_pred . }) . .map(|stack| stack.depth) . { . debug!("evaluate_stack --> recursive at depth {}", cycle_depth); . . // If we have a stack like `A B C D E A`, where the top of . // the stack is the final `A`, then this will iterate over . // `A, E, D, C, B` -- i.e., all the participants apart . // from the cycle head. We mark them as participating in a . // cycle. This suppresses caching for those nodes. See . // `in_cycle` field for more details. 10 ( 0.00%) stack.update_reached_depth(cycle_depth); . . // Subtle: when checking for a coinductive cycle, we do . // not compare using the "freshened trait refs" (which . // have erased regions) but rather the fully explicit . // trait refs. This is important because it's only a cycle . // if the regions match exactly. 6 ( 0.00%) let cycle = stack.iter().skip(1).take_while(|s| s.depth >= cycle_depth); 5 ( 0.00%) let tcx = self.tcx(); 35 ( 0.00%) let cycle = cycle.map(|stack| stack.obligation.predicate.to_predicate(tcx)); 55 ( 0.00%) if self.coinductive_match(cycle) { . debug!("evaluate_stack --> recursive, coinductive"); . Some(EvaluatedToOk) . } else { . debug!("evaluate_stack --> recursive, inductive"); . Some(EvaluatedToRecur) . } . } else { . None . } . } . 37,953 ( 0.00%) fn evaluate_stack<'o>( . &mut self, . stack: &TraitObligationStack<'o, 'tcx>, . ) -> Result { . // In intercrate mode, whenever any of the generics are unbound, . // there can always be an impl. Even if there are no impls in . // this crate, perhaps the type would be unified with . // something from another crate that does provide an impl. . // -- line 890 ---------------------------------------- -- line 903 ---------------------------------------- . // imagine, this is just where we started. To avoid that, we . // check for unbound variables and return an ambiguous (hence possible) . // match if we've seen this trait before. . // . // This suffices to allow chains like `FnMut` implemented in . // terms of `Fn` etc, but we could probably make this more . // precise still. . let unbound_input_types = 4,217 ( 0.00%) stack.fresh_trait_pred.skip_binder().trait_ref.substs.types().any(|ty| ty.is_fresh()); . 12,651 ( 0.00%) if stack.obligation.polarity() != ty::ImplPolarity::Negative { . // This check was an imperfect workaround for a bug in the old . // intercrate mode; it should be removed when that goes away. 21,085 ( 0.00%) if unbound_input_types && self.intercrate { . debug!("evaluate_stack --> unbound argument, intercrate --> ambiguous",); . // Heuristics: show the diagnostics when there are no candidates in crate. . if self.intercrate_ambiguity_causes.is_some() { . debug!("evaluate_stack: intercrate_ambiguity_causes is some"); . if let Ok(candidate_set) = self.assemble_candidates(stack) { . if !candidate_set.ambiguous && candidate_set.vec.is_empty() { . let trait_ref = stack.obligation.predicate.skip_binder().trait_ref; . let self_ty = trait_ref.self_ty(); -- line 924 ---------------------------------------- -- line 937 ---------------------------------------- . self.intercrate_ambiguity_causes.as_mut().unwrap().push(cause); . } . } . } . return Ok(EvaluatedToAmbig); . } . } . 8,434 ( 0.00%) if unbound_input_types . && stack.iter().skip(1).any(|prev| { 132 ( 0.00%) stack.obligation.param_env == prev.obligation.param_env . && self.match_fresh_trait_refs( 176 ( 0.00%) stack.fresh_trait_pred, 176 ( 0.00%) prev.fresh_trait_pred, . prev.obligation.param_env, . ) . }) . { . debug!("evaluate_stack --> unbound argument, recursive --> giving up",); . return Ok(EvaluatedToUnknown); . } . 41,696 ( 0.00%) match self.candidate_from_obligation(stack) { 19,098 ( 0.00%) Ok(Some(c)) => self.evaluate_candidate(stack, &c), . Err(SelectionError::Ambiguous(_)) => Ok(EvaluatedToAmbig), . Ok(None) => Ok(EvaluatedToAmbig), . Err(Overflow) => Err(OverflowError::Canonical), . Err(ErrorReporting) => Err(OverflowError::ErrorReporting), . Err(..) => Ok(EvaluatedToErr), . } 42,170 ( 0.00%) } . . /// For defaulted traits, we use a co-inductive strategy to solve, so . /// that recursion is ok. This routine returns `true` if the top of the . /// stack (`cycle[0]`): . /// . /// - is a defaulted trait, . /// - it also appears in the backtrace at some position `X`, . /// - all the predicates at positions `X..` between `X` and the top are -- line 975 ---------------------------------------- -- line 977 ---------------------------------------- . pub fn coinductive_match(&mut self, mut cycle: I) -> bool . where . I: Iterator>, . { . cycle.all(|predicate| self.coinductive_predicate(predicate)) . } . . fn coinductive_predicate(&self, predicate: ty::Predicate<'tcx>) -> bool { 10 ( 0.00%) let result = match predicate.kind().skip_binder() { 45 ( 0.00%) ty::PredicateKind::Trait(ref data) => self.tcx().trait_is_auto(data.def_id()), . _ => false, . }; . debug!(?predicate, ?result, "coinductive_predicate"); . result . } . . /// Further evaluates `candidate` to decide whether all type parameters match and whether nested . /// obligations are met. Returns whether `candidate` remains viable after this further -- line 994 ---------------------------------------- -- line 998 ---------------------------------------- . skip(self, stack), . fields(depth = stack.obligation.recursion_depth) . )] . fn evaluate_candidate<'o>( . &mut self, . stack: &TraitObligationStack<'o, 'tcx>, . candidate: &SelectionCandidate<'tcx>, . ) -> Result { 9,268 ( 0.00%) let mut result = self.evaluation_probe(|this| { . let candidate = (*candidate).clone(); 74,291 ( 0.00%) match this.confirm_candidate(stack.obligation, candidate) { . Ok(selection) => { . debug!(?selection); 18,536 ( 0.00%) this.evaluate_predicates_recursively( . stack.list(), 60,242 ( 0.00%) selection.nested_obligations().into_iter(), . ) . } . Err(..) => Ok(EvaluatedToErr), . } . })?; . . // If we erased any lifetimes, then we want to use . // `EvaluatedToOkModuloRegions` instead of `EvaluatedToOk` -- line 1021 ---------------------------------------- -- line 1037 ---------------------------------------- . &self, . param_env: ty::ParamEnv<'tcx>, . trait_pred: ty::PolyTraitPredicate<'tcx>, . ) -> Option { . // Neither the global nor local cache is aware of intercrate . // mode, so don't do any caching. In particular, we might . // re-use the same `InferCtxt` with both an intercrate . // and non-intercrate `SelectionContext` 13,962 ( 0.00%) if self.intercrate { . return None; . } . . let tcx = self.tcx(); . if self.can_use_global_caches(param_env) { 45,493 ( 0.00%) if let Some(res) = tcx.evaluation_cache.get(¶m_env.and(trait_pred), tcx) { . return Some(res); . } . } 16,780 ( 0.00%) self.infcx.evaluation_cache.get(¶m_env.and(trait_pred), tcx) . } . 50,604 ( 0.00%) fn insert_evaluation_cache( . &mut self, . param_env: ty::ParamEnv<'tcx>, . trait_pred: ty::PolyTraitPredicate<'tcx>, . dep_node: DepNodeIndex, . result: EvaluationResult, . ) { . // Avoid caching results that depend on more than just the trait-ref . // - the stack can create recursion. 16,868 ( 0.00%) if result.is_stack_dependent() { . return; . } . . // Neither the global nor local cache is aware of intercrate . // mode, so don't do any caching. In particular, we might . // re-use the same `InferCtxt` with both an intercrate . // and non-intercrate `SelectionContext` 8,434 ( 0.00%) if self.intercrate { . return; . } . . if self.can_use_global_caches(param_env) { . if !trait_pred.needs_infer() { . debug!(?trait_pred, ?result, "insert_evaluation_cache global"); . // This may overwrite the cache with the same value . // FIXME: Due to #50507 this overwrites the different values . // This should be changed to use HashMapExt::insert_same . // when that is fixed 3,754 ( 0.00%) self.tcx().evaluation_cache.insert(param_env.and(trait_pred), dep_node, result); . return; . } . } . . debug!(?trait_pred, ?result, "insert_evaluation_cache"); 1,668 ( 0.00%) self.infcx.evaluation_cache.insert(param_env.and(trait_pred), dep_node, result); 33,736 ( 0.00%) } . . /// For various reasons, it's possible for a subobligation . /// to have a *lower* recursion_depth than the obligation used to create it. . /// Projection sub-obligations may be returned from the projection cache, . /// which results in obligations with an 'old' `recursion_depth`. . /// Additionally, methods like `InferCtxt.subtype_predicate` produce . /// subobligations without taking in a 'parent' depth, causing the . /// generated subobligations to have a `recursion_depth` of `0`. . /// . /// To ensure that obligation_depth never decreases, we force all subobligations . /// to have at least the depth of the original obligation. 153 ( 0.00%) fn add_depth>>( . &self, . it: I, . min_depth: usize, . ) { 2,000 ( 0.00%) it.for_each(|o| o.recursion_depth = cmp::max(min_depth, o.recursion_depth) + 1); 306 ( 0.00%) } . . fn check_recursion_depth>( . &self, . depth: usize, . error_obligation: &Obligation<'tcx, T>, . ) -> Result<(), OverflowError> { 247,172 ( 0.00%) if !self.infcx.tcx.recursion_limit().value_within_limit(depth) { . match self.query_mode { . TraitQueryMode::Standard => { . if self.infcx.is_tainted_by_errors() { . return Err(OverflowError::ErrorReporting); . } . self.infcx.report_overflow_error(error_obligation, true); . } . TraitQueryMode::Canonical => { -- line 1126 ---------------------------------------- -- line 1143 ---------------------------------------- . ) -> Result<(), OverflowError> { . self.check_recursion_depth(obligation.recursion_depth, error_obligation) . } . . fn in_task(&mut self, op: OP) -> (R, DepNodeIndex) . where . OP: FnOnce(&mut Self) -> R, . { 109,343 ( 0.00%) let (result, dep_node) = 84,202 ( 0.00%) self.tcx().dep_graph.with_anon_task(self.tcx(), DepKind::TraitSelect, || op(self)); . self.tcx().dep_graph.read_index(dep_node); 100,932 ( 0.00%) (result, dep_node) . } . . /// filter_impls filters constant trait obligations and candidates that have a positive impl . /// for a negative goal and a negative impl for a positive goal . #[instrument(level = "debug", skip(self))] . fn filter_impls( . &mut self, . candidates: Vec>, . obligation: &TraitObligation<'tcx>, . ) -> Vec> { . let tcx = self.tcx(); . let mut result = Vec::with_capacity(candidates.len()); . 123,930 ( 0.00%) for candidate in candidates { . // Respect const trait obligations 22,770 ( 0.00%) if obligation.is_const() { . match candidate { . // const impl . ImplCandidate(def_id) . if tcx.impl_constness(def_id) == hir::Constness::Const => {} . // const param . ParamCandidate(trait_pred) . if trait_pred.skip_binder().constness . == ty::BoundConstness::ConstIfConst => {} -- line 1178 ---------------------------------------- -- line 1186 ---------------------------------------- . ConstDropCandidate(_) => {} . _ => { . // reject all other types of candidates . continue; . } . } . } . 15,180 ( 0.00%) if let ImplCandidate(def_id) = candidate { 9,788 ( 0.00%) if ty::ImplPolarity::Reservation == tcx.impl_polarity(def_id) 4,894 ( 0.00%) || obligation.polarity() == tcx.impl_polarity(def_id) . || self.allow_negative_impls . { . result.push(candidate); . } . } else { . result.push(candidate); . } . } . 32,352 ( 0.00%) result . } . . /// filter_reservation_impls filter reservation impl for any goal as ambiguous 106,743 ( 0.00%) #[instrument(level = "debug", skip(self))] . fn filter_reservation_impls( . &mut self, . candidate: SelectionCandidate<'tcx>, . obligation: &TraitObligation<'tcx>, . ) -> SelectionResult<'tcx, SelectionCandidate<'tcx>> { . let tcx = self.tcx(); . // Treat reservation impls as ambiguity. 19,724 ( 0.00%) if let ImplCandidate(def_id) = candidate { 7,166 ( 0.00%) if let ty::ImplPolarity::Reservation = tcx.impl_polarity(def_id) { . if let Some(intercrate_ambiguity_clauses) = &mut self.intercrate_ambiguity_causes { . let attrs = tcx.get_attrs(def_id); . let attr = tcx.sess.find_by_name(&attrs, sym::rustc_reservation_impl); . let value = attr.and_then(|a| a.value_str()); . if let Some(value) = value { . debug!( . "filter_reservation_impls: \ . reservation impl ambiguity on {:?}", -- line 1227 ---------------------------------------- -- line 1232 ---------------------------------------- . message: value.to_string(), . }, . ); . } . } . return Ok(None); . } . } 37,674 ( 0.00%) Ok(Some(candidate)) . } . . fn is_knowable<'o>(&mut self, stack: &TraitObligationStack<'o, 'tcx>) -> Option { . debug!("is_knowable(intercrate={:?})", self.intercrate); . 25,371 ( 0.00%) if !self.intercrate || stack.obligation.polarity() == ty::ImplPolarity::Negative { . return None; . } . . let obligation = &stack.obligation; 138 ( 0.00%) let predicate = self.infcx().resolve_vars_if_possible(obligation.predicate); . . // Okay to skip binder because of the nature of the . // trait-ref-is-knowable check, which does not care about . // bound regions. . let trait_ref = predicate.skip_binder().trait_ref; . 138 ( 0.00%) coherence::trait_ref_is_knowable(self.tcx(), trait_ref) . } . . /// Returns `true` if the global caches can be used. . fn can_use_global_caches(&self, param_env: ty::ParamEnv<'tcx>) -> bool { . // If there are any inference variables in the `ParamEnv`, then we . // always use a cache local to this particular scope. Otherwise, we . // switch to a global cache. . if param_env.needs_infer() { -- line 1266 ---------------------------------------- -- line 1286 ---------------------------------------- . &mut self, . mut param_env: ty::ParamEnv<'tcx>, . cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>, . ) -> Option>> { . // Neither the global nor local cache is aware of intercrate . // mode, so don't do any caching. In particular, we might . // re-use the same `InferCtxt` with both an intercrate . // and non-intercrate `SelectionContext` 109,128 ( 0.00%) if self.intercrate { 46 ( 0.00%) return None; . } . let tcx = self.tcx(); . let mut pred = cache_fresh_trait_pred.skip_binder(); 109,036 ( 0.00%) pred.remap_constness(tcx, &mut param_env); . 54,518 ( 0.00%) if self.can_use_global_caches(param_env) { 539,730 ( 0.00%) if let Some(res) = tcx.selection_cache.get(¶m_env.and(pred), tcx) { 599,989 ( 0.00%) return Some(res); . } . } 91,470 ( 0.00%) self.infcx.selection_cache.get(¶m_env.and(pred), tcx) . } . . /// Determines whether can we safely cache the result . /// of selecting an obligation. This is almost always `true`, . /// except when dealing with certain `ParamCandidate`s. . /// . /// Ordinarily, a `ParamCandidate` will contain no inference variables, . /// since it was usually produced directly from a `DefId`. However, -- line 1314 ---------------------------------------- -- line 1325 ---------------------------------------- . fn can_cache_candidate( . &self, . result: &SelectionResult<'tcx, SelectionCandidate<'tcx>>, . ) -> bool { . // Neither the global nor local cache is aware of intercrate . // mode, so don't do any caching. In particular, we might . // re-use the same `InferCtxt` with both an intercrate . // and non-intercrate `SelectionContext` 16,822 ( 0.00%) if self.intercrate { . return false; . } 25,095 ( 0.00%) match result { . Ok(Some(SelectionCandidate::ParamCandidate(trait_ref))) => !trait_ref.needs_infer(), . _ => true, . } . } . . fn insert_candidate_cache( . &mut self, . mut param_env: ty::ParamEnv<'tcx>, . cache_fresh_trait_pred: ty::PolyTraitPredicate<'tcx>, . dep_node: DepNodeIndex, . candidate: SelectionResult<'tcx, SelectionCandidate<'tcx>>, . ) { . let tcx = self.tcx(); . let mut pred = cache_fresh_trait_pred.skip_binder(); . 16,822 ( 0.00%) pred.remap_constness(tcx, &mut param_env); . . if !self.can_cache_candidate(&candidate) { . debug!(?pred, ?candidate, "insert_candidate_cache - candidate is not cacheable"); . return; . } . 8,360 ( 0.00%) if self.can_use_global_caches(param_env) { 19,046 ( 0.00%) if let Err(Overflow) = candidate { . // Don't cache overflow globally; we only produce this in certain modes. . } else if !pred.needs_infer() { 31,280 ( 0.00%) if !candidate.needs_infer() { . debug!(?pred, ?candidate, "insert_candidate_cache global"); . // This may overwrite the cache with the same value. 211,140 ( 0.00%) tcx.selection_cache.insert(param_env.and(pred), dep_node, candidate); . return; . } . } . } . . debug!(?pred, ?candidate, "insert_candidate_cache local"); 12,420 ( 0.00%) self.infcx.selection_cache.insert(param_env.and(pred), dep_node, candidate); . } . . /// Matches a predicate against the bounds of its self type. . /// . /// Given an obligation like `::Bar: Baz` where the self type is . /// a projection, look at the bounds of `T::Bar`, see if we can find a . /// `Baz` bound. We return indexes into the list returned by . /// `tcx.item_bounds` for any applicable bounds. 603 ( 0.00%) fn match_projection_obligation_against_definition_bounds( . &mut self, . obligation: &TraitObligation<'tcx>, . ) -> smallvec::SmallVec<[usize; 2]> { 871 ( 0.00%) let poly_trait_predicate = self.infcx().resolve_vars_if_possible(obligation.predicate); . let placeholder_trait_predicate = 1,139 ( 0.00%) self.infcx().replace_bound_vars_with_placeholders(poly_trait_predicate); . debug!( . ?placeholder_trait_predicate, . "match_projection_obligation_against_definition_bounds" . ); . 67 ( 0.00%) let tcx = self.infcx.tcx; 478 ( 0.00%) let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() { 87 ( 0.00%) ty::Projection(ref data) => (data.item_def_id, data.substs), 190 ( 0.00%) ty::Opaque(def_id, substs) => (def_id, substs), . _ => { . span_bug!( . obligation.cause.span, . "match_projection_obligation_against_definition_bounds() called \ . but self-ty is not a projection: {:?}", . placeholder_trait_predicate.trait_ref.self_ty() . ); . } -- line 1405 ---------------------------------------- -- line 1411 ---------------------------------------- . // unnecessary ambiguity. . let mut distinct_normalized_bounds = FxHashSet::default(); . . let matching_bounds = bounds . .iter() . .enumerate() . .filter_map(|(idx, bound)| { . let bound_predicate = bound.kind(); 891 ( 0.00%) if let ty::PredicateKind::Trait(pred) = bound_predicate.skip_binder() { . let bound = bound_predicate.rebind(pred.trait_ref); 2,985 ( 0.00%) if self.infcx.probe(|_| { 1,168 ( 0.00%) match self.match_normalize_trait_ref( . obligation, 796 ( 0.00%) bound, 796 ( 0.00%) placeholder_trait_predicate.trait_ref, . ) { . Ok(None) => true, . Ok(Some(normalized_trait)) . if distinct_normalized_bounds.insert(normalized_trait) => . { . true . } . _ => false, -- line 1433 ---------------------------------------- -- line 1437 ---------------------------------------- . } . } . None . }) . .collect(); . . debug!(?matching_bounds, "match_projection_obligation_against_definition_bounds"); . matching_bounds 603 ( 0.00%) } . . /// Equates the trait in `obligation` with trait bound. If the two traits . /// can be equated and the normalized trait bound doesn't contain inference . /// variables or placeholders, the normalized bound is returned. 2,756 ( 0.00%) fn match_normalize_trait_ref( . &mut self, . obligation: &TraitObligation<'tcx>, . trait_bound: ty::PolyTraitRef<'tcx>, . placeholder_trait_ref: ty::TraitRef<'tcx>, . ) -> Result>, ()> { . debug_assert!(!placeholder_trait_ref.has_escaping_bound_vars()); 724 ( 0.00%) if placeholder_trait_ref.def_id != trait_bound.def_id() { . // Avoid unnecessary normalization 336 ( 0.00%) return Err(()); . } . 528 ( 0.00%) let Normalized { value: trait_bound, obligations: _ } = ensure_sufficient_stack(|| { . project::normalize_with_depth( . self, 44 ( 0.00%) obligation.param_env, . obligation.cause.clone(), 132 ( 0.00%) obligation.recursion_depth + 1, 176 ( 0.00%) trait_bound, . ) . }); 132 ( 0.00%) self.infcx 88 ( 0.00%) .at(&obligation.cause, obligation.param_env) . .sup(ty::Binder::dummy(placeholder_trait_ref), trait_bound) . .map(|InferOk { obligations: _, value: () }| { . // This method is called within a probe, so we can't have . // inference variables and placeholders escape. . if !trait_bound.needs_infer() && !trait_bound.has_placeholders() { 155 ( 0.00%) Some(trait_bound) . } else { . None . } . }) . .map_err(|_| ()) 1,908 ( 0.00%) } . . fn evaluate_where_clause<'o>( . &mut self, . stack: &TraitObligationStack<'o, 'tcx>, . where_clause_trait_ref: ty::PolyTraitRef<'tcx>, . ) -> Result { . self.evaluation_probe(|this| { 10,164 ( 0.00%) match this.match_where_clause_trait_ref(stack.obligation, where_clause_trait_ref) { 1,920 ( 0.00%) Ok(obligations) => this.evaluate_predicates_recursively(stack.list(), obligations), . Err(()) => Ok(EvaluatedToErr), . } . }) . } . 1,674 ( 0.00%) pub(super) fn match_projection_projections( . &mut self, . obligation: &ProjectionTyObligation<'tcx>, . env_predicate: PolyProjectionPredicate<'tcx>, . potentially_unnormalized_candidates: bool, . ) -> bool { . let mut nested_obligations = Vec::new(); 930 ( 0.00%) let (infer_predicate, _) = self.infcx.replace_bound_vars_with_fresh_vars( 558 ( 0.00%) obligation.cause.span, . LateBoundRegionConversionTime::HigherRankedType, . env_predicate, . ); 372 ( 0.00%) let infer_projection = if potentially_unnormalized_candidates { 256 ( 0.00%) ensure_sufficient_stack(|| { 128 ( 0.00%) project::normalize_with_depth_to( . self, 32 ( 0.00%) obligation.param_env, . obligation.cause.clone(), 96 ( 0.00%) obligation.recursion_depth + 1, 64 ( 0.00%) infer_predicate.projection_ty, . &mut nested_obligations, . ) . }) . } else { 308 ( 0.00%) infer_predicate.projection_ty . }; . 186 ( 0.00%) self.infcx 372 ( 0.00%) .at(&obligation.cause, obligation.param_env) 372 ( 0.00%) .sup(obligation.predicate, infer_projection) 1,347 ( 0.00%) .map_or(false, |InferOk { obligations, value: () }| { . self.evaluate_predicates_recursively( . TraitObligationStackList::empty(&ProvisionalEvaluationCache::default()), . nested_obligations.into_iter().chain(obligations), . ) 278 ( 0.00%) .map_or(false, |res| res.may_apply()) . }) 1,674 ( 0.00%) } . . /////////////////////////////////////////////////////////////////////////// . // WINNOW . // . // Winnowing is the process of attempting to resolve ambiguity by . // probing further. During the winnowing process, we unify all . // type variables and then we also attempt to evaluate recursive . // bounds to see if they are satisfied. -- line 1544 ---------------------------------------- -- line 1550 ---------------------------------------- . /// See the comment for "SelectionCandidate" for more details. . fn candidate_should_be_dropped_in_favor_of( . &mut self, . sized_predicate: bool, . victim: &EvaluatedCandidate<'tcx>, . other: &EvaluatedCandidate<'tcx>, . needs_infer: bool, . ) -> bool { 2,159 ( 0.00%) if victim.candidate == other.candidate { . return true; . } . . // Check if a bound would previously have been removed when normalizing . // the param_env so that it can be given the lowest priority. See . // #50825 for the motivation for this. . let is_global = |cand: &ty::PolyTraitPredicate<'tcx>| { . cand.is_global() && !cand.has_late_bound_regions() . }; . . // (*) Prefer `BuiltinCandidate { has_nested: false }`, `PointeeCandidate`, . // `DiscriminantKindCandidate`, and `ConstDropCandidate` to anything else. . // . // This is a fix for #53123 and prevents winnowing from accidentally extending the . // lifetime of a variable. 39,042 ( 0.00%) match (&other.candidate, &victim.candidate) { . (_, AutoImplCandidate(..)) | (AutoImplCandidate(..), _) => { . bug!( . "default implementations shouldn't be recorded \ . when there are other valid candidates" . ); . } . . // (*) -- line 1582 ---------------------------------------- -- line 1674 ---------------------------------------- . } . (ObjectCandidate(_), ProjectionCandidate(_)) . | (ProjectionCandidate(_), ObjectCandidate(_)) => { . bug!("Have both object and projection candidate") . } . . // Arbitrarily give projection and object candidates priority. . ( 4,318 ( 0.00%) ObjectCandidate(_) | ProjectionCandidate(_), . ImplCandidate(..) . | ClosureCandidate . | GeneratorCandidate . | FnPointerCandidate { .. } . | BuiltinObjectCandidate . | BuiltinUnsizeCandidate . | TraitUpcastingUnsizeCandidate(_) . | BuiltinCandidate { .. } -- line 1690 ---------------------------------------- -- line 1696 ---------------------------------------- . | ClosureCandidate . | GeneratorCandidate . | FnPointerCandidate { .. } . | BuiltinObjectCandidate . | BuiltinUnsizeCandidate . | TraitUpcastingUnsizeCandidate(_) . | BuiltinCandidate { .. } . | TraitAliasCandidate(..), 8,636 ( 0.00%) ObjectCandidate(_) | ProjectionCandidate(_), . ) => false, . 21,590 ( 0.00%) (&ImplCandidate(other_def), &ImplCandidate(victim_def)) => { . // See if we can toss out `victim` based on specialization. . // This requires us to know *for sure* that the `other` impl applies . // i.e., `EvaluatedToOk`. . // . // FIXME(@lcnr): Using `modulo_regions` here seems kind of scary . // to me but is required for `std` to compile, so I didn't change it . // for now. . let tcx = self.tcx(); 8,636 ( 0.00%) if other.evaluation.must_apply_modulo_regions() { 17,120 ( 0.00%) if tcx.specializes((other_def, victim_def)) { . return true; . } . } . 10,730 ( 0.00%) if other.evaluation.must_apply_considering_regions() { 8,464 ( 0.00%) match tcx.impls_are_allowed_to_overlap(other_def, victim_def) { . Some(ty::ImplOverlapKind::Permitted { marker: true }) => { . // Subtle: If the predicate we are evaluating has inference . // variables, do *not* allow discarding candidates due to . // marker trait impls. . // . // Without this restriction, we could end up accidentally . // constrainting inference variables based on an arbitrarily . // chosen trait impl. -- line 1731 ---------------------------------------- -- line 1790 ---------------------------------------- . | BuiltinUnsizeCandidate . | TraitUpcastingUnsizeCandidate(_) . | BuiltinCandidate { has_nested: true } . | TraitAliasCandidate(..), . ) => false, . } . } . 20,960 ( 0.00%) fn sized_conditions( . &mut self, . obligation: &TraitObligation<'tcx>, . ) -> BuiltinImplConditions<'tcx> { . use self::BuiltinImplConditions::{Ambiguous, None, Where}; . . // NOTE: binder moved to (*) 6,288 ( 0.00%) let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty()); . 10,504 ( 0.00%) match self_ty.kind() { . ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) . | ty::Uint(_) . | ty::Int(_) . | ty::Bool . | ty::Float(_) . | ty::FnDef(..) . | ty::FnPtr(_) . | ty::RawPtr(..) -- line 1815 ---------------------------------------- -- line 1817 ---------------------------------------- . | ty::Ref(..) . | ty::Generator(..) . | ty::GeneratorWitness(..) . | ty::Array(..) . | ty::Closure(..) . | ty::Never . | ty::Error(_) => { . // safe for everything 578 ( 0.00%) Where(ty::Binder::dummy(Vec::new())) . } . . ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => None, . . ty::Tuple(tys) => Where( . obligation . .predicate 496 ( 0.00%) .rebind(tys.last().into_iter().map(|k| k.expect_ty()).collect()), . ), . . ty::Adt(def, substs) => { 2,148 ( 0.00%) let sized_crit = def.sized_constraint(self.tcx()); . // (*) binder moved here 5,370 ( 0.00%) Where( . obligation.predicate.rebind({ 1,074 ( 0.00%) sized_crit.iter().map(|ty| ty.subst(self.tcx(), substs)).collect() . }), . ) . } . . ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => None, . ty::Infer(ty::TyVar(_)) => Ambiguous, . . ty::Placeholder(..) . | ty::Bound(..) . | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty); . } . } 16,768 ( 0.00%) } . 14,016 ( 0.00%) fn copy_clone_conditions( . &mut self, . obligation: &TraitObligation<'tcx>, . ) -> BuiltinImplConditions<'tcx> { . // NOTE: binder moved to (*) 3,504 ( 0.00%) let self_ty = self.infcx.shallow_resolve(obligation.predicate.skip_binder().self_ty()); . . use self::BuiltinImplConditions::{Ambiguous, None, Where}; . 9,010 ( 0.00%) match *self_ty.kind() { . ty::Infer(ty::IntVar(_)) . | ty::Infer(ty::FloatVar(_)) . | ty::FnDef(..) . | ty::FnPtr(_) 94 ( 0.00%) | ty::Error(_) => Where(ty::Binder::dummy(Vec::new())), . . ty::Uint(_) . | ty::Int(_) . | ty::Bool . | ty::Float(_) . | ty::Char . | ty::RawPtr(..) . | ty::Never -- line 1879 ---------------------------------------- -- line 1886 ---------------------------------------- . ty::Dynamic(..) . | ty::Str . | ty::Slice(..) . | ty::Generator(..) . | ty::GeneratorWitness(..) . | ty::Foreign(..) . | ty::Ref(_, _, hir::Mutability::Mut) => None, . 60 ( 0.00%) ty::Tuple(tys) => { . // (*) binder moved here 338 ( 0.00%) Where(obligation.predicate.rebind(tys.iter().map(|k| k.expect_ty()).collect())) . } . 242 ( 0.00%) ty::Closure(_, substs) => { . // (*) binder moved here 726 ( 0.00%) let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty()); 484 ( 0.00%) if let ty::Infer(ty::TyVar(_)) = ty.kind() { . // Not yet resolved. . Ambiguous . } else { 1,694 ( 0.00%) Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect())) . } . } . . ty::Adt(..) | ty::Projection(..) | ty::Param(..) | ty::Opaque(..) => { . // Fallback to whatever user-defined impls exist in this case. . None . } . -- line 1914 ---------------------------------------- -- line 1920 ---------------------------------------- . } . . ty::Placeholder(..) . | ty::Bound(..) . | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty); . } . } 10,512 ( 0.00%) } . . /// For default impls, we need to break apart a type into its . /// "constituent types" -- meaning, the types that it contains. . /// . /// Here are some (simple) examples: . /// . /// ``` . /// (i32, u32) -> [i32, u32] -- line 1936 ---------------------------------------- -- line 1937 ---------------------------------------- . /// Foo where struct Foo { x: i32, y: u32 } -> [i32, u32] . /// Bar where struct Bar { x: T, y: u32 } -> [i32, u32] . /// Zed where enum Zed { A(T), B(u32) } -> [i32, u32] . /// ``` . fn constituent_types_for_ty( . &self, . t: ty::Binder<'tcx, Ty<'tcx>>, . ) -> ty::Binder<'tcx, Vec>> { 25 ( 0.00%) match *t.skip_binder().kind() { . ty::Uint(_) . | ty::Int(_) . | ty::Bool . | ty::Float(_) . | ty::FnDef(..) . | ty::FnPtr(_) . | ty::Str . | ty::Error(_) -- line 1953 ---------------------------------------- -- line 1968 ---------------------------------------- . ty::RawPtr(ty::TypeAndMut { ty: element_ty, .. }) | ty::Ref(_, element_ty, _) => { . t.rebind(vec![element_ty]) . } . . ty::Array(element_ty, _) | ty::Slice(element_ty) => t.rebind(vec![element_ty]), . . ty::Tuple(ref tys) => { . // (T1, ..., Tn) -- meets any bound that all of T1...Tn meet 2 ( 0.00%) t.rebind(tys.iter().map(|k| k.expect_ty()).collect()) . } . . ty::Closure(_, ref substs) => { . let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty()); . t.rebind(vec![ty]) . } . . ty::Generator(_, ref substs, _) => { -- line 1984 ---------------------------------------- -- line 2003 ---------------------------------------- . // We can resolve the `impl Trait` to its concrete type, . // which enforces a DAG between the functions requiring . // the auto trait bounds in question. . t.rebind(vec![self.tcx().type_of(def_id).subst(self.tcx(), substs)]) . } . } . } . 4,140 ( 0.00%) fn collect_predicates_for_types( . &mut self, . param_env: ty::ParamEnv<'tcx>, . cause: ObligationCause<'tcx>, . recursion_depth: usize, . trait_def_id: DefId, . types: ty::Binder<'tcx, Vec>>, . ) -> Vec> { . // Because the types were potentially derived from -- line 2019 ---------------------------------------- -- line 2030 ---------------------------------------- . // 2. Produce something like `&'0 i32 : Copy` . // 3. Re-bind the regions back to `for<'a> &'a i32 : Copy` . . types . .as_ref() . .skip_binder() // binder moved -\ . .iter() . .flat_map(|ty| { 1,176 ( 0.00%) let ty: ty::Binder<'tcx, Ty<'tcx>> = types.rebind(ty); // <----/ . 4,704 ( 0.00%) self.infcx.commit_unconditionally(|_| { 1,176 ( 0.00%) let placeholder_ty = self.infcx.replace_bound_vars_with_placeholders(ty); 1,960 ( 0.00%) let Normalized { value: normalized_ty, mut obligations } = 3,920 ( 0.00%) ensure_sufficient_stack(|| { . project::normalize_with_depth( . self, 392 ( 0.00%) param_env, . cause.clone(), 392 ( 0.00%) recursion_depth, 392 ( 0.00%) placeholder_ty, . ) . }); 4,312 ( 0.00%) let placeholder_obligation = predicate_for_trait_def( . self.tcx(), 392 ( 0.00%) param_env, . cause.clone(), 784 ( 0.00%) trait_def_id, . recursion_depth, . normalized_ty, . &[], . ); 2,352 ( 0.00%) obligations.push(placeholder_obligation); . obligations . }) . }) . .collect() 2,070 ( 0.00%) } . . /////////////////////////////////////////////////////////////////////////// . // Matching . // . // Matching is a common path used for both evaluation and . // confirmation. It basically unifies types that appear in impls . // and traits. This does affect the surrounding environment; . // therefore, when used during evaluation, match routines must be -- line 2074 ---------------------------------------- -- line 2075 ---------------------------------------- . // run inside of a `probe()` so that their side-effects are . // contained. . . fn rematch_impl( . &mut self, . impl_def_id: DefId, . obligation: &TraitObligation<'tcx>, . ) -> Normalized<'tcx, SubstsRef<'tcx>> { 67,455 ( 0.00%) match self.match_impl(impl_def_id, obligation) { 53,964 ( 0.00%) Ok(substs) => substs, . Err(()) => { . bug!( . "Impl {:?} was matchable against {:?} but now is not", . impl_def_id, . obligation . ); . } . } . } . 486,894 ( 0.00%) #[tracing::instrument(level = "debug", skip(self))] . fn match_impl( . &mut self, . impl_def_id: DefId, . obligation: &TraitObligation<'tcx>, . ) -> Result>, ()> { . let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap(); . . // Before we create the substitutions and everything, first . // consider a "quick reject". This avoids creating more types . // and so forth that we need to. . if self.fast_reject_trait_refs(obligation, &impl_trait_ref) { 2,986 ( 0.00%) return Err(()); . } . . let placeholder_obligation = 168,931 ( 0.00%) self.infcx().replace_bound_vars_with_placeholders(obligation.predicate); 72,399 ( 0.00%) let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref; . 120,665 ( 0.00%) let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id); . 48,266 ( 0.00%) let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs); . . debug!(?impl_trait_ref); . 144,798 ( 0.00%) let Normalized { value: impl_trait_ref, obligations: mut nested_obligations } = 168,931 ( 0.00%) ensure_sufficient_stack(|| { . project::normalize_with_depth( . self, 24,133 ( 0.00%) obligation.param_env, . obligation.cause.clone(), 72,399 ( 0.00%) obligation.recursion_depth + 1, 48,266 ( 0.00%) impl_trait_ref, . ) . }); . . debug!(?impl_trait_ref, ?placeholder_obligation_trait_ref); . . let cause = ObligationCause::new( 24,133 ( 0.00%) obligation.cause.span, 48,266 ( 0.00%) obligation.cause.body_id, 217,197 ( 0.00%) ObligationCauseCode::MatchImpl(obligation.cause.clone(), impl_def_id), . ); . 48,266 ( 0.00%) let InferOk { obligations, .. } = self . .infcx 24,133 ( 0.00%) .at(&cause, obligation.param_env) . .eq(placeholder_obligation_trait_ref, impl_trait_ref) . .map_err(|e| debug!("match_impl: failed eq_trait_refs due to `{}`", e))?; . nested_obligations.extend(obligations); . 55,167 ( 0.00%) if !self.intercrate . && self.tcx().impl_polarity(impl_def_id) == ty::ImplPolarity::Reservation . { . debug!("match_impl: reservation impls only apply in intercrate mode"); . return Err(()); . } . . debug!(?impl_substs, ?nested_obligations, "match_impl: success"); 110,310 ( 0.00%) Ok(Normalized { value: impl_substs, obligations: nested_obligations }) . } . . fn fast_reject_trait_refs( . &mut self, . obligation: &TraitObligation<'_>, . impl_trait_ref: &ty::TraitRef<'_>, . ) -> bool { . // We can avoid creating type variables and doing the full . // substitution if we find that any of the input types, when . // simplified, do not match. . 76,878 ( 0.00%) iter::zip(obligation.predicate.skip_binder().trait_ref.substs, impl_trait_ref.substs).any( . |(obligation_arg, impl_arg)| { 244,750 ( 0.00%) match (obligation_arg.unpack(), impl_arg.unpack()) { . (GenericArgKind::Type(obligation_ty), GenericArgKind::Type(impl_ty)) => { . // Note, we simplify parameters for the obligation but not the . // impl so that we do not reject a blanket impl but do reject . // more concrete impls if we're searching for `T: Trait`. 326,168 ( 0.00%) let simplified_obligation_ty = fast_reject::simplify_type( . self.tcx(), . obligation_ty, . SimplifyParams::Yes, . StripReferences::No, . ); 244,626 ( 0.00%) let simplified_impl_ty = fast_reject::simplify_type( . self.tcx(), . impl_ty, . SimplifyParams::No, . StripReferences::No, . ); . 122,313 ( 0.00%) simplified_obligation_ty.is_some() . && simplified_impl_ty.is_some() . && simplified_obligation_ty != simplified_impl_ty . } . (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => { . // Lifetimes can never cause a rejection. . false . } . (GenericArgKind::Const(_), GenericArgKind::Const(_)) => { -- line 2194 ---------------------------------------- -- line 2201 ---------------------------------------- . } . }, . ) . } . . /// Normalize `where_clause_trait_ref` and try to match it against . /// `obligation`. If successful, return any predicates that . /// result from the normalization. 8,316 ( 0.00%) fn match_where_clause_trait_ref( . &mut self, . obligation: &TraitObligation<'tcx>, . where_clause_trait_ref: ty::PolyTraitRef<'tcx>, . ) -> Result>, ()> { . self.match_poly_trait_ref(obligation, where_clause_trait_ref) 7,392 ( 0.00%) } . . /// Returns `Ok` if `poly_trait_ref` being true implies that the . /// obligation is satisfied. . #[instrument(skip(self), level = "debug")] . fn match_poly_trait_ref( . &mut self, . obligation: &TraitObligation<'tcx>, . poly_trait_ref: ty::PolyTraitRef<'tcx>, . ) -> Result>, ()> { 2,174 ( 0.00%) self.infcx 924 ( 0.00%) .at(&obligation.cause, obligation.param_env) 6,522 ( 0.00%) .sup(obligation.predicate.to_poly_trait_ref(), poly_trait_ref) . .map(|InferOk { obligations, .. }| obligations) . .map_err(|_| ()) . } . . /////////////////////////////////////////////////////////////////////////// . // Miscellany . . fn match_fresh_trait_refs( . &self, . previous: ty::PolyTraitPredicate<'tcx>, . current: ty::PolyTraitPredicate<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> bool { 132 ( 0.00%) let mut matcher = ty::_match::Match::new(self.tcx(), param_env); . matcher.relate(previous, current).is_ok() . } . . fn push_stack<'o>( . &mut self, . previous_stack: TraitObligationStackList<'o, 'tcx>, . obligation: &'o TraitObligation<'tcx>, . ) -> TraitObligationStack<'o, 'tcx> { 357,930 ( 0.00%) let fresh_trait_pred = obligation.predicate.fold_with(&mut self.freshener); . . let dfn = previous_stack.cache.next_dfn(); 13,962 ( 0.00%) let depth = previous_stack.depth() + 1; 495,009 ( 0.00%) TraitObligationStack { . obligation, 293,621 ( 0.00%) fresh_trait_pred, . reached_depth: Cell::new(depth), . previous: previous_stack, . dfn, . depth, . } . } . . #[instrument(skip(self), level = "debug")] . fn closure_trait_ref_unnormalized( . &mut self, . obligation: &TraitObligation<'tcx>, . substs: SubstsRef<'tcx>, . ) -> ty::PolyTraitRef<'tcx> { 1,551 ( 0.00%) let closure_sig = substs.as_closure().sig(); . . debug!(?closure_sig); . . // (1) Feels icky to skip the binder here, but OTOH we know . // that the self-type is an unboxed closure type and hence is . // in fact unparameterized (or at least does not reference any . // regions bound in the obligation). Still probably some . // refactoring could make this nicer. 5,170 ( 0.00%) closure_trait_ref_and_return_type( . self.tcx(), 3,102 ( 0.00%) obligation.predicate.def_id(), 517 ( 0.00%) obligation.predicate.skip_binder().self_ty(), // (1) 2,068 ( 0.00%) closure_sig, . util::TupleArgumentsFlag::No, . ) . .map_bound(|(trait_ref, _)| trait_ref) . } . . fn generator_trait_ref_unnormalized( . &mut self, . obligation: &TraitObligation<'tcx>, -- line 2291 ---------------------------------------- -- line 2307 ---------------------------------------- . ) . .map_bound(|(trait_ref, ..)| trait_ref) . } . . /// Returns the obligations that are implied by instantiating an . /// impl or trait. The obligations are substituted and fully . /// normalized. This is used when confirming an impl or default . /// impl. 310,408 ( 0.00%) #[tracing::instrument(level = "debug", skip(self, cause, param_env))] . fn impl_or_trait_obligations( . &mut self, . cause: ObligationCause<'tcx>, . recursion_depth: usize, . param_env: ty::ParamEnv<'tcx>, . def_id: DefId, // of impl or trait . substs: SubstsRef<'tcx>, // for impl or trait . ) -> Vec> { -- line 2323 ---------------------------------------- -- line 2334 ---------------------------------------- . // V: Iterator, V: Sized, . // ::Item: Copy . // When we substitute, say, `V => IntoIter, U => $0`, the last . // obligation will normalize to `<$0 as Iterator>::Item = $1` and . // `$1: Copy`, so we must ensure the obligations are emitted in . // that order. . let predicates = tcx.predicates_of(def_id); . debug!(?predicates); 13,496 ( 0.00%) assert_eq!(predicates.parent, None); 40,488 ( 0.00%) let mut obligations = Vec::with_capacity(predicates.predicates.len()); . for (predicate, _) in predicates.predicates { . debug!(?predicate); 101,730 ( 0.00%) let predicate = normalize_with_depth_to( . self, . param_env, . cause.clone(), . recursion_depth, 20,346 ( 0.00%) predicate.subst(tcx, substs), . &mut obligations, . ); 203,460 ( 0.00%) obligations.push(Obligation { . cause: cause.clone(), . recursion_depth, . param_env, . predicate, . }); . } . . // We are performing deduplication here to avoid exponential blowups -- line 2362 ---------------------------------------- -- line 2363 ---------------------------------------- . // (#38528) from happening, but the real cause of the duplication is . // unknown. What we know is that the deduplication avoids exponential . // amount of predicates being propagated when processing deeply nested . // types. . // . // This code is hot enough that it's worth avoiding the allocation . // required for the FxHashSet when possible. Special-casing lengths 0, . // 1 and 2 covers roughly 75-80% of the cases. 27,840 ( 0.00%) if obligations.len() <= 1 { . // No possibility of duplicates. 6,683 ( 0.00%) } else if obligations.len() == 2 { . // Only two elements. Drop the second if they are equal. 3 ( 0.00%) if obligations[0] == obligations[1] { 9 ( 0.00%) obligations.truncate(1); . } . } else { . // Three or more elements. Use a general deduplication process. . let mut seen = FxHashSet::default(); 2,243 ( 0.00%) obligations.retain(|i| seen.insert(i.clone())); . } . 53,984 ( 0.00%) obligations . } . } . . trait TraitObligationExt<'tcx> { . fn derived_cause( . &self, . variant: fn(DerivedObligationCause<'tcx>) -> ObligationCauseCode<'tcx>, . ) -> ObligationCause<'tcx>; -- line 2392 ---------------------------------------- -- line 2408 ---------------------------------------- . */ . . let obligation = self; . . // NOTE(flaper87): As of now, it keeps track of the whole error . // chain. Ideally, we should have a way to configure this either . // by using -Z verbose or just a CLI argument. . let derived_cause = DerivedObligationCause { 55,364 ( 0.00%) parent_trait_pred: obligation.predicate, 27,342 ( 0.00%) parent_code: obligation.cause.clone_code(), . }; . let derived_code = variant(derived_cause); 165,742 ( 0.00%) ObligationCause::new(obligation.cause.span, obligation.cause.body_id, derived_code) . } . } . . impl<'o, 'tcx> TraitObligationStack<'o, 'tcx> { . fn list(&'o self) -> TraitObligationStackList<'o, 'tcx> { . TraitObligationStackList::with(self) . } . . fn cache(&self) -> &'o ProvisionalEvaluationCache<'tcx> { 14,844 ( 0.00%) self.previous.cache . } . . fn iter(&'o self) -> TraitObligationStackList<'o, 'tcx> { . self.list() . } . . /// Indicates that attempting to evaluate this stack entry . /// required accessing something from the stack at depth `reached_depth`. 10 ( 0.00%) fn update_reached_depth(&self, reached_depth: usize) { 5 ( 0.00%) assert!( 5 ( 0.00%) self.depth >= reached_depth, . "invoked `update_reached_depth` with something under this stack: \ . self.depth={} reached_depth={}", . self.depth, . reached_depth, . ); . debug!(reached_depth, "update_reached_depth"); . let mut p = self; 15 ( 0.00%) while reached_depth < p.depth { . debug!(?p.fresh_trait_pred, "update_reached_depth: marking as cycle participant"); 5 ( 0.00%) p.reached_depth.set(p.reached_depth.get().min(reached_depth)); 5 ( 0.00%) p = p.previous.head.unwrap(); . } 10 ( 0.00%) } . } . . /// The "provisional evaluation cache" is used to store intermediate cache results . /// when solving auto traits. Auto traits are unusual in that they can support . /// cycles. So, for example, a "proof tree" like this would be ok: . /// . /// - `Foo: Send` :- . /// - `Bar: Send` :- -- line 2462 ---------------------------------------- -- line 2540 ---------------------------------------- . /// evaluation. When we create an entry in the evaluation cache using this provisional . /// cache entry (see `on_completion`), we use this `dep_node` to ensure that future reads from . /// the cache will have all of the necessary incr comp dependencies tracked. . dep_node: DepNodeIndex, . } . . impl<'tcx> Default for ProvisionalEvaluationCache<'tcx> { . fn default() -> Self { 65,535 ( 0.00%) Self { dfn: Cell::new(0), map: Default::default() } . } . } . . impl<'tcx> ProvisionalEvaluationCache<'tcx> { . /// Get the next DFN in sequence (basically a counter). . fn next_dfn(&self) -> usize { 6,981 ( 0.00%) let result = self.dfn.get(); 27,924 ( 0.00%) self.dfn.set(result + 1); . result . } . . /// Check the provisional cache for any result for . /// `fresh_trait_ref`. If there is a hit, then you must consider . /// it an access to the stack slots at depth . /// `reached_depth` (from the returned value). . fn get_provisional( -- line 2564 ---------------------------------------- -- line 2663 ---------------------------------------- . fn on_completion( . &self, . dfn: usize, . mut op: impl FnMut(ty::PolyTraitPredicate<'tcx>, EvaluationResult, DepNodeIndex), . ) { . debug!(?dfn, "on_completion"); . . for (fresh_trait_pred, eval) in 29,519 ( 0.00%) self.map.borrow_mut().drain_filter(|_k, eval| eval.from_dfn >= dfn) . { . debug!(?fresh_trait_pred, ?eval, "on_completion"); . . op(fresh_trait_pred, eval.result, eval.dep_node); . } . } . } . -- line 2679 ---------------------------------------- -- line 2692 ---------------------------------------- . TraitObligationStackList { cache: r.cache(), head: Some(r) } . } . . fn head(&self) -> Option<&'o TraitObligationStack<'o, 'tcx>> { . self.head . } . . fn depth(&self) -> usize { 17,269 ( 0.00%) if let Some(head) = self.head { head.depth } else { 0 } . } . } . . impl<'o, 'tcx> Iterator for TraitObligationStackList<'o, 'tcx> { . type Item = &'o TraitObligationStack<'o, 'tcx>; . . fn next(&mut self) -> Option<&'o TraitObligationStack<'o, 'tcx>> { 15,410 ( 0.00%) let o = self.head?; 1,398 ( 0.00%) *self = o.previous; . Some(o) . } . } . . impl<'o, 'tcx> fmt::Debug for TraitObligationStack<'o, 'tcx> { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(f, "TraitObligationStack({:?})", self.obligation) . } -- line 2717 ---------------------------------------- 620,253 ( 0.00%) -------------------------------------------------------------------------------- The following files chosen for auto-annotation could not be found: -------------------------------------------------------------------------------- ./malloc/malloc.c ./stdlib/msort.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,027,246,174 (17.16%) events annotated