-------------------------------------------------------------------------------- I1 cache: 65536 B, 64 B, 4-way associative D1 cache: 32768 B, 64 B, 8-way associative LL cache: 67108864 B, 64 B, 64-way associative Command: /usr/home/liquid/.rustup/toolchains/w-profiling/bin/rustc --crate-name idna --edition=2018 src/lib.rs --error-format=json --json=diagnostic-rendered-ansi,artifacts,future-incompat --crate-type lib --emit=dep-info,metadata,link -C embed-bitcode=no -C debuginfo=2 -C metadata=7dcc06f197553bdf -C extra-filename=-7dcc06f197553bdf --out-dir /usr/home/liquid/tmp/.tmpvsy94g/target/debug/deps -L dependency=/usr/home/liquid/tmp/.tmpvsy94g/target/debug/deps --extern matches=/usr/home/liquid/tmp/.tmpvsy94g/target/debug/deps/libmatches-9dc97549d86d1154.rmeta --extern unicode_bidi=/usr/home/liquid/tmp/.tmpvsy94g/target/debug/deps/libunicode_bidi-6b691207298595a3.rmeta --extern unicode_normalization=/usr/home/liquid/tmp/.tmpvsy94g/target/debug/deps/libunicode_normalization-224c518aa9bd8a2c.rmeta -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-idna-0.2.3-Debug-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 4,932,019,418 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 143,951,448 ( 2.92%) ???:llvm::FPPassManager::runOnFunction(llvm::Function&) 135,460,252 ( 2.75%) ./malloc/malloc.c:_int_malloc 128,064,913 ( 2.60%) ./malloc/malloc.c:_int_free 87,649,490 ( 1.78%) ???:llvm::SelectionDAG::Combine(llvm::CombineLevel, llvm::AAResults*, llvm::CodeGenOpt::Level) 83,414,385 ( 1.69%) ./malloc/malloc.c:malloc 49,583,064 ( 1.01%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 40,090,956 ( 0.81%) ???:(anonymous namespace)::Verifier::visitInstruction(llvm::Instruction&) 38,157,821 ( 0.77%) ./malloc/malloc.c:free 35,851,259 ( 0.73%) ???:(anonymous namespace)::RegAllocFast::allocateBasicBlock(llvm::MachineBasicBlock&) 32,687,947 ( 0.66%) ???:llvm::AttributeList::addAttributes(llvm::LLVMContext&, unsigned int, llvm::AttrBuilder const&) const 31,881,313 ( 0.65%) ???:llvm::MachineInstr::addOperand(llvm::MachineFunction&, llvm::MachineOperand const&) 31,669,613 ( 0.64%) ???:llvm::PMDataManager::verifyPreservedAnalysis(llvm::Pass*) 30,910,861 ( 0.63%) ???:llvm::raw_svector_ostream::write_impl(char const*, unsigned long) 26,936,158 ( 0.55%) ???:(anonymous namespace)::Verifier::visitMDNode(llvm::MDNode const&, (anonymous namespace)::Verifier::AreDebugLocsAllowed) 26,902,315 ( 0.55%) ???:llvm::SelectionDAGISel::SelectCodeCommon(llvm::SDNode*, unsigned char const*, unsigned int) 25,286,132 ( 0.51%) ./malloc/malloc.c:malloc_consolidate 24,668,950 ( 0.50%) ???:llvm::MCExpr::evaluateAsRelocatableImpl(llvm::MCValue&, llvm::MCAssembler const*, llvm::MCAsmLayout const*, llvm::MCFixup const*, llvm::DenseMap, llvm::detail::DenseMapPair > const*, bool) const 21,121,847 ( 0.43%) ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S:__memset_avx2_erms 18,945,237 ( 0.38%) ???:llvm::ScheduleDAGSDNodes::BuildSchedUnits() 17,659,123 ( 0.36%) ???:(anonymous namespace)::VarLocBasedLDV::process(llvm::MachineInstr&, (anonymous namespace)::VarLocBasedLDV::OpenRangesSet&, (anonymous namespace)::VarLocBasedLDV::VarLocMap&, llvm::SmallVector<(anonymous namespace)::VarLocBasedLDV::TransferDebugPair, 4u>&) 15,758,210 ( 0.32%) ???:llvm::TargetLoweringBase::getTypeConversion(llvm::LLVMContext&, llvm::EVT) const 15,433,368 ( 0.31%) ./malloc/malloc.c:unlink_chunk.constprop.0 14,486,433 ( 0.29%) ???:llvm::MCAsmLayout::getSymbolOffset(llvm::MCSymbol const&) const 14,263,394 ( 0.29%) ???:llvm::StringMapImpl::LookupBucketFor(llvm::StringRef) 13,791,032 ( 0.28%) ???:llvm::TargetRegisterInfo::shouldRealignStack(llvm::MachineFunction const&) const 13,097,028 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 12,376,150 ( 0.25%) ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S:__memcmp_avx2_movbe 12,206,270 ( 0.25%) ???:(anonymous namespace)::Verifier::visitCallBase(llvm::CallBase&) 12,144,376 ( 0.25%) ???:llvm::coro::declaresIntrinsics(llvm::Module const&, std::initializer_list) 12,131,858 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/mod.rs:::next_token 12,079,972 ( 0.24%) ???:llvm::TargetRegisterInfo::checkAllSuperRegsMarked(llvm::BitVector const&, llvm::ArrayRef) const 12,063,650 ( 0.24%) ???:llvm::SmallSet >::insert(llvm::Register const&) 11,643,578 ( 0.24%) ???:(anonymous namespace)::TwoAddressInstructionPass::runOnMachineFunction(llvm::MachineFunction&) 11,538,451 ( 0.23%) ???:(anonymous namespace)::Verifier::verify(llvm::Function const&) [clone .llvm.4153962086227604281] 11,377,821 ( 0.23%) ???:llvm::MCObjectStreamer::emitBytes(llvm::StringRef) 11,362,069 ( 0.23%) ???:(anonymous namespace)::X86MCCodeEmitter::emitPrefixImpl(unsigned int&, llvm::MCInst const&, llvm::MCSubtargetInfo const&, llvm::raw_ostream&) const 11,361,362 ( 0.23%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 11,293,638 ( 0.23%) ???:llvm::InstrEmitter::EmitMachineNode(llvm::SDNode*, bool, bool, llvm::DenseMap, llvm::detail::DenseMapPair >&) 11,090,037 ( 0.22%) ???:llvm::DAGTypeLegalizer::run() 10,998,364 ( 0.22%) ./string/../sysdeps/x86_64/multiarch/strcmp-avx2.S:__strncmp_avx2 10,969,065 ( 0.22%) ???:(anonymous namespace)::SelectionDAGLegalize::LegalizeOp(llvm::SDNode*) [clone .llvm.8386621111310650999] 10,934,746 ( 0.22%) ???:llvm::SelectionDAG::MorphNodeTo(llvm::SDNode*, unsigned int, llvm::SDVTList, llvm::ArrayRef) 10,861,403 ( 0.22%) ???:llvm::MCAsmLayout::getFragmentOffset(llvm::MCFragment const*) const 10,772,363 ( 0.22%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_sse2_unaligned_erms 10,760,520 ( 0.22%) ???:llvm::MetadataTracking::track(void*, llvm::Metadata&, llvm::PointerUnion) 10,397,769 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs:::lookup_source_file_idx 10,311,661 ( 0.21%) ???:llvm::DomTreeBuilder::SemiNCAInfo >::CalculateFromScratch(llvm::DominatorTreeBase&, llvm::DomTreeBuilder::SemiNCAInfo >::BatchUpdateInfo*) 10,309,062 ( 0.21%) ./elf/dl-lookup.c:_dl_lookup_symbol_x 9,995,044 ( 0.20%) ???:llvm::SelectionDAG::Legalize() 9,560,206 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs:::span_data_to_lines_and_cols 9,168,894 ( 0.19%) ???:llvm::FoldingSetBase::FindNodeOrInsertPos(llvm::FoldingSetNodeID const&, void*&, llvm::FoldingSetBase::FoldingSetInfo const&) 9,083,312 ( 0.18%) ???:(anonymous namespace)::VarLocBasedLDV::ExtendRanges(llvm::MachineFunction&, llvm::TargetPassConfig*) [clone .llvm.4451506318407214204] 9,066,588 ( 0.18%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 9,056,403 ( 0.18%) ???:(anonymous namespace)::Verifier::verifyFunctionAttrs(llvm::FunctionType*, llvm::AttributeList, llvm::Value const*, bool) 9,042,085 ( 0.18%) ???:multikeySort(llvm::MutableArrayRef*>, int) 8,982,737 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs:::advance_token 8,938,459 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::check 8,842,753 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::parse_token_tree 8,785,584 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::short_write_process_buffer:: 8,678,523 ( 0.18%) ???:llvm::SelectionDAG::getConstant(llvm::ConstantInt const&, llvm::SDLoc const&, llvm::EVT, bool, bool) 8,586,970 ( 0.17%) ???:(anonymous namespace)::DAGCombiner::combine(llvm::SDNode*) 8,508,633 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs:>::try_read_immediate 8,491,496 ( 0.17%) ???:(anonymous namespace)::PEI::runOnMachineFunction(llvm::MachineFunction&) 8,435,807 ( 0.17%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::get:: 8,426,287 ( 0.17%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 8,381,116 ( 0.17%) ???:llvm::MCContext::getOrCreateSymbol(llvm::Twine const&) 8,016,963 ( 0.16%) ???:llvm::FoldingSetNodeID::AddInteger(unsigned int) 7,999,473 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/layout.rs:<&rustc_middle::ty::TyS as rustc_target::abi::TyAbiInterface<_>>::ty_and_layout_field::field_ty_or_layout::> 7,960,625 ( 0.16%) ???:(anonymous namespace)::ScheduleDAGRRList::Schedule() [clone .llvm.6953762222372402862] 7,869,615 ( 0.16%) ???:llvm::calculateDbgEntityHistory(llvm::MachineFunction const*, llvm::TargetRegisterInfo const*, llvm::DbgValueHistoryMap&, llvm::DbgLabelInstrMap&) 7,601,633 ( 0.15%) ./stdlib/msort.c:msort_with_tmp.part.0 7,483,293 ( 0.15%) ???:(anonymous namespace)::X86MCInstLower::Lower(llvm::MachineInstr const*, llvm::MCInst&) const 7,368,827 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::hash_stable 7,265,602 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 7,125,133 ( 0.14%) ???:llvm::X86FrameLowering::hasFP(llvm::MachineFunction const&) const 6,883,071 ( 0.14%) ???:(anonymous namespace)::X86MCCodeEmitter::encodeInstruction(llvm::MCInst const&, llvm::raw_ostream&, llvm::SmallVectorImpl&, llvm::MCSubtargetInfo const&) const 6,866,562 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 6,863,068 ( 0.14%) ???:(anonymous namespace)::Verifier::visitFunction(llvm::Function const&)::$_3::operator()(llvm::Instruction const&, llvm::MDNode const*) const 6,785,095 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 6,756,685 ( 0.14%) ???:llvm::FunctionLoweringInfo::set(llvm::Function const&, llvm::MachineFunction&, llvm::SelectionDAG*) 6,649,206 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 6,545,895 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_target/src/abi/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 6,543,405 ( 0.13%) ???:llvm::PMDataManager::removeNotPreservedAnalysis(llvm::Pass*) 6,531,928 ( 0.13%) ???:(anonymous namespace)::ELFObjectWriter::recordRelocation(llvm::MCAssembler&, llvm::MCAsmLayout const&, llvm::MCFragment const*, llvm::MCFixup const&, llvm::MCValue, unsigned long&) [clone .llvm.14145361893594770252] 6,514,829 ( 0.13%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (core::result::Result, rustc_middle::ty::layout::LayoutError>, rustc_query_system::dep_graph::graph::DepNodeIndex), core::hash::BuildHasherDefault>>::from_key_hashed_nocheck::> 6,359,285 ( 0.13%) ???:llvm::DwarfDebug::beginInstruction(llvm::MachineInstr const*) 6,186,054 ( 0.13%) ???:llvm::MachineFunction::CreateMachineInstr(llvm::MCInstrDesc const&, llvm::DebugLoc const&, bool) 6,146,896 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/hir/map/mod.rs:::attrs 6,033,167 ( 0.12%) ???:llvm::ScheduleDAGSDNodes::AddSchedEdges() 5,927,780 ( 0.12%) ???:llvm::SmallPtrSetImplBase::insert_imp_big(void const*) 5,812,207 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_target/src/abi/mod.rs:::scalar::> 5,795,216 ( 0.12%) ???:llvm::SelectionDAGISel::SelectAllBasicBlocks(llvm::Function const&) 5,793,603 ( 0.12%) ???:llvm::DataLayout::getAlignment(llvm::Type*, bool) const 5,788,420 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs:rustc_mir_dataflow::drop_flag_effects::on_all_children_bits::is_terminal_path 5,758,101 ( 0.12%) ???:(anonymous namespace)::CFIInstrInserter::runOnMachineFunction(llvm::MachineFunction&) 5,697,383 ( 0.12%) ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S:__memset_avx2_unaligned_erms 5,611,463 ( 0.11%) /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) 5,609,557 ( 0.11%) ???:llvm::Twine::printOneChild(llvm::raw_ostream&, llvm::Twine::Child, llvm::Twine::NodeKind) const 5,587,485 ( 0.11%) ./malloc/malloc.c:realloc 5,441,532 ( 0.11%) ???:(anonymous namespace)::ELFWriter::writeObject(llvm::MCAssembler&, llvm::MCAsmLayout const&) 5,434,917 ( 0.11%) ???:(anonymous namespace)::RegAllocFast::markRegUsedInInstr(unsigned short) 5,417,557 ( 0.11%) ???:llvm::SelectionDAG::AssignTopologicalOrder() 5,374,468 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/coercion.rs:::coerce 5,358,873 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::reserve_rehash::>::{closure#0}> 5,336,832 ( 0.11%) ???:llvm::MCAssembler::layout(llvm::MCAsmLayout&) 5,293,965 ( 0.11%) ???:llvm::SelectionDAG::getRegister(unsigned int, llvm::EVT) 5,271,506 ( 0.11%) ???:llvm::DomTreeBuilder::SemiNCAInfo >::runSemiNCA(llvm::DominatorTreeBase&, unsigned int) 5,244,013 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::eq 5,220,409 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/middle/region.rs:::temporary_scope 5,217,923 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs:::fold_ty 5,210,871 ( 0.11%) ???:llvm::raw_ostream::write(char const*, unsigned long) 5,173,189 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/layout.rs:<&rustc_middle::ty::TyS as rustc_target::abi::TyAbiInterface>>::ty_and_layout_field 5,168,149 ( 0.10%) ???:llvm::MDNode::MDNode(llvm::LLVMContext&, unsigned int, llvm::Metadata::StorageType, llvm::ArrayRef, llvm::ArrayRef) 5,103,929 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:>::hash_stable 5,033,095 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::, rustc_middle::ty::context::Interned>::{closure#0}> 4,984,357 ( 0.10%) ???:llvm::LLVMContextImpl::~LLVMContextImpl() 4,958,152 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::shallow_resolve_ty -------------------------------------------------------------------------------- -- 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, . { 3 ( 0.00%) let mut next_child = move_data.move_paths[path].first_child; 6 ( 0.00%) while let Some(child_index) = next_child { . let move_path_children = &move_data.move_paths[child_index]; 6 ( 0.00%) if let Some(&elem) = move_path_children.place.projection.last() { 12 ( 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; 927,470 ( 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 . } 1,044,045 ( 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), . { 5,202 ( 0.00%) match lookup_result { . LookupResult::Parent(..) => { . // access to untracked value - do not touch children . } . LookupResult::Exact(e) => on_all_children_bits(tcx, body, move_data, e, each_child), . } . } . . pub fn on_all_children_bits<'tcx, F>( -- line 99 ---------------------------------------- -- line 100 ---------------------------------------- . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . move_path_index: MovePathIndex, . mut each_child: F, . ) where . F: FnMut(MovePathIndex), . { 1,258,440 ( 0.03%) fn is_terminal_path<'tcx>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . path: MovePathIndex, . ) -> bool { 314,610 ( 0.01%) place_contents_drop_state_cannot_differ(tcx, body, move_data.move_paths[path].place) 1,258,440 ( 0.03%) } . 1,494,305 ( 0.03%) 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), . { 73,764 ( 0.00%) each_child(move_path_index); . 1,101,194 ( 0.02%) if is_terminal_path(tcx, body, move_data, move_path_index) { . return; . } . 148,956 ( 0.00%) let mut next_child_index = move_data.move_paths[move_path_index].first_child; 301,948 ( 0.01%) while let Some(child_index) = next_child_index { 8,070 ( 0.00%) on_all_children_bits(tcx, body, move_data, child_index, each_child); 1,345 ( 0.00%) next_child_index = move_data.move_paths[child_index].next_sibling; . } 1,186,848 ( 0.02%) } 929,992 ( 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), . { 1,114 ( 0.00%) on_all_children_bits(tcx, body, &ctxt.move_data, path, |child| { 544 ( 0.00%) let place = &ctxt.move_data.move_paths[path].place; 136 ( 0.00%) let ty = place.ty(body, tcx).ty; . debug!("on_all_drop_children_bits({:?}, {:?} : {:?})", path, place, ty); . 24 ( 0.00%) let erased_ty = tcx.erase_regions(ty); 830 ( 0.00%) if erased_ty.needs_drop(tcx, ctxt.param_env) { 136 ( 0.00%) each_child(child); . } else { . debug!("on_all_drop_children_bits - skipping") . } . }) . } . 4,827 ( 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; 432 ( 0.00%) for arg in body.args_iter() { 1,020 ( 0.00%) let place = mir::Place::from(arg); 1,530 ( 0.00%) let lookup_result = move_data.rev_lookup.find(place.as_ref()); . on_lookup_result_bits(tcx, body, move_data, lookup_result, |mpi| { 558 ( 0.00%) callback(mpi, DropFlagState::Present) . }); . } 3,456 ( 0.00%) } . 938,349 ( 0.02%) pub fn drop_flag_effects_for_location<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . ctxt: &MoveDataParamEnv<'tcx>, . loc: Location, . mut callback: F, . ) where . F: FnMut(MovePathIndex, DropFlagState), . { . let move_data = &ctxt.move_data; . debug!("drop_flag_effects_for_location({:?})", loc); . . // first, move out of the RHS 15,699 ( 0.00%) for mi in &move_data.loc_map[loc] { 303,328 ( 0.01%) let path = mi.move_path_index(move_data); . debug!("moving out of path {:?}", move_data.move_paths[path]); . 80,521 ( 0.00%) on_all_children_bits(tcx, body, move_data, path, |mpi| callback(mpi, DropFlagState::Absent)) . } . . debug!("drop_flag_effects: assignment for location({:?})", loc); . 73,764 ( 0.00%) for_location_inits(tcx, body, move_data, loc, |mpi| callback(mpi, DropFlagState::Present)); 792,224 ( 0.02%) } . . pub fn for_location_inits<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . loc: Location, . mut callback: F, . ) where . F: FnMut(MovePathIndex), . { 15,699 ( 0.00%) for ii in &move_data.init_loc_map[loc] { 298,136 ( 0.01%) let init = move_data.inits[*ii]; 152,652 ( 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. 8,148 ( 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), . ) { 3,395 ( 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]; 1,873 ( 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. 22 ( 0.00%) let (downcast, base_proj) = variant_path.place.projection.split_last().unwrap(); 88 ( 0.00%) assert_eq!(enum_place.projection.len(), base_proj.len()); . 66 ( 0.00%) let variant_idx = match *downcast { . mir::ProjectionElem::Downcast(_, idx) => idx, . _ => unreachable!(), . }; . 22 ( 0.00%) if variant_idx != active_variant { . on_all_children_bits(tcx, body, move_data, variant_mpi, |mpi| { 22 ( 0.00%) handle_inactive_variant(mpi) . }); . } . } 5,432 ( 0.00%) } 1,223,126 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs -------------------------------------------------------------------------------- Ir -- line 108 ---------------------------------------- . suppress_errors: bool, . }, . } . . impl RegionckMode { . /// Indicates that the MIR borrowck will repeat these region . /// checks, so we should ignore errors if NLL is (unconditionally) . /// enabled. 55 ( 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. 55 ( 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 }, . } 110 ( 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> { 33,615 ( 0.00%) fn new() -> InferCtxtInner<'tcx> { 228,582 ( 0.00%) 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(), 20,169 ( 0.00%) region_constraint_storage: Some(RegionConstraintStorage::new()), . region_obligations: vec![], . opaque_types: Default::default(), . opaque_types_vars: Default::default(), . } 40,338 ( 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> { 1,891 ( 0.00%) self.projection_cache.with_log(&mut self.undo_log) . } . . #[inline] . fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> { 503,119 ( 0.01%) 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>, . >, . > { 8,370 ( 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>, . >, . > { 13,097 ( 0.00%) self.const_unification_storage.with_log(&mut self.undo_log) . } . . #[inline] . pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> { 28,709 ( 0.00%) self.region_constraint_storage . .as_mut() . .expect("region constraints already solved") 19,361 ( 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. 18,568 ( 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 20,659 ( 0.00%) #[derive(Clone, Debug)] . pub enum SubregionOrigin<'tcx> { . /// Arose from a subtyping relation 1,261 ( 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. 102 ( 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 99 ( 0.00%) DataBorrowed(Ty<'tcx>, Span), . . /// (&'a &'b T) where a >= b 80 ( 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> { 6,723 ( 0.00%) fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> { 20,169 ( 0.00%) InferCtxtBuilder { tcx: self, defining_use_anchor: None, fresh_typeck_results: None } 6,723 ( 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. 1,251 ( 0.00%) pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self { 1,529 ( 0.00%) self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner))); 695 ( 0.00%) self.with_opaque_type_inference(table_owner) 973 ( 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. 132 ( 0.00%) pub fn with_opaque_type_inference(mut self, defining_use_anchor: LocalDefId) -> Self { 66 ( 0.00%) self.defining_use_anchor = Some(defining_use_anchor); 410 ( 0.00%) self 198 ( 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`). 7,695 ( 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| { 8,584 ( 0.00%) let (value, subst) = 353 ( 0.00%) infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical); 13,396 ( 0.00%) f(infcx, value, subst) . }) 8,412 ( 0.00%) } . 45,286 ( 0.00%) pub fn enter(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R { 18,095 ( 0.00%) let InferCtxtBuilder { tcx, defining_use_anchor, ref fresh_typeck_results } = *self; . let in_progress_typeck_results = fresh_typeck_results.as_ref(); 294,279 ( 0.01%) f(InferCtxt { . tcx, . defining_use_anchor, . in_progress_typeck_results, 6,723 ( 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), 6,723 ( 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), . }) 48,403 ( 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 { 37 ( 0.00%) let InferOk { value, obligations } = self; 168 ( 0.00%) for obligation in obligations { . fulfill_cx.register_predicate_obligation(infcx, obligation); . } . value . } . } . . impl<'tcx> InferOk<'tcx, ()> { 15,684 ( 0.00%) pub fn into_obligations(self) -> PredicateObligations<'tcx> { 62,736 ( 0.00%) self.obligations 15,684 ( 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() 34,962 ( 0.00%) } . 248,936 ( 0.01%) pub fn freshen>(&self, t: T) -> T { 280,053 ( 0.01%) t.fold_with(&mut self.freshener()) 280,053 ( 0.01%) } . . /// Returns the origin of the type variable identified by `vid`, or `None` . /// if this is not a type variable. . /// . /// No attempt is made to resolve `ty`. 136 ( 0.00%) pub fn type_var_origin(&'a self, ty: Ty<'tcx>) -> Option { 272 ( 0.00%) match *ty.kind() { 66 ( 0.00%) ty::Infer(ty::TyVar(vid)) => { 264 ( 0.00%) Some(*self.inner.borrow_mut().type_variables().var_origin(vid)) . } 2 ( 0.00%) _ => None, . } 272 ( 0.00%) } . 31,117 ( 0.00%) pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, false) 31,117 ( 0.00%) } . . /// Like `freshener`, but does not replace `'static` regions. 125,342 ( 0.00%) pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, true) 125,342 ( 0.00%) } . 300 ( 0.00%) pub fn unsolved_variables(&self) -> Vec> { 150 ( 0.00%) let mut inner = self.inner.borrow_mut(); 150 ( 0.00%) let mut vars: Vec> = inner . .type_variables() . .unsolved_variables() . .into_iter() 132 ( 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 }) 160 ( 0.00%) .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none()) 2 ( 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 525 ( 0.00%) } . 92,361 ( 0.00%) fn combine_fields( . &'a self, . trace: TypeTrace<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> CombineFields<'a, 'tcx> { 369,452 ( 0.01%) CombineFields { . infcx: self, 923,630 ( 0.02%) trace, . cause: None, . param_env, . obligations: PredicateObligations::new(), . } 92,361 ( 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. 48 ( 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); 71,184 ( 0.00%) let result = func(self); . self.in_snapshot.set(flag); . result 54 ( 0.00%) } . 493,072 ( 0.01%) 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,479,216 ( 0.03%) 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. 246,536 ( 0.00%) _in_progress_typeck_results: self . .in_progress_typeck_results . .map(|typeck_results| typeck_results.borrow()), . } 986,144 ( 0.02%) } . 639,573 ( 0.01%) #[instrument(skip(self, snapshot), level = "debug")] . fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 58,143 ( 0.00%) undo_snapshot, 58,143 ( 0.00%) region_constraints_snapshot, 58,143 ( 0.00%) universe, 58,143 ( 0.00%) was_in_snapshot, 116,286 ( 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(); 58,143 ( 0.00%) inner.rollback_to(undo_snapshot); . inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot); . } . 2,825,895 ( 0.06%) #[instrument(skip(self, snapshot), level = "debug")] . fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 188,393 ( 0.00%) undo_snapshot, . region_constraints_snapshot: _, . universe: _, 188,393 ( 0.00%) was_in_snapshot, 376,786 ( 0.01%) _in_progress_typeck_results, . } = snapshot; . . self.in_snapshot.set(was_in_snapshot); . . self.inner.borrow_mut().commit(undo_snapshot); . } . . /// Executes `f` and commit the bindings. 20,475 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 25,190 ( 0.00%) pub fn commit_unconditionally(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 2,290 ( 0.00%) let snapshot = self.start_snapshot(); 7,580 ( 0.00%) let r = f(&snapshot); 16,030 ( 0.00%) self.commit_from(snapshot); 13,575 ( 0.00%) r . } . . /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`. 1,015,181 ( 0.02%) #[instrument(skip(self, f), level = "debug")] 1,259,701 ( 0.03%) pub fn commit_if_ok(&self, f: F) -> Result . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result, . { 250,040 ( 0.01%) let snapshot = self.start_snapshot(); 583,066 ( 0.01%) let r = f(&snapshot); . debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok()); 316,992 ( 0.01%) match r { . Ok(_) => { 1,305,395 ( 0.03%) self.commit_from(snapshot); . } . Err(_) => { 352,271 ( 0.01%) self.rollback_to("commit_if_ok -- error", snapshot); . } . } 1,557,090 ( 0.03%) r . } . . /// Execute `f` then unroll any bindings it creates. 75,241 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 92,738 ( 0.00%) pub fn probe(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 45,606 ( 0.00%) let snapshot = self.start_snapshot(); 39,804 ( 0.00%) let r = f(&snapshot); 206,318 ( 0.00%) self.rollback_to("probe", snapshot); 179,206 ( 0.00%) r . } . . /// If `should_skip` is true, then execute `f` then unroll any bindings it creates. 9 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 12 ( 0.00%) pub fn probe_maybe_skip_leak_check(&self, should_skip: bool, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 2 ( 0.00%) let snapshot = self.start_snapshot(); 1 ( 0.00%) let was_skip_leak_check = self.skip_leak_check.get(); 2 ( 0.00%) if should_skip { . self.skip_leak_check.set(true); . } 4 ( 0.00%) let r = f(&snapshot); 9 ( 0.00%) self.rollback_to("probe", snapshot); . self.skip_leak_check.set(was_skip_leak_check); 12 ( 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 4,766 ( 0.00%) pub fn region_constraints_added_in_snapshot( . &self, . snapshot: &CombinedSnapshot<'a, 'tcx>, . ) -> Option { 9,532 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() . .region_constraints_added_in_snapshot(&snapshot.undo_snapshot) 7,149 ( 0.00%) } . . pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) { . self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup); . } . 300 ( 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. . }) . }) 225 ( 0.00%) } . 396 ( 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. . }) . }) 297 ( 0.00%) } . 5,610 ( 0.00%) #[instrument(skip(self), level = "debug")] . pub fn sub_regions( . &self, . origin: SubregionOrigin<'tcx>, . a: ty::Region<'tcx>, . b: ty::Region<'tcx>, . ) { 5,049 ( 0.00%) self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b); . } . . /// Require that the region `r` be equal to one of the regions in . /// the set `regions`. . #[instrument(skip(self), level = "debug")] . pub fn member_constraint( . &self, . opaque_type_def_id: DefId, -- line 947 ---------------------------------------- -- line 969 ---------------------------------------- . /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up . /// actually requiring `a <: b`. This is of course a valid coercion, . /// but it's not as flexible as `FnCtxt::coerce` would be. . /// . /// (We may refactor this in the future, but there are a number of . /// practical obstacles. Among other things, `FnCtxt::coerce` presently . /// records adjustments that are required on the HIR in order to perform . /// the coercion, and we don't currently have a way to manage that.) 6 ( 0.00%) pub fn coerce_predicate( . &self, . cause: &ObligationCause<'tcx>, . param_env: ty::ParamEnv<'tcx>, . predicate: ty::PolyCoercePredicate<'tcx>, . ) -> Option> { 4 ( 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, . }); 10 ( 0.00%) self.subtype_predicate(cause, param_env, subtype_predicate) 8 ( 0.00%) } . 408 ( 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. 34 ( 0.00%) let r_a = self.shallow_resolve(predicate.skip_binder().a); 34 ( 0.00%) let r_b = self.shallow_resolve(predicate.skip_binder().b); 268 ( 0.00%) match (r_a.kind(), r_b.kind()) { 66 ( 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); 66 ( 0.00%) return None; . } . _ => {} . } . . Some(self.commit_if_ok(|_snapshot| { 1 ( 0.00%) let ty::SubtypePredicate { a_is_expected, a, b } = . self.replace_bound_vars_with_placeholders(predicate); . 2 ( 0.00%) let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?; . . Ok(ok.unit()) . })) 306 ( 0.00%) } . 1,704 ( 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) . }); 1,420 ( 0.00%) self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b` . Ok(()) . }) 1,136 ( 0.00%) } . . /// Number of type variables created so far. 20 ( 0.00%) pub fn num_ty_vars(&self) -> usize { . self.inner.borrow_mut().type_variables().num_vars() 40 ( 0.00%) } . 57,342 ( 0.00%) pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid { 286,710 ( 0.01%) self.inner.borrow_mut().type_variables().new_var(self.universe(), origin) 86,013 ( 0.00%) } . 57,008 ( 0.00%) pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> { 200,530 ( 0.00%) self.tcx.mk_ty_var(self.next_ty_var_id(origin)) 85,512 ( 0.00%) } . 184 ( 0.00%) pub fn next_ty_var_in_universe( . &self, . origin: TypeVariableOrigin, . universe: ty::UniverseIndex, . ) -> Ty<'tcx> { 1,012 ( 0.00%) let vid = self.inner.borrow_mut().type_variables().new_var(universe, origin); 92 ( 0.00%) self.tcx.mk_ty_var(vid) 276 ( 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 { 265 ( 0.00%) self.inner.borrow_mut().int_unification_table().new_key(None) . } . 159 ( 0.00%) pub fn next_int_var(&self) -> Ty<'tcx> { . self.tcx.mk_int_var(self.next_int_var_id()) 212 ( 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. 1,068 ( 0.00%) pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> { 40,417 ( 0.00%) self.next_region_var_in_universe(origin, self.universe()) 2,136 ( 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. 17,280 ( 0.00%) pub fn next_region_var_in_universe( . &self, . origin: RegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { . let region_var = 112,320 ( 0.00%) self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin); 43,200 ( 0.00%) self.tcx.mk_region(ty::ReVar(region_var)) 25,920 ( 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. 1,828 ( 0.00%) pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex { . self.inner.borrow_mut().unwrap_region_constraints().universe(r) 2,742 ( 0.00%) } . . /// Number of region variables created so far. 550 ( 0.00%) pub fn num_region_vars(&self) -> usize { . self.inner.borrow_mut().unwrap_region_constraints().num_region_vars() 825 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 1,610 ( 0.00%) pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> { . self.next_region_var(RegionVariableOrigin::Nll(origin)) 3,220 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 15 ( 0.00%) pub fn next_nll_region_var_in_universe( . &self, . origin: NllRegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { 105 ( 0.00%) self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe) 30 ( 0.00%) } . 108,800 ( 0.00%) pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 58,702 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { . // Create a region inference variable for the given . // region parameter definition. 4,649 ( 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)`. 35,152 ( 0.00%) let ty_var_id = self.inner.borrow_mut().type_variables().new_var( . self.universe(), 43,940 ( 0.00%) TypeVariableOrigin { . kind: TypeVariableOriginKind::TypeParameterDefinition( 8,788 ( 0.00%) param.name, 8,788 ( 0.00%) Some(param.def_id), . ), . span, . }, . ); . 8,788 ( 0.00%) self.tcx.mk_ty_var(ty_var_id).into() . } . GenericParamDefKind::Const { .. } => { . let origin = ConstVariableOrigin { . kind: ConstVariableOriginKind::ConstParameterDefinition( . param.name, . param.def_id, . ), . span, . }; . let const_var_id = 1,793 ( 0.00%) self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue { . origin, . val: ConstVariableValue::Unknown { universe: self.universe() }, . }); 163 ( 0.00%) self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into() . } . } 1,304 ( 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. 30,390 ( 0.00%) pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> { 127,765 ( 0.00%) InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param)) 20,260 ( 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). 246 ( 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() . ); . 15,255 ( 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() 369 ( 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`. 16,793 ( 0.00%) pub fn resolve_regions( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) -> Vec> { 45,581 ( 0.00%) let (var_infos, data) = { . let mut inner = self.inner.borrow_mut(); . let inner = &mut *inner; 2,399 ( 0.00%) assert!( 7,197 ( 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() 2,399 ( 0.00%) }; . . let region_rels = 2,399 ( 0.00%) &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map()); . 21,591 ( 0.00%) let (lexical_region_resolutions, errors) = 57,576 ( 0.00%) lexical_region_resolve::resolve(region_rels, var_infos, data, mode); . 9,596 ( 0.00%) let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions)); 2,399 ( 0.00%) assert!(old_value.is_none()); . . errors 21,591 ( 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`. 23,990 ( 0.00%) pub fn resolve_regions_and_report_errors( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) { 4,798 ( 0.00%) let errors = self.resolve_regions(region_context, outlives_env, mode); . 7,197 ( 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. 4,798 ( 0.00%) self.report_region_errors(&errors); . } 11,995 ( 0.00%) } . . /// Obtains (and clears) the current set of region . /// constraints. The inference context is still usable: further . /// unifications will simply add new constraints. . /// . /// This method is not meant to be used with normal lexical region . /// resolution. Rather, it is used in the NLL mode as a kind of . /// interim hack: basically we run normal type-check and generate -- line 1307 ---------------------------------------- -- line 1319 ---------------------------------------- . } . . /// Gives temporary access to the region constraint data. . pub fn with_region_constraints( . &self, . op: impl FnOnce(&RegionConstraintData<'tcx>) -> R, . ) -> R { . let mut inner = self.inner.borrow_mut(); 2,192 ( 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. 330 ( 0.00%) pub fn take_region_var_origins(&self) -> VarInfos { . let mut inner = self.inner.borrow_mut(); 1,254 ( 0.00%) let (var_infos, data) = inner . .region_constraint_storage . .take() . .expect("regions already resolved") . .with_log(&mut inner.undo_log) 66 ( 0.00%) .into_infos_and_data(); 66 ( 0.00%) assert!(data.is_empty()); . var_infos 528 ( 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)`. 946 ( 0.00%) pub fn probe_ty_var(&self, vid: TyVid) -> Result, ty::UniverseIndex> { . use self::type_variable::TypeVariableValue; . 2,838 ( 0.00%) match self.inner.borrow_mut().type_variables().probe(vid) { . TypeVariableValue::Known { value } => Ok(value), . TypeVariableValue::Unknown { universe } => Err(universe), . } 3,311 ( 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>, . { 464,149 ( 0.01%) value.fold_with(&mut ShallowResolver { infcx: self }) . } . 2,006 ( 0.00%) pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid { . self.inner.borrow_mut().type_variables().root_var(var) 3,009 ( 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. 4,072 ( 0.00%) pub fn resolve_vars_if_possible(&self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { 226,368 ( 0.00%) if !value.needs_infer() { 429,769 ( 0.01%) return value; // Avoid duplicated subst-folding. . } 37,146 ( 0.00%) let mut r = resolve::OpportunisticVarResolver::new(self); 35,422 ( 0.00%) value.fold_with(&mut r) 5,083 ( 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) . } . 55,188 ( 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 = 12,257 ( 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 }, . ) . }; 139,824 ( 0.00%) self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c) 36,792 ( 0.00%) } . . /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method. 96 ( 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); . 36 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() 204 ( 0.00%) .verify_generic_bound(origin, kind, a, bound); 84 ( 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. 544 ( 0.00%) pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option { 1,088 ( 0.00%) let closure_kind_ty = closure_substs.as_closure().kind_ty(); . let closure_kind_ty = self.shallow_resolve(closure_kind_ty); 816 ( 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 { 535,214 ( 0.01%) self.universe.get() 233,853 ( 0.00%) } . . /// Creates and return a fresh universe that extends all previous . /// universes. Updates `self.universe` to that new universe. 244 ( 0.00%) pub fn create_next_universe(&self) -> ty::UniverseIndex { 244 ( 0.00%) let u = self.universe.get().next_universe(); . self.universe.set(u); . u 244 ( 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`. 1,847,712 ( 0.04%) fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> { 591,600 ( 0.01%) 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`. 135,280 ( 0.00%) let known = self.inner.borrow_mut().type_variables().probe(v).known(); . known.map_or(typ, |t| self.shallow_resolve_ty(t)) . } . 4,320 ( 0.00%) ty::Infer(ty::IntVar(v)) => self . .inner . .borrow_mut() . .int_unification_table() . .probe_value(v) 1,215 ( 0.00%) .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . . ty::Infer(ty::FloatVar(v)) => self . .inner . .borrow_mut() . .float_unification_table() . .probe_value(v) . .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . . _ => typ, . } 2,078,676 ( 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))`. 70,031 ( 0.00%) match self.inner.borrow_mut().type_variables().inlined_probe(v) { . TypeVariableValue::Unknown { .. } => false, . TypeVariableValue::Known { .. } => true, . } . } . . TyOrConstInferVar::TyInt(v) => { . // If `inlined_probe_value` returns a value it's always a . // `ty::Int(_)` or `ty::UInt(_)`, which never matches a . // `ty::Infer(_)`. 2,408 ( 0.00%) self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some() . } . . TyOrConstInferVar::TyFloat(v) => { . // If `probe_value` returns a value it's always a . // `ty::Float(_)`, which never matches a `ty::Infer(_)`. . // . // Not `inlined_probe_value(v)` because this call site is colder. . self.inner.borrow_mut().float_unification_table().probe_value(v).is_some() -- line 1688 ---------------------------------------- -- line 1716 ---------------------------------------- . /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`. . Const(ConstVid<'tcx>), . } . . impl<'tcx> TyOrConstInferVar<'tcx> { . /// Tries to extract an inference variable from a type or a constant, returns `None` . /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and . /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`). 1,115 ( 0.00%) pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option { . match arg.unpack() { . GenericArgKind::Type(ty) => Self::maybe_from_ty(ty), . GenericArgKind::Const(ct) => Self::maybe_from_const(ct), . GenericArgKind::Lifetime(_) => None, . } 1,115 ( 0.00%) } . . /// Tries to extract an inference variable from a type, returns `None` . /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`). 66 ( 0.00%) pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option { 10,541 ( 0.00%) match *ty.kind() { 2,274 ( 0.00%) ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)), 88 ( 0.00%) ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)), . ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)), . _ => None, . } 66 ( 0.00%) } . . /// Tries to extract an inference variable from a constant, returns `None` . /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`). . pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option { . match ct.val { . ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)), . _ => None, . } -- line 1749 ---------------------------------------- -- line 1755 ---------------------------------------- . } . . impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { . self.infcx.tcx . } . . fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { 437,912 ( 0.01%) self.infcx.shallow_resolve_ty(ty) . } . 1,024 ( 0.00%) fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 1,018 ( 0.00%) if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct { 1,265 ( 0.00%) self.infcx . .inner . .borrow_mut() . .const_unification_table() 759 ( 0.00%) .probe_value(*vid) . .val . .known() . .unwrap_or(ct) . } else { . ct . } 1,280 ( 0.00%) } . } . . impl<'tcx> TypeTrace<'tcx> { . pub fn span(&self) -> Span { 12 ( 0.00%) self.cause.span . } . . pub fn types( . cause: &ObligationCause<'tcx>, . a_is_expected: bool, . a: Ty<'tcx>, . b: Ty<'tcx>, . ) -> TypeTrace<'tcx> { -- line 1792 ---------------------------------------- -- line 1800 ---------------------------------------- . b: &'tcx ty::Const<'tcx>, . ) -> TypeTrace<'tcx> { . TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) } . } . } . . impl<'tcx> SubregionOrigin<'tcx> { . pub fn span(&self) -> Span { 30 ( 0.00%) match *self { 6 ( 0.00%) Subtype(ref a) => a.span(), . RelateObjectBound(a) => a, . RelateParamBound(a, ..) => a, . RelateRegionParamBound(a) => a, . Reborrow(a) => a, . ReborrowUpvar(a, _) => a, . DataBorrowed(_, a) => a, . ReferenceOutlivesReferent(_, a) => a, . CompareImplMethodObligation { span, .. } => span, -- line 1817 ---------------------------------------- -- line 1818 ---------------------------------------- . CompareImplTypeObligation { span, .. } => span, . } . } . . pub fn from_obligation_cause(cause: &traits::ObligationCause<'tcx>, default: F) -> Self . where . F: FnOnce() -> Self, . { 2,609 ( 0.00%) match *cause.code() { 438 ( 0.00%) traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => { 2,190 ( 0.00%) SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span) . } . . traits::ObligationCauseCode::CompareImplMethodObligation { . impl_item_def_id, . trait_item_def_id, . } => SubregionOrigin::CompareImplMethodObligation { . span: cause.span, . impl_item_def_id, -- line 1836 ---------------------------------------- 759,561 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_target/src/abi/mod.rs -------------------------------------------------------------------------------- Ir -- line 40 ---------------------------------------- . /// Minimum size of #[repr(C)] enums (default I32 bits) . pub c_enum_min_size: Integer, . } . . impl Default for TargetDataLayout { . /// Creates an instance of `TargetDataLayout`. . fn default() -> TargetDataLayout { . let align = |bits| Align::from_bits(bits).unwrap(); 24 ( 0.00%) TargetDataLayout { . endian: Endian::Big, . i1_align: AbiAndPrefAlign::new(align(8)), . i8_align: AbiAndPrefAlign::new(align(8)), . i16_align: AbiAndPrefAlign::new(align(16)), . i32_align: AbiAndPrefAlign::new(align(32)), . i64_align: AbiAndPrefAlign { abi: align(32), pref: align(64) }, . i128_align: AbiAndPrefAlign { abi: align(32), pref: align(64) }, . f32_align: AbiAndPrefAlign::new(align(32)), . f64_align: AbiAndPrefAlign::new(align(64)), . pointer_size: Size::from_bits(64), . pointer_align: AbiAndPrefAlign::new(align(64)), . aggregate_align: AbiAndPrefAlign { abi: align(0), pref: align(64) }, 8 ( 0.00%) vector_align: vec![ . (Size::from_bits(64), AbiAndPrefAlign::new(align(64))), . (Size::from_bits(128), AbiAndPrefAlign::new(align(128))), . ], . instruction_address_space: AddressSpace::DATA, . c_enum_min_size: Integer::I32, . } . } . } . . impl TargetDataLayout { 18 ( 0.00%) pub fn parse(target: &Target) -> Result { . // Parse an address space index from a string. . let parse_address_space = |s: &str, cause: &str| { . s.parse::().map(AddressSpace).map_err(|err| { . format!("invalid address space `{}` for `{}` in \"data-layout\": {}", s, cause, err) . }) . }; . . // Parse a bit count from a string. -- line 80 ---------------------------------------- -- line 83 ---------------------------------------- . format!("invalid {} `{}` for `{}` in \"data-layout\": {}", kind, s, cause, err) . }) . }; . . // Parse a size string. . let size = |s: &str, cause: &str| parse_bits(s, "size", cause).map(Size::from_bits); . . // Parse an alignment string. 20 ( 0.00%) let align = |s: &[&str], cause: &str| { 2 ( 0.00%) if s.is_empty() { . return Err(format!("missing alignment for `{}` in \"data-layout\"", cause)); . } 12 ( 0.00%) let align_from_bits = |bits| { . Align::from_bits(bits).map_err(|err| { . format!("invalid alignment for `{}` in \"data-layout\": {}", cause, err) . }) 16 ( 0.00%) }; 18 ( 0.00%) let abi = parse_bits(s[0], "alignment", cause)?; . let pref = s.get(1).map_or(Ok(abi), |pref| parse_bits(pref, "alignment", cause))?; 14 ( 0.00%) Ok(AbiAndPrefAlign { abi: align_from_bits(abi)?, pref: align_from_bits(pref)? }) 16 ( 0.00%) }; . . let mut dl = TargetDataLayout::default(); . let mut i128_align_src = 64; 32 ( 0.00%) for spec in target.data_layout.split('-') { . let spec_parts = spec.split(':').collect::>(); . . match &*spec_parts { 78 ( 0.00%) ["e"] => dl.endian = Endian::Little, . ["E"] => dl.endian = Endian::Big, 2 ( 0.00%) [p] if p.starts_with('P') => { . dl.instruction_address_space = parse_address_space(&p[1..], "P")? . } 44 ( 0.00%) ["a", ref a @ ..] => dl.aggregate_align = align(a, "a")?, 4 ( 0.00%) ["f32", ref a @ ..] => dl.f32_align = align(a, "f32")?, 4 ( 0.00%) ["f64", ref a @ ..] => dl.f64_align = align(a, "f64")?, 44 ( 0.00%) [p @ "p", s, ref a @ ..] | [p @ "p0", s, ref a @ ..] => { . dl.pointer_size = size(s, p)?; . dl.pointer_align = align(a, p)?; . } 64 ( 0.00%) [s, ref a @ ..] if s.starts_with('i') => { 4 ( 0.00%) let bits = match s[1..].parse::() { . Ok(bits) => bits, . Err(_) => { . size(&s[1..], "i")?; // For the user error. . continue; . } . }; 14 ( 0.00%) let a = align(a, s)?; 10 ( 0.00%) match bits { . 1 => dl.i1_align = a, . 8 => dl.i8_align = a, . 16 => dl.i16_align = a, . 32 => dl.i32_align = a, 6 ( 0.00%) 64 => dl.i64_align = a, . _ => {} . } 8 ( 0.00%) if bits >= i128_align_src && bits <= 128 { . // Default alignment for i128 is decided by taking the alignment of . // largest-sized i{64..=128}. . i128_align_src = bits; 8 ( 0.00%) dl.i128_align = a; . } . } 14 ( 0.00%) [s, ref a @ ..] if s.starts_with('v') => { . let v_size = size(&s[1..], "v")?; . let a = align(a, s)?; . if let Some(v) = dl.vector_align.iter_mut().find(|v| v.0 == v_size) { . v.1 = a; . continue; . } . // No existing entry, add a new one. . dl.vector_align.push((v_size, a)); . } . _ => {} // Ignore everything else. . } . } . . // Perform consistency checks against the Target information. 8 ( 0.00%) if dl.endian != target.endian { . return Err(format!( . "inconsistent target specification: \"data-layout\" claims \ . architecture is {}-endian, while \"target-endian\" is `{}`", . dl.endian.as_str(), . target.endian.as_str(), . )); . } . 10 ( 0.00%) if dl.pointer_size.bits() != target.pointer_width.into() { . return Err(format!( . "inconsistent target specification: \"data-layout\" claims \ . pointers are {}-bit, while \"target-pointer-width\" is `{}`", . dl.pointer_size.bits(), . target.pointer_width . )); . } . 4 ( 0.00%) dl.c_enum_min_size = Integer::from_size(Size::from_bits(target.c_enum_min_bits))?; . 34 ( 0.00%) Ok(dl) 18 ( 0.00%) } . . /// Returns exclusive upper bound on object size. . /// . /// The theoretical maximum object size is defined as the maximum positive `isize` value. . /// This ensures that the `offset` semantics remain well-defined by allowing it to correctly . /// index every address within an object along with one byte past the end, along with allowing . /// `isize` to store the difference between any two pointers into an object. . /// . /// The upper bound on 64-bit currently needs to be lower because LLVM uses a 64-bit integer . /// to represent object size in bits. It would need to be 1 << 61 to account for this, but is . /// currently conservatively bounded to 1 << 47 as that is enough to cover the current usable . /// address space on 64-bit ARMv8 and x86_64. . #[inline] . pub fn obj_size_bound(&self) -> u64 { 959,712 ( 0.02%) match self.pointer_size.bits() { . 16 => 1 << 15, . 32 => 1 << 31, . 64 => 1 << 47, . bits => panic!("obj_size_bound: unknown pointer bit size {}", bits), . } 91 ( 0.00%) } . . #[inline] . pub fn ptr_sized_integer(&self) -> Integer { 6,987 ( 0.00%) match self.pointer_size.bits() { . 16 => I16, . 32 => I32, . 64 => I64, . bits => panic!("ptr_sized_integer: unknown pointer bit size {}", bits), . } 36 ( 0.00%) } . . #[inline] 2 ( 0.00%) pub fn vector_align(&self, vec_size: Size) -> AbiAndPrefAlign { 4 ( 0.00%) for &(size, align) in &self.vector_align { 4 ( 0.00%) if size == vec_size { . return align; . } . } . // Default to natural alignment, which is what LLVM does. . // That is, use the size, rounded up to a power of 2. . AbiAndPrefAlign::new(Align::from_bytes(vec_size.bytes().next_power_of_two()).unwrap()) 3 ( 0.00%) } . } . . pub trait HasDataLayout { . fn data_layout(&self) -> &TargetDataLayout; . } . . impl HasDataLayout for TargetDataLayout { . #[inline] . fn data_layout(&self) -> &TargetDataLayout { . self . } . } . . /// Endianness of the target, which must match cfg(target-endian). 2 ( 0.00%) #[derive(Copy, Clone, PartialEq)] . pub enum Endian { . Little, . Big, . } . . impl Endian { . pub fn as_str(&self) -> &'static str { 3 ( 0.00%) match self { . Self::Little => "little", . Self::Big => "big", . } 1 ( 0.00%) } . } . . impl fmt::Debug for Endian { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . f.write_str(self.as_str()) . } . } . -- line 261 ---------------------------------------- -- line 273 ---------------------------------------- . . impl ToJson for Endian { . fn to_json(&self) -> Json { . self.as_str().to_json() . } . } . . /// Size of a type in bytes. 3 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encodable, Decodable)] . #[derive(HashStable_Generic)] . pub struct Size { . // The top 3 bits are ALWAYS zero. 437,050 ( 0.01%) raw: u64, . } . . impl Size { . pub const ZERO: Size = Size { raw: 0 }; . . /// Rounds `bits` up to the next-higher byte boundary, if `bits` is . /// is not aligned. . pub fn from_bits(bits: impl TryInto) -> Size { -- line 293 ---------------------------------------- -- line 296 ---------------------------------------- . #[cold] . fn overflow(bits: u64) -> ! { . panic!("Size::from_bits({}) has overflowed", bits); . } . . // This is the largest value of `bits` that does not cause overflow . // during rounding, and guarantees that the resulting number of bytes . // cannot cause overflow when multiplied by 8. 98 ( 0.00%) if bits > 0xffff_ffff_ffff_fff8 { . overflow(bits); . } . . // Avoid potential overflow from `bits + 7`. 896 ( 0.00%) Size { raw: bits / 8 + ((bits % 8) + 7) / 8 } . } . . #[inline] . pub fn from_bytes(bytes: impl TryInto) -> Size { . let bytes: u64 = bytes.try_into().ok().unwrap(); . Size { raw: bytes } . } . -- line 317 ---------------------------------------- -- line 322 ---------------------------------------- . . #[inline] . pub fn bytes_usize(self) -> usize { . self.bytes().try_into().unwrap() . } . . #[inline] . pub fn bits(self) -> u64 { 791,103 ( 0.02%) self.raw << 3 . } . . #[inline] . pub fn bits_usize(self) -> usize { . self.bits().try_into().unwrap() . } . . #[inline] 106 ( 0.00%) pub fn align_to(self, align: Align) -> Size { 35,387 ( 0.00%) let mask = align.bytes() - 1; 34,170 ( 0.00%) Size::from_bytes((self.bytes() + mask) & !mask) 318 ( 0.00%) } . . #[inline] . pub fn is_aligned(self, align: Align) -> bool { 24 ( 0.00%) let mask = align.bytes() - 1; 12 ( 0.00%) self.bytes() & mask == 0 . } . . #[inline] . pub fn checked_add(self, offset: Size, cx: &C) -> Option { . let dl = cx.data_layout(); . 159,784 ( 0.00%) let bytes = self.bytes().checked_add(offset.bytes())?; . 796,877 ( 0.02%) if bytes < dl.obj_size_bound() { Some(Size::from_bytes(bytes)) } else { None } . } . . #[inline] 50 ( 0.00%) pub fn checked_mul(self, count: u64, cx: &C) -> Option { . let dl = cx.data_layout(); . 77 ( 0.00%) let bytes = self.bytes().checked_mul(count)?; 199 ( 0.00%) if bytes < dl.obj_size_bound() { Some(Size::from_bytes(bytes)) } else { None } 25 ( 0.00%) } . . /// Truncates `value` to `self` bits and then sign-extends it to 128 bits . /// (i.e., if it is negative, fill with 1's on the left). . #[inline] . pub fn sign_extend(self, value: u128) -> u128 { . let size = self.bits(); 8 ( 0.00%) if size == 0 { . // Truncated until nothing is left. . return 0; . } . // Sign-extend it. 1,795 ( 0.00%) let shift = 128 - size; . // Shift the unsigned value to the left, then shift back to the right as signed . // (essentially fills with sign bit on the left). 60,830 ( 0.00%) (((value << shift) as i128) >> shift) as u128 . } . . /// Truncates `value` to `self` bits. . #[inline] . pub fn truncate(self, value: u128) -> u128 { . let size = self.bits(); 269,476 ( 0.01%) if size == 0 { . // Truncated until nothing is left. . return 0; . } 261,245 ( 0.01%) let shift = 128 - size; . // Truncate (shift left to drop out leftover values, shift right to fill with zeroes). 3,057,793 ( 0.06%) (value << shift) >> shift . } . . #[inline] . pub fn signed_int_min(&self) -> i128 { 16,083 ( 0.00%) self.sign_extend(1_u128 << (self.bits() - 1)) as i128 . } . . #[inline] . pub fn signed_int_max(&self) -> i128 { 16,083 ( 0.00%) i128::MAX >> (128 - self.bits()) . } . . #[inline] 91 ( 0.00%) pub fn unsigned_int_max(&self) -> u128 { 693,756 ( 0.01%) u128::MAX >> (128 - self.bits()) 182 ( 0.00%) } . } . . // Panicking addition, subtraction and multiplication for convenience. . // Avoid during layout computation, return `LayoutError` instead. . . impl Add for Size { . type Output = Size; . #[inline] . fn add(self, other: Size) -> Size { . Size::from_bytes(self.bytes().checked_add(other.bytes()).unwrap_or_else(|| { . panic!("Size::add: {} + {} doesn't fit in u64", self.bytes(), other.bytes()) . })) 43 ( 0.00%) } . } . . impl Sub for Size { . type Output = Size; . #[inline] . fn sub(self, other: Size) -> Size { . Size::from_bytes(self.bytes().checked_sub(other.bytes()).unwrap_or_else(|| { . panic!("Size::sub: {} - {} would result in negative size", self.bytes(), other.bytes()) -- line 430 ---------------------------------------- -- line 438 ---------------------------------------- . fn mul(self, size: Size) -> Size { . size * self . } . } . . impl Mul for Size { . type Output = Size; . #[inline] 55,524 ( 0.00%) fn mul(self, count: u64) -> Size { 105,732 ( 0.00%) match self.bytes().checked_mul(count) { . Some(bytes) => Size::from_bytes(bytes), . None => panic!("Size::mul: {} * {} doesn't fit in u64", self.bytes(), count), . } 55,524 ( 0.00%) } . } . . impl AddAssign for Size { . #[inline] . fn add_assign(&mut self, other: Size) { 16,679 ( 0.00%) *self = *self + other; . } . } . . impl Step for Size { . #[inline] . fn steps_between(start: &Self, end: &Self) -> Option { . u64::steps_between(&start.bytes(), &end.bytes()) . } -- line 465 ---------------------------------------- -- line 494 ---------------------------------------- . Self::from_bytes(u64::backward_unchecked(start.bytes(), count)) . } . } . . /// Alignment of a type in bytes (always a power of two). . #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encodable, Decodable)] . #[derive(HashStable_Generic)] . pub struct Align { 62,384 ( 0.00%) pow2: u8, . } . . impl Align { . pub const ONE: Align = Align { pow2: 0 }; . . #[inline] . pub fn from_bits(bits: u64) -> Result { . Align::from_bytes(Size::from_bits(bits).bytes()) . } . . #[inline] . pub fn from_bytes(align: u64) -> Result { . // Treat an alignment of 0 bytes like 1-byte alignment. 8 ( 0.00%) if align == 0 { . return Ok(Align::ONE); . } . . #[cold] . fn not_power_of_2(align: u64) -> String { . format!("`{}` is not a power of 2", align) . } . . #[cold] . fn too_large(align: u64) -> String { . format!("`{}` is too large", align) . } . . let mut bytes = align; . let mut pow2: u8 = 0; 78 ( 0.00%) while (bytes & 1) == 0 { 51 ( 0.00%) pow2 += 1; 34 ( 0.00%) bytes >>= 1; . } 10 ( 0.00%) if bytes != 1 { . return Err(not_power_of_2(align)); . } 10 ( 0.00%) if pow2 > 29 { . return Err(too_large(align)); . } . 182 ( 0.00%) Ok(Align { pow2 }) . } . . #[inline] . pub fn bytes(self) -> u64 { 104,692 ( 0.00%) 1 << self.pow2 . } . . #[inline] . pub fn bits(self) -> u64 { 8,711 ( 0.00%) self.bytes() * 8 . } . . /// Computes the best alignment possible for the given offset . /// (the largest power of two that the offset is a multiple of). . /// . /// N.B., for an offset of `0`, this happens to return `2^64`. . #[inline] . pub fn max_for_offset(offset: Size) -> Align { -- line 561 ---------------------------------------- -- line 591 ---------------------------------------- . . #[inline] . pub fn max(self, other: AbiAndPrefAlign) -> AbiAndPrefAlign { . AbiAndPrefAlign { abi: self.abi.max(other.abi), pref: self.pref.max(other.pref) } . } . } . . /// Integers, also used for enum discriminants. 114,095 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, HashStable_Generic)] . pub enum Integer { . I8, . I16, . I32, . I64, . I128, . } . . impl Integer { . #[inline] . pub fn size(self) -> Size { 668,037 ( 0.01%) match self { . I8 => Size::from_bytes(1), . I16 => Size::from_bytes(2), . I32 => Size::from_bytes(4), . I64 => Size::from_bytes(8), . I128 => Size::from_bytes(16), . } . } . . pub fn align(self, cx: &C) -> AbiAndPrefAlign { . let dl = cx.data_layout(); . 14,485 ( 0.00%) match self { 227,479 ( 0.00%) I8 => dl.i8_align, 11,360 ( 0.00%) I16 => dl.i16_align, 2,041 ( 0.00%) I32 => dl.i32_align, 5,379 ( 0.00%) I64 => dl.i64_align, . I128 => dl.i128_align, . } . } . . /// Finds the smallest Integer type which can represent the signed value. . #[inline] . pub fn fit_signed(x: i128) -> Integer { . match x { 1,274 ( 0.00%) -0x0000_0000_0000_0080..=0x0000_0000_0000_007f => I8, . -0x0000_0000_0000_8000..=0x0000_0000_0000_7fff => I16, . -0x0000_0000_8000_0000..=0x0000_0000_7fff_ffff => I32, . -0x8000_0000_0000_0000..=0x7fff_ffff_ffff_ffff => I64, . _ => I128, . } . } . . /// Finds the smallest Integer type which can represent the unsigned value. . #[inline] . pub fn fit_unsigned(x: u128) -> Integer { . match x { 364 ( 0.00%) 0..=0x0000_0000_0000_00ff => I8, 8 ( 0.00%) 0..=0x0000_0000_0000_ffff => I16, 12 ( 0.00%) 0..=0x0000_0000_ffff_ffff => I32, . 0..=0xffff_ffff_ffff_ffff => I64, . _ => I128, . } . } . . /// Finds the smallest integer with the given alignment. 1,056 ( 0.00%) pub fn for_align(cx: &C, wanted: Align) -> Option { . let dl = cx.data_layout(); . 6,861 ( 0.00%) for candidate in [I8, I16, I32, I64, I128] { 1,367 ( 0.00%) if wanted == candidate.align(dl).abi && wanted.bytes() == candidate.size().bytes() { . return Some(candidate); . } . } . None 1,056 ( 0.00%) } . . /// Find the largest integer with the given alignment or less. . pub fn approximate_align(cx: &C, wanted: Align) -> Integer { . let dl = cx.data_layout(); . . // FIXME(eddyb) maybe include I128 in the future, when it works everywhere. . for candidate in [I64, I32, I16] { 5,723 ( 0.00%) if wanted >= candidate.align(dl).abi && wanted.bytes() >= candidate.size().bytes() { . return candidate; . } . } . I8 . } . . // FIXME(eddyb) consolidate this and other methods that find the appropriate . // `Integer` given some requirements. . #[inline] . fn from_size(size: Size) -> Result { 8 ( 0.00%) match size.bits() { . 8 => Ok(Integer::I8), . 16 => Ok(Integer::I16), . 32 => Ok(Integer::I32), . 64 => Ok(Integer::I64), . 128 => Ok(Integer::I128), . _ => Err(format!("rust does not support integers with {} bits", size.bits())), . } . } . } . . /// Fundamental unit of memory access and layout. 1,969,609 ( 0.04%) #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub enum Primitive { . /// The `bool` is the signedness of the `Integer` type. . /// . /// One would think we would not care about such details this low down, . /// but some ABIs are described in terms of C types and ISAs where the . /// integer arithmetic is done on {sign,zero}-extended registers, e.g. . /// a negative integer passed by zero-extension will appear positive in . /// the callee, and most operations on it will produce the wrong values. 683,699 ( 0.01%) Int(Integer, bool), . F32, . F64, . Pointer, . } . . impl Primitive { . pub fn size(self, cx: &C) -> Size { . let dl = cx.data_layout(); . 891,809 ( 0.02%) match self { . Int(i, _) => i.size(), . F32 => Size::from_bits(32), . F64 => Size::from_bits(64), 7,860 ( 0.00%) Pointer => dl.pointer_size, . } 91 ( 0.00%) } . . pub fn align(self, cx: &C) -> AbiAndPrefAlign { . let dl = cx.data_layout(); . 26,015 ( 0.00%) match self { . Int(i, _) => i.align(dl), . F32 => dl.f32_align, . F64 => dl.f64_align, 1,828 ( 0.00%) Pointer => dl.pointer_align, . } . } . . // FIXME(eddyb) remove, it's trivial thanks to `matches!`. . #[inline] . pub fn is_float(self) -> bool { . matches!(self, F32 | F64) . } -- line 739 ---------------------------------------- -- line 753 ---------------------------------------- . /// sequence: . /// . /// 254 (-2), 255 (-1), 0, 1, 2 . /// . /// This is intended specifically to mirror LLVM’s `!range` metadata semantics. . #[derive(Clone, Copy, PartialEq, Eq, Hash)] . #[derive(HashStable_Generic)] . pub struct WrappingRange { 345,178 ( 0.01%) pub start: u128, . pub end: u128, . } . . impl WrappingRange { . /// Returns `true` if `v` is contained in the range. . #[inline(always)] . pub fn contains(&self, v: u128) -> bool { 10,252 ( 0.00%) if self.start <= self.end { . self.start <= v && v <= self.end . } else { . self.start <= v || v <= self.end . } . } . . /// Returns `self` with replaced `start` . #[inline(always)] -- line 777 ---------------------------------------- -- line 787 ---------------------------------------- . self . } . . /// Returns `true` if `size` completely fills the range. . #[inline] . pub fn is_full_for(&self, size: Size) -> bool { . let max_value = size.unsigned_int_max(); . debug_assert!(self.start <= max_value && self.end <= max_value); 37,442 ( 0.00%) self.start == (self.end.wrapping_add(1) & max_value) . } . } . . impl fmt::Debug for WrappingRange { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . if self.start > self.end { . write!(fmt, "(..={}) | ({}..)", self.end, self.start)?; . } else { -- line 803 ---------------------------------------- -- line 806 ---------------------------------------- . Ok(()) . } . } . . /// Information about one scalar component of a Rust type. . #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] . #[derive(HashStable_Generic)] . pub struct Scalar { 402,605 ( 0.01%) pub value: Primitive, . . // FIXME(eddyb) always use the shortest range, e.g., by finding . // the largest space between two consecutive valid values and . // taking everything else as the (shortest) valid range. 459,051 ( 0.01%) pub valid_range: WrappingRange, . } . . impl Scalar { . #[inline] . pub fn is_bool(&self) -> bool { 92,895 ( 0.00%) matches!( 50,186 ( 0.00%) self, . Scalar { value: Int(I8, false), valid_range: WrappingRange { start: 0, end: 1 } } . ) . } . . /// Returns `true` if all possible numbers are valid, i.e `valid_range` covers the whole layout . #[inline] 108 ( 0.00%) pub fn is_always_valid(&self, cx: &C) -> bool { 12,030 ( 0.00%) self.valid_range.is_full_for(self.value.size(cx)) 216 ( 0.00%) } . } . . /// Describes how the fields of a type are located in memory. 950,292 ( 0.02%) #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub enum FieldsShape { . /// Scalar primitives and `!`, which never have fields. . Primitive, . . /// All fields start at no offset. The `usize` is the field count. 5 ( 0.00%) Union(NonZeroUsize), . . /// Array/vector-like placement, with all fields of identical types. 68 ( 0.00%) Array { stride: Size, count: u64 }, . . /// Struct-like placement, with precomputed offsets. . /// . /// Fields are guaranteed to not overlap, but note that gaps . /// before, between and after all the fields are NOT always . /// padding, and as such their contents may not be discarded. . /// For example, enum variants leave a gap at the start, . /// where the discriminant field in the enum layout goes. -- line 856 ---------------------------------------- -- line 875 ---------------------------------------- . // FIXME(camlorn) also consider small vector optimization here. . memory_index: Vec, . }, . } . . impl FieldsShape { . #[inline] . pub fn count(&self) -> usize { 24,012 ( 0.00%) match *self { . FieldsShape::Primitive => 0, . FieldsShape::Union(count) => count.get(), . FieldsShape::Array { count, .. } => count.try_into().unwrap(), 8,467 ( 0.00%) FieldsShape::Arbitrary { ref offsets, .. } => offsets.len(), . } . } . . #[inline] 291,464 ( 0.01%) pub fn offset(&self, i: usize) -> Size { 913,904 ( 0.02%) match *self { . FieldsShape::Primitive => { . unreachable!("FieldsShape::offset: `Primitive`s have no fields") . } 84 ( 0.00%) FieldsShape::Union(count) => { 42 ( 0.00%) assert!( 42 ( 0.00%) i < count.get(), . "tried to access field {} of union with {} fields", . i, . count . ); . Size::ZERO . } . FieldsShape::Array { stride, count } => { . let i = u64::try_from(i).unwrap(); 19,982 ( 0.00%) assert!(i < count); . stride * i . } 174,260 ( 0.00%) FieldsShape::Arbitrary { ref offsets, .. } => offsets[i], . } 291,464 ( 0.01%) } . . #[inline] . pub fn memory_index(&self, i: usize) -> usize { 2,718 ( 0.00%) match *self { . FieldsShape::Primitive => { . unreachable!("FieldsShape::memory_index: `Primitive`s have no fields") . } . FieldsShape::Union(_) | FieldsShape::Array { .. } => i, . FieldsShape::Arbitrary { ref memory_index, .. } => memory_index[i].try_into().unwrap(), . } . } . . /// Gets source indices of the fields by increasing offsets. . #[inline] . pub fn index_by_increasing_offset<'a>(&'a self) -> impl Iterator + 'a { 9,660 ( 0.00%) let mut inverse_small = [0u8; 64]; . let mut inverse_big = vec![]; 1,983 ( 0.00%) let use_small = self.count() <= inverse_small.len(); . . // We have to write this logic twice in order to keep the array small. . if let FieldsShape::Arbitrary { ref memory_index, .. } = *self { 1,983 ( 0.00%) if use_small { . for i in 0..self.count() { 5,238 ( 0.00%) inverse_small[memory_index[i] as usize] = i as u8; . } . } else { . inverse_big = vec![0; self.count()]; . for i in 0..self.count() { . inverse_big[memory_index[i] as usize] = i as u32; . } . } . } . 27,506 ( 0.00%) (0..self.count()).map(move |i| match *self { . FieldsShape::Primitive | FieldsShape::Union(_) | FieldsShape::Array { .. } => i, . FieldsShape::Arbitrary { .. } => { 1,619 ( 0.00%) if use_small { 3,365 ( 0.00%) inverse_small[i] as usize . } else { . inverse_big[i] as usize . } . } . }) . } . } . -- line 959 ---------------------------------------- -- line 965 ---------------------------------------- . . impl AddressSpace { . /// The default address space, corresponding to data space. . pub const DATA: Self = AddressSpace(0); . } . . /// Describes how values of the type are passed by target ABIs, . /// in terms of categories of C types there are ABI rules for. 595,789 ( 0.01%) #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub enum Abi { . Uninhabited, . Scalar(Scalar), 630 ( 0.00%) ScalarPair(Scalar, Scalar), . Vector { . element: Scalar, . count: u64, . }, . Aggregate { . /// If true, the size is exact, otherwise it's only a lower bound. 9,094 ( 0.00%) sized: bool, . }, . } . . impl Abi { . /// Returns `true` if the layout corresponds to an unsized type. . #[inline] . pub fn is_unsized(&self) -> bool { 533,580 ( 0.01%) match *self { . Abi::Uninhabited | Abi::Scalar(_) | Abi::ScalarPair(..) | Abi::Vector { .. } => false, . Abi::Aggregate { sized } => !sized, . } . } . . /// Returns `true` if this is a single signed integer scalar . #[inline] . pub fn is_signed(&self) -> bool { 145,238 ( 0.00%) match self { 338,774 ( 0.01%) Abi::Scalar(scal) => match scal.value { . Primitive::Int(_, signed) => signed, . _ => false, . }, . _ => panic!("`is_signed` on non-scalar ABI {:?}", self), . } . } . . /// Returns `true` if this is an uninhabited type . #[inline] . pub fn is_uninhabited(&self) -> bool { 20,982 ( 0.00%) matches!(*self, Abi::Uninhabited) . } . . /// Returns `true` is this is a scalar type . #[inline] . pub fn is_scalar(&self) -> bool { 10 ( 0.00%) matches!(*self, Abi::Scalar(_)) . } . } . . rustc_index::newtype_index! { . pub struct VariantIdx { . derive [HashStable_Generic] . } . } . 661,457 ( 0.01%) #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub enum Variants { . /// Single enum variants, structs/tuples, unions, and all non-ADTs. 98,007 ( 0.00%) Single { index: VariantIdx }, . . /// Enum-likes with more than one inhabited variant: each variant comes with . /// a *discriminant* (usually the same as the variant index but the user can . /// assign explicit discriminant values). That discriminant is encoded . /// as a *tag* on the machine. The layout of each variant is . /// a struct, and they all have space reserved for the tag. . /// For enums, the tag is the sole field of the layout. . Multiple { . tag: Scalar, 245 ( 0.00%) tag_encoding: TagEncoding, 196 ( 0.00%) tag_field: usize, 49 ( 0.00%) variants: IndexVec, . }, . } . 1,130 ( 0.00%) #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub enum TagEncoding { . /// The tag directly stores the discriminant, but possibly with a smaller layout . /// (so converting the tag to the discriminant can require sign extension). . Direct, . . /// Niche (values invalid for a type) encoding the discriminant: . /// Discriminant and variant index coincide. . /// The variant `dataful_variant` contains a niche at an arbitrary -- line 1056 ---------------------------------------- -- line 1057 ---------------------------------------- . /// offset (field `tag_field` of the enum), which for a variant with . /// discriminant `d` is set to . /// `(d - niche_variants.start).wrapping_add(niche_start)`. . /// . /// For example, `Option<(usize, &T)>` is represented such that . /// `None` has a null pointer for the second tuple field, and . /// `Some` is the identity function (with a non-null reference). . Niche { 28 ( 0.00%) dataful_variant: VariantIdx, 28 ( 0.00%) niche_variants: RangeInclusive, 168 ( 0.00%) niche_start: u128, . }, . } . . #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub struct Niche { 57,311 ( 0.00%) pub offset: Size, 57,311 ( 0.00%) pub scalar: Scalar, . } . . impl Niche { 1,284 ( 0.00%) pub fn from_scalar(cx: &C, offset: Size, scalar: Scalar) -> Option { 1,284 ( 0.00%) let niche = Niche { offset, scalar }; 921,714 ( 0.02%) if niche.available(cx) > 0 { Some(niche) } else { None } 1,498 ( 0.00%) } . 68 ( 0.00%) pub fn available(&self, cx: &C) -> u128 { 352 ( 0.00%) let Scalar { value, valid_range: v } = self.scalar; . let size = value.size(cx); 117,042 ( 0.00%) assert!(size.bits() <= 128); . let max_value = size.unsigned_int_max(); . . // Find out how many values are outside the valid range. . let niche = v.end.wrapping_add(1)..v.start; 8,311 ( 0.00%) niche.end.wrapping_sub(niche.start) & max_value 136 ( 0.00%) } . 301 ( 0.00%) pub fn reserve(&self, cx: &C, count: u128) -> Option<(u128, Scalar)> { 129 ( 0.00%) assert!(count > 0); . 258 ( 0.00%) let Scalar { value, valid_range: v } = self.scalar; . let size = value.size(cx); 86 ( 0.00%) assert!(size.bits() <= 128); . let max_value = size.unsigned_int_max(); . . let niche = v.end.wrapping_add(1)..v.start; 129 ( 0.00%) let available = niche.end.wrapping_sub(niche.start) & max_value; 129 ( 0.00%) if count > available { . return None; . } . . // Extend the range of valid values being reserved by moving either `v.start` or `v.end` bound. . // Given an eventual `Option`, we try to maximize the chance for `None` to occupy the niche of zero. . // This is accomplished by prefering enums with 2 variants(`count==1`) and always taking the shortest path to niche zero. . // Having `None` in niche zero can enable some special optimizations. . // -- line 1112 ---------------------------------------- -- line 1120 ---------------------------------------- . let start = v.start.wrapping_sub(count) & max_value; . Some((start, Scalar { value, valid_range: v.with_start(start) })) . }; . let move_end = |v: WrappingRange| { . let start = v.end.wrapping_add(1) & max_value; . let end = v.end.wrapping_add(count) & max_value; . Some((start, Scalar { value, valid_range: v.with_end(end) })) . }; 215 ( 0.00%) let distance_end_zero = max_value - v.end; 172 ( 0.00%) if v.start > v.end { . // zero is unavailable because wrapping occurs . move_end(v) 129 ( 0.00%) } else if v.start <= distance_end_zero { 40 ( 0.00%) if count <= v.start { . move_start(v) . } else { . // moved past zero, use other bound . move_end(v) . } . } else { 66 ( 0.00%) let end = v.end.wrapping_add(count) & max_value; . let overshot_zero = (1..=v.end).contains(&end); 99 ( 0.00%) if overshot_zero { . // moved past zero, use other bound . move_start(v) . } else { . move_end(v) . } . } 387 ( 0.00%) } . } . 848,428 ( 0.02%) #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub struct Layout { . /// Says where the fields are located within the layout. . pub fields: FieldsShape, . . /// Encodes information about multi-variant layouts. . /// Even with `Multiple` variants, a layout still has its own fields! Those are then . /// shared between all variants. One of them will be the discriminant, . /// but e.g. generators can have more. . /// . /// To access all fields of this layout, both `fields` and the fields of the active variant . /// must be taken into account. 2,807 ( 0.00%) pub variants: Variants, . . /// The `abi` defines how this data is passed between functions, and it defines . /// value restrictions via `valid_range`. . /// . /// Note that this is entirely orthogonal to the recursive structure defined by . /// `variants` and `fields`; for example, `ManuallyDrop>` has . /// `Abi::ScalarPair`! So, even with non-`Aggregate` `abi`, `fields` and `variants` . /// have to be taken into account to find all fields of this layout. 58,814 ( 0.00%) pub abi: Abi, . . /// The leaf scalar with the largest number of invalid values . /// (i.e. outside of its `valid_range`), if it exists. 290,388 ( 0.01%) pub largest_niche: Option, . 469,854 ( 0.01%) pub align: AbiAndPrefAlign, 235,452 ( 0.00%) pub size: Size, . } . . impl Layout { 344,106 ( 0.01%) pub fn scalar(cx: &C, scalar: Scalar) -> Self { 344,106 ( 0.01%) let largest_niche = Niche::from_scalar(cx, Size::ZERO, scalar); . let size = scalar.value.size(cx); . let align = scalar.value.align(cx); 1,204,371 ( 0.02%) Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, . fields: FieldsShape::Primitive, 344,106 ( 0.01%) abi: Abi::Scalar(scalar), 229,404 ( 0.00%) largest_niche, . size, . align, . } 458,808 ( 0.01%) } . } . . /// The layout of a type, alongside the type itself. . /// Provides various type traversal APIs (e.g., recursing into fields). . /// . /// Note that the layout is NOT guaranteed to always be identical . /// to that obtained from `layout_of(ty)`, as we need to produce . /// layouts for which Rust types do not exist, such as enum variants . /// or synthetic fields of enums (i.e., discriminants) and fat pointers. 7 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable_Generic)] . pub struct TyAndLayout<'a, Ty> { 252,572 ( 0.01%) pub ty: Ty, 518,073 ( 0.01%) pub layout: &'a Layout, . } . . impl<'a, Ty> Deref for TyAndLayout<'a, Ty> { . type Target = &'a Layout; . fn deref(&self) -> &&'a Layout { 466 ( 0.00%) &self.layout . } . } . 1,944 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Debug)] . pub enum PointerKind { . /// Most general case, we know no restrictions to tell LLVM. . Shared, . . /// `&T` where `T` contains no `UnsafeCell`, is `noalias` and `readonly`. . Frozen, . . /// `&mut T` which is `noalias` but not `readonly`. -- line 1227 ---------------------------------------- -- line 1251 ---------------------------------------- . fn ty_and_layout_pointee_info_at( . this: TyAndLayout<'a, Self>, . cx: &C, . offset: Size, . ) -> Option; . } . . impl<'a, Ty> TyAndLayout<'a, Ty> { 380 ( 0.00%) pub fn for_variant(self, cx: &C, variant_index: VariantIdx) -> Self . where . Ty: TyAbiInterface<'a, C>, . { 125,144 ( 0.00%) Ty::ty_and_layout_for_variant(self, cx, variant_index) 380 ( 0.00%) } . 2,850 ( 0.00%) pub fn field(self, cx: &C, i: usize) -> Self . where . Ty: TyAbiInterface<'a, C>, . { 771,358 ( 0.02%) Ty::ty_and_layout_field(self, cx, i) 1,520 ( 0.00%) } . . pub fn pointee_info_at(self, cx: &C, offset: Size) -> Option . where . Ty: TyAbiInterface<'a, C>, . { 15,526 ( 0.00%) Ty::ty_and_layout_pointee_info_at(self, cx, offset) . } . } . . impl<'a, Ty> TyAndLayout<'a, Ty> { . /// Returns `true` if the layout corresponds to an unsized type. . pub fn is_unsized(&self) -> bool { 72,015 ( 0.00%) self.abi.is_unsized() . } . . /// Returns `true` if the type is a ZST and not unsized. . pub fn is_zst(&self) -> bool { 622,284 ( 0.01%) match self.abi { . Abi::Scalar(_) | Abi::ScalarPair(..) | Abi::Vector { .. } => false, . Abi::Uninhabited => self.size.bytes() == 0, 94,536 ( 0.00%) Abi::Aggregate { sized } => sized && self.size.bytes() == 0, . } 15 ( 0.00%) } . . /// Determines if this type permits "raw" initialization by just transmuting some . /// memory into an instance of `T`. . /// `zero` indicates if the memory is zero-initialized, or alternatively . /// left entirely uninitialized. . /// This is conservative: in doubt, it will answer `true`. . /// . /// FIXME: Once we removed all the conservatism, we could alternatively -- line 1302 ---------------------------------------- 2,906,692 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/middle/region.rs -------------------------------------------------------------------------------- Ir -- line 77 ---------------------------------------- . // . // FIXME(pnkfelix): this currently derives `PartialOrd` and `Ord` to . // placate the same deriving in `ty::FreeRegion`, but we may want to . // actually attach a more meaningful ordering to scopes than the one . // generated via deriving here. . #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Copy, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub struct Scope { 40,488 ( 0.00%) pub id: hir::ItemLocalId, 871,590 ( 0.02%) pub data: ScopeData, . } . . impl fmt::Debug for Scope { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . match self.data { . ScopeData::Node => write!(fmt, "Node({:?})", self.id), . ScopeData::CallSite => write!(fmt, "CallSite({:?})", self.id), . ScopeData::Arguments => write!(fmt, "Arguments({:?})", self.id), -- line 94 ---------------------------------------- -- line 99 ---------------------------------------- . "Remainder {{ block: {:?}, first_statement_index: {}}}", . self.id, . fsi.as_u32(), . ), . } . } . } . 3,958,407 ( 0.08%) #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub enum ScopeData { . Node, . . /// Scope of the call-site for a function or closure . /// (outlives the arguments as well as the body). . CallSite, . -- line 115 ---------------------------------------- -- line 159 ---------------------------------------- . /// . /// N.B., likely to be replaced as API is refined; e.g., pnkfelix . /// anticipates `fn entry_node_id` and `fn each_exit_node_id`. . pub fn item_local_id(&self) -> hir::ItemLocalId { . self.id . } . . pub fn hir_id(&self, scope_tree: &ScopeTree) -> Option { 17,101 ( 0.00%) scope_tree . .root_body . .map(|hir_id| hir::HirId { owner: hir_id.owner, local_id: self.item_local_id() }) . } . . /// Returns the span of this `Scope`. Note that in general the . /// returned span may not correspond to the span of any `NodeId` in . /// the AST. 119,707 ( 0.00%) pub fn span(&self, tcx: TyCtxt<'_>, scope_tree: &ScopeTree) -> Span { 34,202 ( 0.00%) let hir_id = match self.hir_id(scope_tree) { . Some(hir_id) => hir_id, . None => return DUMMY_SP, . }; 68,404 ( 0.00%) let span = tcx.hir().span(hir_id); 68,404 ( 0.00%) if let ScopeData::Remainder(first_statement_index) = self.data { 1,194 ( 0.00%) if let Node::Block(ref blk) = tcx.hir().get(hir_id) { . // Want span for scope starting after the . // indexed statement and ending at end of . // `blk`; reuse span of `blk` and shift `lo` . // forward to end of indexed statement. . // . // (This is the special case alluded to in the . // doc-comment for this method) . 1,592 ( 0.00%) let stmt_span = blk.stmts[first_statement_index.index()].span; . . // To avoid issues with macro-generated spans, the span . // of the statement must be nested in that of the block. 395 ( 0.00%) if span.lo() <= stmt_span.lo() && stmt_span.lo() <= span.hi() { 764 ( 0.00%) return span.with_lo(stmt_span.lo()); . } . } . } . span 153,909 ( 0.00%) } . } . . pub type ScopeDepth = u32; . . /// The region scope tree encodes information about region relationships. . #[derive(Default, Debug)] . pub struct ScopeTree { . /// If not empty, this body is the root of this region hierarchy. -- line 209 ---------------------------------------- -- line 321 ---------------------------------------- . /// The `Span` of the yield. . pub span: Span, . /// The number of expressions and patterns appearing before the `yield` in the body, plus one. . pub expr_and_pat_count: usize, . pub source: hir::YieldSource, . } . . impl ScopeTree { 280,836 ( 0.01%) pub fn record_scope_parent(&mut self, child: Scope, parent: Option<(Scope, ScopeDepth)>) { . debug!("{:?}.parent = {:?}", child, parent); . 93,612 ( 0.00%) if let Some(p) = parent { . let prev = self.parent_map.insert(child, p); 46,673 ( 0.00%) assert!(prev.is_none()); . } . . // Record the destruction scopes for later so we can query them. 93,612 ( 0.00%) if let ScopeData::Destruction = child.data { . self.destruction_scopes.insert(child.item_local_id(), child); . } 184,596 ( 0.00%) } . 78,946 ( 0.00%) pub fn opt_destruction_scope(&self, n: hir::ItemLocalId) -> Option { . self.destruction_scopes.get(&n).cloned() 78,946 ( 0.00%) } . . pub fn record_var_scope(&mut self, var: hir::ItemLocalId, lifetime: Scope) { . debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime); 234 ( 0.00%) assert!(var != lifetime.item_local_id()); . self.var_map.insert(var, lifetime); . } . . pub fn record_rvalue_scope(&mut self, var: hir::ItemLocalId, lifetime: Option) { . debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime); 36 ( 0.00%) if let Some(lifetime) = lifetime { . assert!(var != lifetime.item_local_id()); . } . self.rvalue_scopes.insert(var, lifetime); . } . . /// Returns the narrowest scope that encloses `id`, if any. . pub fn opt_encl_scope(&self, id: Scope) -> Option { . self.parent_map.get(&id).cloned().map(|(p, _)| p) . } . . /// Returns the lifetime of the local variable `var_id` 672 ( 0.00%) pub fn var_scope(&self, var_id: hir::ItemLocalId) -> Scope { . self.var_map . .get(&var_id) . .cloned() . .unwrap_or_else(|| bug!("no enclosing scope for id {:?}", var_id)) 672 ( 0.00%) } . . /// Returns the scope when the temp created by `expr_id` will be cleaned up. 547,596 ( 0.01%) pub fn temporary_scope(&self, expr_id: hir::ItemLocalId) -> Option { . // Check for a designated rvalue scope. 60 ( 0.00%) if let Some(&s) = self.rvalue_scopes.get(&expr_id) { . debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s); . return s; . } . . // Otherwise, locate the innermost terminating scope . // if there's one. Static items, for instance, won't . // have an enclosing scope, hence no scope will be . // returned. 78,208 ( 0.00%) let mut id = Scope { id: expr_id, data: ScopeData::Node }; . 2,192,571 ( 0.04%) while let Some(&(p, _)) = self.parent_map.get(&id) { 726,245 ( 0.01%) match p.data { . ScopeData::Destruction => { . debug!("temporary_scope({:?}) = {:?} [enclosing]", expr_id, id); . return Some(id); . } 246,189 ( 0.00%) _ => id = p, . } . } . . debug!("temporary_scope({:?}) = None", expr_id); . None 625,824 ( 0.01%) } . . /// Returns `true` if `subscope` is equal to or is lexically nested inside `superscope`, and . /// `false` otherwise. . /// . /// Used by clippy. . pub fn is_subscope_of(&self, subscope: Scope, superscope: Scope) -> bool { . let mut s = subscope; . debug!("is_subscope_of({:?}, {:?})", subscope, superscope); -- line 408 ---------------------------------------- 1,531,689 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs -------------------------------------------------------------------------------- Ir -- line 111 ---------------------------------------- . const EMPTY: u8 = 0b1111_1111; . . /// Control byte value for a deleted bucket. . const DELETED: u8 = 0b1000_0000; . . /// Checks whether a control byte represents a full bucket (top bit is clear). . #[inline] . fn is_full(ctrl: u8) -> bool { 2,262,229 ( 0.05%) 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)); 79,227 ( 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::()); 50,088,209 ( 1.02%) 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" . ); . 408,432 ( 0.01%) self.stride += Group::WIDTH; 408,432 ( 0.01%) self.pos += self.stride; 375,109 ( 0.01%) self.pos &= bucket_mask; . } . } . . /// Returns the number of buckets needed to hold the given number of items, . /// taking the maximum load factor into account. . /// . /// Returns `None` if an overflow occurs. . // Workaround for emscripten bug emscripten-core/emscripten-fastcomp#258 . #[cfg_attr(target_os = "emscripten", inline(never))] . #[cfg_attr(not(target_os = "emscripten"), inline)] . fn capacity_to_buckets(cap: usize) -> Option { . debug_assert_ne!(cap, 0); . . // For small tables we require at least 1 empty bucket so that lookups are . // guaranteed to terminate if an element doesn't exist in the table. 101,372 ( 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. 231,825 ( 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. 25,926 ( 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 { 269,016 ( 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. 32,045 ( 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 = 182,380 ( 0.00%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 254,582 ( 0.01%) let len = ctrl_offset.checked_add(buckets + Group::WIDTH)?; . . Some(( . unsafe { Layout::from_size_align_unchecked(len, ctrl_align) }, . ctrl_offset, . )) . } . } . -- line 263 ---------------------------------------- -- line 337 ---------------------------------------- . } . } . #[cfg_attr(feature = "inline-more", inline)] . pub unsafe fn drop(&self) { . self.as_ptr().drop_in_place(); . } . #[inline] . pub unsafe fn read(&self) -> T { 35,284 ( 0.00%) self.as_ptr().read() . } . #[inline] . pub unsafe fn write(&self, val: T) { . self.as_ptr().write(val); . } . #[inline] . pub unsafe fn as_ref<'a>(&self) -> &'a T { . &*self.as_ptr() -- line 353 ---------------------------------------- -- line 422 ---------------------------------------- . /// Creates a new empty hash table without allocating any memory, using the . /// given allocator. . /// . /// In effect this returns a table with exactly 1 bucket. However we can . /// leave the data pointer dangling since that bucket is never written to . /// due to our load factor forcing us to always have at least 1 free bucket. . #[inline] . pub fn new_in(alloc: A) -> Self { 102 ( 0.00%) Self { . table: RawTableInner::new_in(alloc), . marker: PhantomData, . } . } . . /// Allocates a new hash table with the given number of buckets. . /// . /// The control bytes are left uninitialized. -- line 438 ---------------------------------------- -- line 440 ---------------------------------------- . unsafe fn new_uninitialized( . alloc: A, . buckets: usize, . fallibility: Fallibility, . ) -> Result { . debug_assert!(buckets.is_power_of_two()); . . Ok(Self { 85 ( 0.00%) table: RawTableInner::new_uninitialized( . alloc, . TableLayout::new::(), . buckets, . fallibility, . )?, . marker: PhantomData, . }) . } -- line 456 ---------------------------------------- -- line 458 ---------------------------------------- . /// Attempts to allocate a new hash table with at least enough capacity . /// for inserting the given number of elements without reallocating. . fn fallible_with_capacity( . alloc: A, . capacity: usize, . fallibility: Fallibility, . ) -> Result { . Ok(Self { 12,421 ( 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")] 4,506 ( 0.00%) pub unsafe fn erase_no_drop(&mut self, item: &Bucket) { 4,506 ( 0.00%) let index = self.bucket_index(item); . self.table.erase(index); 9,012 ( 0.00%) } . . /// Erases an element from the table, dropping it in place. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::needless_pass_by_value)] . #[allow(deprecated)] . pub unsafe fn erase(&mut self, item: Bucket) { . // Erase the element from the table first since drop might panic. 2,764 ( 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 { 6,248 ( 0.00%) self.erase_no_drop(&item); 14 ( 0.00%) item.read() . } . . /// Finds and removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] 766,888 ( 0.02%) pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option { . // Avoid `Option::map` because it bloats LLVM IR. 36,244 ( 0.00%) match self.find(hash, eq) { 19,718 ( 0.00%) Some(bucket) => Some(unsafe { self.remove(bucket) }), 327,929 ( 0.01%) None => None, . } 1,196,941 ( 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) { 26,910 ( 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) { 233,317 ( 0.00%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 147,757 ( 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)] 407,375 ( 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 . }, . ) . } 343,472 ( 0.01%) } . . /// Allocates a new table of a different size and moves the contents of the . /// current table into it. . fn resize( . &mut self, . capacity: usize, . hasher: impl Fn(&T) -> u64, . fallibility: Fallibility, -- line 706 ---------------------------------------- -- line 714 ---------------------------------------- . ) . } . } . . /// Inserts a new element into the table, and returns its raw bucket. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 2,641,486 ( 0.05%) pub fn insert(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> Bucket { . unsafe { . let mut index = self.table.find_insert_slot(hash); . . // We can avoid growing the table once we have reached our load . // factor if we are replacing a tombstone. This works since the . // number of EMPTY slots does not change in this case. 1,661 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 2,279,001 ( 0.05%) if unlikely(self.table.growth_left == 0 && special_is_empty(old_ctrl)) { . self.reserve(1, hasher); . index = self.table.find_insert_slot(hash); . } . . self.table.record_item_insert_at(index, old_ctrl, hash); . . let bucket = self.bucket(index); 2 ( 0.00%) bucket.write(value); . bucket . } 1,965,527 ( 0.04%) } . . /// Attempts to insert a new element without growing the table and return its raw bucket. . /// . /// Returns an `Err` containing the given element if inserting it would require growing the . /// table. . /// . /// This does not check if the given element already exists in the table. . #[cfg(feature = "raw")] -- line 749 ---------------------------------------- -- line 760 ---------------------------------------- . } . } . } . . /// Inserts a new element into the table, and returns a mutable reference to it. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 397,944 ( 0.01%) pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T { 120 ( 0.00%) unsafe { self.insert(hash, value, hasher).as_mut() } 298,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"))] 868 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 236,756 ( 0.00%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 7,421 ( 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. 482,614 ( 0.01%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 374,206 ( 0.01%) self.table.items += 1; . bucket 1,635 ( 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] 37,171 ( 0.00%) pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { 102,105 ( 0.00%) let result = self.table.find_inner(hash, &mut |index| unsafe { 81,617 ( 0.00%) eq(self.bucket(index).as_ref()) 73,092 ( 0.00%) }); . . // Avoid `Option::map` because it bloats LLVM IR. . match result { 18,092 ( 0.00%) Some(index) => Some(unsafe { self.bucket(index) }), . None => None, . } 42,424 ( 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. 46,673 ( 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] 2,590 ( 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. 18,465 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_mut() }), . None => None, . } 2,960 ( 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 { 2,201,153 ( 0.04%) self.len() == 0 . } . . /// Returns the number of buckets in the table. . #[inline] . pub fn buckets(&self) -> usize { . self.table.bucket_mask + 1 . } . . /// Returns an iterator over every element in the table. It is up to . /// the caller to ensure that the `RawTable` outlives the `RawIter`. . /// Because we cannot make the `next` method unsafe on the `RawIter` . /// struct, we have to make the `iter` method unsafe. . #[inline] . pub unsafe fn iter(&self) -> RawIter { 7 ( 0.00%) let data = Bucket::from_base_index(self.data_end(), 0); . RawIter { . iter: RawIterRange::new(self.table.ctrl.as_ptr(), data, self.table.buckets()), 234,732 ( 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(); 1,760 ( 0.00%) let allocation = self.into_allocation(); 1,320 ( 0.00%) RawIntoIter { 2,200 ( 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)> { 635 ( 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(( 161 ( 0.00%) unsafe { NonNull::new_unchecked(self.table.ctrl.as_ptr().sub(ctrl_offset)) }, . layout, . )) . }; . mem::forget(self); . alloc . } . } . -- line 1033 ---------------------------------------- -- line 1042 ---------------------------------------- . T: Sync, . A: Sync, . { . } . . impl RawTableInner { . #[inline] . const fn new_in(alloc: A) -> Self { 1,169,022 ( 0.02%) Self { . // Be careful to cast the entire slice to a raw pointer. . ctrl: unsafe { NonNull::new_unchecked(Group::static_empty() as *const _ as *mut u8) }, . bucket_mask: 0, . items: 0, . growth_left: 0, . alloc, . } . } . } . . impl RawTableInner { . #[cfg_attr(feature = "inline-more", inline)] 318,454 ( 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()); . } . 95,696 ( 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)); 175,872 ( 0.00%) Ok(Self { . ctrl, 80,015 ( 0.00%) bucket_mask: buckets - 1, . items: 0, . growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 231,844 ( 0.00%) } . . #[inline] 28,915 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 7,270 ( 0.00%) if capacity == 0 { 6,450 ( 0.00%) Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = . capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 144,934 ( 0.00%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; . result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 14,005 ( 0.00%) Ok(result) . } . } 28,915 ( 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] 78,436 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { . let index = self.find_insert_slot(hash); 78,436 ( 0.00%) let old_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . (index, old_ctrl) 156,872 ( 0.00%) } . . /// Searches for an empty or deleted bucket which is suitable for inserting . /// a new element. . /// . /// There must be at least 1 empty bucket in the table. . #[inline] . fn find_insert_slot(&self, hash: u64) -> usize { . let mut probe_seq = self.probe_seq(hash); . loop { . unsafe { . let group = Group::load(self.ctrl(probe_seq.pos)); 1,417,423 ( 0.03%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 4,158,434 ( 0.08%) let result = (probe_seq.pos + bit) & self.bucket_mask; . . // In tables smaller than the group width, trailing control . // bytes outside the range of the table are filled with . // EMPTY entries. These will unfortunately trigger a . // match, but once masked may point to a full bucket that . // is already occupied. We detect this situation here and . // perform a second scan starting at the beginning of the . // table. This second scan is guaranteed to find an empty . // slot (due to the load factor) before hitting the trailing . // control bytes (containing EMPTY). 1,947,034 ( 0.04%) 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); . 45,064 ( 0.00%) loop { . let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 6,854,353 ( 0.14%) for bit in group.match_byte(h2_hash) { 13,994,748 ( 0.28%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 9,891,539 ( 0.20%) if likely(eq(index)) { . return Some(index); . } . } . 1,784,034 ( 0.04%) if likely(group.match_empty().any_bit_set()) { . return None; . } . . probe_seq.move_next(self.bucket_mask); . } . } . . #[allow(clippy::mut_mut)] -- line 1198 ---------------------------------------- -- line 1225 ---------------------------------------- . Bucket::from_base_index(self.data_end(), index) . } . . #[inline] . unsafe fn bucket_ptr(&self, index: usize, size_of: usize) -> *mut u8 { . debug_assert_ne!(self.bucket_mask, 0); . debug_assert!(index < self.buckets()); . let base: *mut u8 = self.data_end().as_ptr(); 5,824,568 ( 0.12%) 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 { 34,457,287 ( 0.70%) pos: h1(hash) & self.bucket_mask, . stride: 0, . } . } . . /// Returns the index of a bucket for which a value must be inserted if there is enough rooom . /// in the table, otherwise returns error . #[cfg(feature = "raw")] . #[inline] -- line 1257 ---------------------------------------- -- line 1263 ---------------------------------------- . } else { . self.record_item_insert_at(index, old_ctrl, hash); . Ok(index) . } . } . . #[inline] . unsafe fn record_item_insert_at(&mut self, index: usize, old_ctrl: u8, hash: u64) { 2,806,983 ( 0.06%) self.growth_left -= special_is_empty(old_ctrl) as usize; . self.set_ctrl_h2(index, hash); 2,243,868 ( 0.05%) self.items += 1; . } . . #[inline] . fn is_in_same_group(&self, i: usize, new_i: usize, hash: u64) -> bool { . let probe_seq_pos = self.probe_seq(hash).pos; . let probe_index = . |pos: usize| (pos.wrapping_sub(probe_seq_pos) & self.bucket_mask) / Group::WIDTH; . probe_index(i) == probe_index(new_i) -- line 1281 ---------------------------------------- -- line 1312 ---------------------------------------- . // replicate the buckets at the end of the trailing group. For example . // with 2 buckets and a group size of 4, the control bytes will look . // like this: . // . // Real | Replicated . // --------------------------------------------- . // | [A] | [B] | [EMPTY] | [EMPTY] | [A] | [B] | . // --------------------------------------------- 4,106,959 ( 0.08%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 1,368,265 ( 0.03%) *self.ctrl(index) = ctrl; 1,368,410 ( 0.03%) *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 { 451,338 ( 0.01%) self.bucket_mask + 1 . } . . #[inline] . fn num_ctrl_bytes(&self) -> usize { 158,018 ( 0.00%) self.bucket_mask + 1 + Group::WIDTH . } . . #[inline] . fn is_empty_singleton(&self) -> bool { 1,914,651 ( 0.04%) self.bucket_mask == 0 . } . . #[allow(clippy::mut_mut)] . #[inline] . unsafe fn prepare_resize( . &self, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result, TryReserveError> { . debug_assert!(self.items <= capacity); . . // Allocate and initialize the new table. 1,548 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( . self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 113,301 ( 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_| { 48,867 ( 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. 97,738 ( 0.00%) let new_items = match self.items.checked_add(additional) { . Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 97,734 ( 0.00%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 205,112 ( 0.00%) if new_items <= full_capacity / 2 { . // Rehash in-place without re-allocating if we have plenty of spare . // capacity that is locked up due to DELETED entries. . self.rehash_in_place(hasher, layout.size, drop); . Ok(()) . } else { . // Otherwise, conservatively resize to at least the next size up . // to avoid churning deletes into frequent rehashes. . self.resize_inner( 48,867 ( 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> { 3,854 ( 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() { 876,162 ( 0.02%) if !is_full(*self.ctrl(i)) { . continue; . } . . // This may panic. . let hash = hasher(self, i); . . // We can use a simpler version of insert() here since: . // - there are no DELETED entries. -- line 1444 ---------------------------------------- -- line 1454 ---------------------------------------- . } . . // We successfully copied all elements without panicking. Now replace . // self with the new table. The old table will have its memory freed but . // the items will not be dropped (since they have been moved into the . // new table). . mem::swap(self, &mut new_table); . 48,867 ( 0.00%) Ok(()) . } . . /// Rehashes the contents of the table in place (i.e. without changing the . /// allocation). . /// . /// If `hasher` panics then some the table's contents may be lost. . /// . /// This uses dynamic dispatch to reduce the amount of -- line 1470 ---------------------------------------- -- line 1554 ---------------------------------------- . #[inline] . unsafe fn free_buckets(&mut self, table_layout: TableLayout) { . // Avoid `Option::unwrap_or_else` because it bloats LLVM IR. . let (layout, ctrl_offset) = match table_layout.calculate_layout_for(self.buckets()) { . Some(lco) => lco, . None => hint::unreachable_unchecked(), . }; . self.alloc.deallocate( 38,269 ( 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) { 2,376 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 2,820 ( 0.00%) self.items = 0; 2,435 ( 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))); 104,621 ( 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. 418,484 ( 0.01%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 521,735 ( 0.01%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 418,484 ( 0.01%) self.items -= 1; . } . } . . impl Clone for RawTable { 288 ( 0.00%) fn clone(&self) -> Self { 56 ( 0.00%) if self.table.is_empty_singleton() { . Self::new_in(self.table.alloc.clone()) . } else { . unsafe { . let mut new_table = ManuallyDrop::new( . // Avoid `Result::ok_or_else` because it bloats LLVM IR. . match Self::new_uninitialized( . self.table.alloc.clone(), . self.table.buckets(), -- line 1615 ---------------------------------------- -- line 1624 ---------------------------------------- . // We need to free the memory allocated for the new table. . new_table.free_buckets(); . }); . . // Return the newly created table. . ManuallyDrop::into_inner(new_table) . } . } 324 ( 0.00%) } . . fn clone_from(&mut self, source: &Self) { . if source.table.is_empty_singleton() { . *self = Self::new_in(self.table.alloc.clone()); . } else { . unsafe { . // First, drop all our elements without clearing the control bytes. . self.drop_elements(); -- line 1640 ---------------------------------------- -- line 1687 ---------------------------------------- . .table . .ctrl(0) . .copy_to_nonoverlapping(self.table.ctrl(0), self.table.num_ctrl_bytes()); . source . .data_start() . .copy_to_nonoverlapping(self.data_start(), self.table.buckets()); . . self.table.items = source.table.items; 34 ( 0.00%) self.table.growth_left = source.table.growth_left; . } . } . . impl RawTable { . /// Common code for clone and clone_from. Assumes `self.buckets() == source.buckets()`. . #[cfg_attr(feature = "inline-more", inline)] . unsafe fn clone_from_impl(&mut self, source: &Self, mut on_panic: impl FnMut(&mut Self)) { . // Copy the control bytes unchanged. We do this in a single pass -- line 1703 ---------------------------------------- -- line 1790 ---------------------------------------- . fn default() -> Self { . Self::new_in(Default::default()) . } . } . . #[cfg(feature = "nightly")] . unsafe impl<#[may_dangle] T, A: Allocator + Clone> Drop for RawTable { . #[cfg_attr(feature = "inline-more", inline)] 772,712 ( 0.02%) fn drop(&mut self) { 837,357 ( 0.02%) if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); . self.free_buckets(); . } . } 823,106 ( 0.02%) } . } . #[cfg(not(feature = "nightly"))] . impl Drop for RawTable { . #[cfg_attr(feature = "inline-more", inline)] . fn drop(&mut self) { . if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); -- line 1813 ---------------------------------------- -- line 1817 ---------------------------------------- . } . } . . impl IntoIterator for RawTable { . type Item = T; . type IntoIter = RawIntoIter; . . #[cfg_attr(feature = "inline-more", inline)] 1,760 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 2,200 ( 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 { 394,114 ( 0.01%) if let Some(index) = self.current_group.lowest_set_bit() { 87,280 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 152,187 ( 0.00%) return Some(self.data.next_n(index)); . } . 337,297 ( 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). 10,799 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); 19,718 ( 0.00%) self.data = self.data.next_n(Group::WIDTH); 12,591 ( 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) { 429 ( 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)] 88,376 ( 0.00%) fn next(&mut self) -> Option> { 185,198 ( 0.00%) if let Some(b) = self.iter.next() { 564,479 ( 0.01%) self.items -= 1; . Some(b) . } else { . // We don't check against items == 0 here to allow the . // compiler to optimize away the item count entirely if the . // iterator length is never queried. . debug_assert_eq!(self.items, 0); . None . } 176,752 ( 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)] 900 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 2,869 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 262 ( 0.00%) } . } . #[cfg(not(feature = "nightly"))] . impl Drop for RawIntoIter { . #[cfg_attr(feature = "inline-more", inline)] . fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); -- line 2203 ---------------------------------------- -- line 2209 ---------------------------------------- . } . } . } . . impl Iterator for RawIntoIter { . type Item = T; . . #[cfg_attr(feature = "inline-more", inline)] 1,230 ( 0.00%) fn next(&mut self) -> Option { 87 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 3,522 ( 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)] 40 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements. Note that this may panic. . self.iter.drop_elements(); . . // Reset the contents of the table now that all elements have been . // dropped. . self.table.clear_no_drop(); . . // Move the now empty table back to its original location. 5 ( 0.00%) self.orig_table . .as_ptr() . .copy_from_nonoverlapping(&*self.table, 1); . } 40 ( 0.00%) } . } . . impl Iterator for RawDrain<'_, T, A> { . type Item = T; . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option { . unsafe { -- line 2289 ---------------------------------------- 17,869,991 ( 0.36%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs -------------------------------------------------------------------------------- Ir -- line 36 ---------------------------------------- . use rustc_session::parse::ParseSess; . use rustc_span::source_map::{MultiSpan, Span, DUMMY_SP}; . use rustc_span::symbol::{kw, sym, Ident, Symbol}; . use tracing::debug; . . use std::ops::Range; . use std::{cmp, mem, slice}; . 125,865 ( 0.00%) bitflags::bitflags! { . struct Restrictions: u8 { . const STMT_EXPR = 1 << 0; . const NO_STRUCT_LITERAL = 1 << 1; . const CONST_EXPR = 1 << 2; . } . } . . #[derive(Clone, Copy, PartialEq, Debug)] -- line 52 ---------------------------------------- -- line 104 ---------------------------------------- . $self.bump(); . return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty); . } . } . } . }; . } . 2,197 ( 0.00%) #[derive(Clone)] . pub struct Parser<'a> { 55 ( 0.00%) pub sess: &'a ParseSess, . /// The current token. 34 ( 0.00%) pub token: Token, . /// The spacing for the current token 34 ( 0.00%) pub token_spacing: Spacing, . /// The previous token. 51 ( 0.00%) pub prev_token: Token, 51 ( 0.00%) pub capture_cfg: bool, 119 ( 0.00%) restrictions: Restrictions, 68 ( 0.00%) expected_tokens: Vec, . // Important: This must only be advanced from `next_tok` . // to ensure that `token_cursor.num_next_calls` is updated properly . token_cursor: TokenCursor, 68 ( 0.00%) desugar_doc_comments: bool, . /// This field is used to keep track of how many left angle brackets we have seen. This is . /// required in order to detect extra leading left angle brackets (`<` characters) and error . /// appropriately. . /// . /// See the comments in the `parse_path_segment` function for more details. 68 ( 0.00%) unmatched_angle_bracket_count: u32, 102 ( 0.00%) max_angle_bracket_count: u32, . /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery . /// it gets removed from here. Every entry left at the end gets emitted as an independent . /// error. 34 ( 0.00%) pub(super) unclosed_delims: Vec, . last_unexpected_token_span: Option, . /// Span pointing at the `:` for the last type ascription the parser has seen, and whether it . /// looked like it could have been a mistyped path or literal `Option:Some(42)`). . pub last_type_ascription: Option<(Span, bool /* likely path typo */)>, . /// If present, this `Parser` is not parsing Rust code but rather a macro call. . subparser_name: Option<&'static str>, . capture_state: CaptureState, . /// This allows us to recover when the user forget to add braces around -- line 146 ---------------------------------------- -- line 173 ---------------------------------------- . /// the first macro inner attribute to invoke a proc-macro). . /// When create a `TokenStream`, the inner attributes get inserted . /// into the proper place in the token stream. . pub type ReplaceRange = (Range, Vec<(FlatToken, Spacing)>); . . /// Controls how we capture tokens. Capturing can be expensive, . /// so we try to avoid performing capturing in cases where . /// we will never need an `AttrAnnotatedTokenStream` 34 ( 0.00%) #[derive(Copy, Clone)] . pub enum Capturing { . /// We aren't performing any capturing - this is the default mode. . No, . /// We are capturing tokens . Yes, . } . 140 ( 0.00%) #[derive(Clone)] . struct CaptureState { 136 ( 0.00%) capturing: Capturing, 34 ( 0.00%) replace_ranges: Vec, . inner_attr_ranges: FxHashMap, . } . . impl<'a> Drop for Parser<'a> { . fn drop(&mut self) { 257 ( 0.00%) emit_unclosed_delims(&mut self.unclosed_delims, &self.sess); . } . } . 9,413 ( 0.00%) #[derive(Clone)] . struct TokenCursor { . frame: TokenCursorFrame, 2,240 ( 0.00%) stack: Vec, . desugar_doc_comments: bool, . // Counts the number of calls to `next` or `next_desugared`, . // depending on whether `desugar_doc_comments` is set. 681 ( 0.00%) num_next_calls: usize, . // During parsing, we may sometimes need to 'unglue' a . // glued token into two component tokens . // (e.g. '>>' into '>' and '>), so that the parser . // can consume them one at a time. This process . // bypasses the normal capturing mechanism . // (e.g. `num_next_calls` will not be incremented), . // since the 'unglued' tokens due not exist in . // the original `TokenStream`. -- line 217 ---------------------------------------- -- line 226 ---------------------------------------- . // in `Option>` requires us to unglue . // the trailing `>>` token. The `break_last_token` . // field is used to track this token - it gets . // appended to the captured stream when . // we evaluate a `LazyTokenStream` . break_last_token: bool, . } . 4,325 ( 0.00%) #[derive(Clone)] . struct TokenCursorFrame { 1,820 ( 0.00%) delim: token::DelimToken, . span: DelimSpan, . open_delim: bool, 3,640 ( 0.00%) tree_cursor: tokenstream::Cursor, . close_delim: bool, . } . . impl TokenCursorFrame { . fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self { 200 ( 0.00%) TokenCursorFrame { . delim, . span, . open_delim: false, 14,331 ( 0.00%) tree_cursor: tts.into_trees(), . close_delim: false, . } . } . } . . impl TokenCursor { 1,518,612 ( 0.03%) fn next(&mut self) -> (Token, Spacing) { . loop { 732,450 ( 0.01%) let (tree, spacing) = if !self.frame.open_delim { 14,251 ( 0.00%) self.frame.open_delim = true; 71,255 ( 0.00%) TokenTree::open_tt(self.frame.span, self.frame.delim).into() 1,489,843 ( 0.03%) } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() { . tree 56,974 ( 0.00%) } else if !self.frame.close_delim { 14,220 ( 0.00%) self.frame.close_delim = true; 71,100 ( 0.00%) TokenTree::close_tt(self.frame.span, self.frame.delim).into() 28,440 ( 0.00%) } else if let Some(frame) = self.stack.pop() { 184,860 ( 0.00%) self.frame = frame; . continue; . } else { 846 ( 0.00%) (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone) . }; . 281,604 ( 0.01%) match tree { . TokenTree::Token(token) => { 1,012,408 ( 0.02%) return (token, spacing); . } . TokenTree::Delimited(sp, delim, tts) => { . let frame = TokenCursorFrame::new(sp, delim, tts); . self.stack.push(mem::replace(&mut self.frame, frame)); . } . } . } 1,012,408 ( 0.02%) } . 3,550 ( 0.00%) fn next_desugared(&mut self) -> (Token, Spacing) { 1,065 ( 0.00%) let (data, attr_style, sp) = match self.next() { . (Token { kind: token::DocComment(_, attr_style, data), span }, _) => { . (data, attr_style, span) . } 1,775 ( 0.00%) tok => return tok, . }; . . // Searches for the occurrences of `"#*` and returns the minimum number of `#`s . // required to wrap the text. . let mut num_of_hashes = 0; . let mut count = 0; . for ch in data.as_str().chars() { . count = match ch { -- line 298 ---------------------------------------- -- line 332 ---------------------------------------- . .iter() . .cloned() . .collect::() . }, . ), . )); . . self.next() 3,195 ( 0.00%) } . } . 2,160 ( 0.00%) #[derive(Debug, Clone, PartialEq)] . enum TokenType { 1,728 ( 0.00%) Token(TokenKind), . Keyword(Symbol), . Operator, . Lifetime, . Ident, . Path, . Type, . Const, . } -- line 353 ---------------------------------------- -- line 378 ---------------------------------------- . /// The separator token. . sep: Option, . /// `true` if a trailing separator is allowed. . trailing_sep_allowed: bool, . } . . impl SeqSep { . fn trailing_allowed(t: TokenKind) -> SeqSep { 33 ( 0.00%) SeqSep { sep: Some(t), trailing_sep_allowed: true } . } . . fn none() -> SeqSep { . SeqSep { sep: None, trailing_sep_allowed: false } . } . } . . pub enum FollowedByType { . Yes, . No, . } . . fn token_descr_opt(token: &Token) -> Option<&'static str> { 38 ( 0.00%) Some(match token.kind { 76 ( 0.00%) _ if token.is_special_ident() => "reserved identifier", 76 ( 0.00%) _ if token.is_used_keyword() => "keyword", 76 ( 0.00%) _ if token.is_unused_keyword() => "reserved keyword", . token::DocComment(..) => "doc comment", . _ => return None, . }) . } . 133 ( 0.00%) pub(super) fn token_descr(token: &Token) -> String { 38 ( 0.00%) let token_str = pprust::token_to_string(token); . match token_descr_opt(token) { . Some(prefix) => format!("{} `{}`", prefix, token_str), 133 ( 0.00%) _ => format!("`{}`", token_str), . } 95 ( 0.00%) } . . impl<'a> Parser<'a> { 560 ( 0.00%) pub fn new( . sess: &'a ParseSess, . tokens: TokenStream, . desugar_doc_comments: bool, . subparser_name: Option<&'static str>, . ) -> Self { 40 ( 0.00%) let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens); 80 ( 0.00%) start_frame.open_delim = true; . start_frame.close_delim = true; . 1,240 ( 0.00%) let mut parser = Parser { . sess, 40 ( 0.00%) token: Token::dummy(), . token_spacing: Spacing::Alone, 40 ( 0.00%) prev_token: Token::dummy(), . capture_cfg: false, . restrictions: Restrictions::empty(), . expected_tokens: Vec::new(), . token_cursor: TokenCursor { 240 ( 0.00%) frame: start_frame, . stack: Vec::new(), . num_next_calls: 0, . desugar_doc_comments, . break_last_token: false, . }, . desugar_doc_comments, . unmatched_angle_bracket_count: 0, . max_angle_bracket_count: 0, -- line 445 ---------------------------------------- -- line 451 ---------------------------------------- . capturing: Capturing::No, . replace_ranges: Vec::new(), . inner_attr_ranges: Default::default(), . }, . current_closure: None, . }; . . // Make parser point to the first token. 80 ( 0.00%) parser.bump(); . . parser 360 ( 0.00%) } . . fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) { . loop { 758,148 ( 0.02%) let (mut next, spacing) = if self.desugar_doc_comments { 1,420 ( 0.00%) self.token_cursor.next_desugared() . } else { 378,009 ( 0.01%) self.token_cursor.next() . }; 505,432 ( 0.01%) self.token_cursor.num_next_calls += 1; . // We've retrieved an token from the underlying . // cursor, so we no longer need to worry about . // an unglued token. See `break_and_eat` for more details 126,358 ( 0.00%) self.token_cursor.break_last_token = false; 505,432 ( 0.01%) if next.span.is_dummy() { . // Tweak the location for better diagnostics, but keep syntactic context intact. 172 ( 0.00%) next.span = fallback_span.with_ctxt(next.span.ctxt()); . } 421,734 ( 0.01%) if matches!( 252,716 ( 0.01%) next.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 505,432 ( 0.01%) return (next, spacing); . } . } . . pub fn unexpected(&mut self) -> PResult<'a, T> { . match self.expect_one_of(&[], &[]) { . Err(e) => Err(e), . // We can get `Ok(true)` from `recover_closing_delimiter` . // which is called in `expected_one_of_not_found`. . Ok(_) => FatalError.raise(), . } . } . . /// Expects and consumes the token `t`. Signals an error if the next token is not `t`. 286,992 ( 0.01%) pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { 31,888 ( 0.00%) if self.expected_tokens.is_empty() { 396 ( 0.00%) if self.token == *t { 330 ( 0.00%) self.bump(); . Ok(false) . } else { . self.unexpected_try_recover(t) . } . } else { 381,864 ( 0.01%) self.expect_one_of(slice::from_ref(t), &[]) . } 478,320 ( 0.01%) } . . /// Expect next token to be edible or inedible token. If edible, . /// then consume it; if inedible, then return without consuming . /// anything. Signal a fatal error if next token is unexpected. 594,408 ( 0.01%) pub fn expect_one_of( . &mut self, . edible: &[TokenKind], . inedible: &[TokenKind], . ) -> PResult<'a, bool /* recovered */> { 99,068 ( 0.00%) if edible.contains(&self.token.kind) { 130,575 ( 0.00%) self.bump(); . Ok(false) . } else if inedible.contains(&self.token.kind) { . // leave it in the input . Ok(false) . } else if self.last_unexpected_token_span == Some(self.token.span) { . FatalError.raise(); . } else { . self.expected_one_of_not_found(edible, inedible) . } 743,010 ( 0.02%) } . . // Public for rustfmt usage. . pub fn parse_ident(&mut self) -> PResult<'a, Ident> { 61,121 ( 0.00%) self.parse_ident_common(true) . } . . fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> { 98,430 ( 0.00%) self.token.ident().ok_or_else(|| match self.prev_token.kind { . TokenKind::DocComment(..) => { . self.span_err(self.prev_token.span, Error::UselessDocComment) . } . _ => self.expected_ident_found(), . }) . } . 229,383 ( 0.00%) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { 32,769 ( 0.00%) let (ident, is_raw) = self.ident_or_err()?; 196,614 ( 0.00%) if !is_raw && ident.is_reserved() { . let mut err = self.expected_ident_found(); . if recover { . err.emit(); . } else { . return Err(err); . } . } 131,076 ( 0.00%) self.bump(); . Ok(ident) 327,690 ( 0.01%) } . . /// Checks if the next token is `tok`, and returns `true` if so. . /// . /// This method will automatically add `tok` to `expected_tokens` if `tok` is not . /// encountered. 2,635,654 ( 0.05%) fn check(&mut self, tok: &TokenKind) -> bool { 1,142,304 ( 0.02%) let is_present = self.token == *tok; 777,546 ( 0.02%) if !is_present { 1,808,862 ( 0.04%) self.expected_tokens.push(TokenType::Token(tok.clone())); . } . is_present 2,635,654 ( 0.05%) } . . /// Consumes a token 'tok' if it exists. Returns whether the given token was present. 4 ( 0.00%) pub fn eat(&mut self, tok: &TokenKind) -> bool { 470,775 ( 0.01%) let is_present = self.check(tok); 324,685 ( 0.01%) if is_present { 18,828 ( 0.00%) self.bump() . } . is_present 5 ( 0.00%) } . . /// If the next token is the given keyword, returns `true` without eating it. . /// An expectation is also added for diagnostics purposes. 8,045 ( 0.00%) fn check_keyword(&mut self, kw: Symbol) -> bool { 1,224 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw)); 44,023 ( 0.00%) self.token.is_keyword(kw) . } . . /// If the next token is the given keyword, eats it and returns `true`. . /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes. . // Public for rustfmt usage. 16,355 ( 0.00%) pub fn eat_keyword(&mut self, kw: Symbol) -> bool { 10,362 ( 0.00%) if self.check_keyword(kw) { 974 ( 0.00%) self.bump(); . true . } else { . false . } 16,355 ( 0.00%) } . . fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { 842 ( 0.00%) if self.token.is_keyword(kw) { 197 ( 0.00%) self.bump(); . true . } else { . false . } . } . . /// If the given word is not a keyword, signals an error. . /// If the next token is not the given word, signals an error. . /// Otherwise, eats it. 75 ( 0.00%) fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { . if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } 60 ( 0.00%) } . . /// Is the given keyword `kw` followed by a non-reserved identifier? 8,736 ( 0.00%) fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { 4,368 ( 0.00%) self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) 9,828 ( 0.00%) } . 91,686 ( 0.00%) fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { 31,106 ( 0.00%) if ok { . true . } else { 1,704 ( 0.00%) self.expected_tokens.push(typ); . false . } 91,686 ( 0.00%) } . . fn check_ident(&mut self) -> bool { 2,113 ( 0.00%) self.check_or_expected(self.token.is_ident(), TokenType::Ident) . } . 58,972 ( 0.00%) fn check_path(&mut self) -> bool { 119,000 ( 0.00%) self.check_or_expected(self.token.is_path_start(), TokenType::Path) 73,715 ( 0.00%) } . . fn check_type(&mut self) -> bool { 292 ( 0.00%) self.check_or_expected(self.token.can_begin_type(), TokenType::Type) . } . . fn check_const_arg(&mut self) -> bool { 280 ( 0.00%) self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) . } . 3,123 ( 0.00%) fn check_inline_const(&self, dist: usize) -> bool { 1,735 ( 0.00%) self.is_keyword_ahead(dist, &[kw::Const]) . && self.look_ahead(dist + 1, |t| match t.kind { . token::Interpolated(ref nt) => matches!(**nt, token::NtBlock(..)), . token::OpenDelim(DelimToken::Brace) => true, . _ => false, . }) 3,123 ( 0.00%) } . . /// Checks to see if the next token is either `+` or `+=`. . /// Otherwise returns `false`. . fn check_plus(&mut self) -> bool { 604 ( 0.00%) self.check_or_expected( 302 ( 0.00%) self.token.is_like_plus(), 302 ( 0.00%) TokenType::Token(token::BinOp(token::Plus)), . ) . } . . /// Eats the expected token if it's present possibly breaking . /// compound tokens like multi-character operators in process. . /// Returns `true` if the token was eaten. 177,480 ( 0.00%) fn break_and_eat(&mut self, expected: TokenKind) -> bool { 103,530 ( 0.00%) if self.token.kind == expected { 312 ( 0.00%) self.bump(); . return true; . } 73,170 ( 0.00%) match self.token.kind.break_two_token_op() { 14 ( 0.00%) Some((first, second)) if first == expected => { 8 ( 0.00%) let first_span = self.sess.source_map().start_point(self.token.span); 10 ( 0.00%) let second_span = self.token.span.with_lo(first_span.hi()); 18 ( 0.00%) self.token = Token::new(first, first_span); . // Keep track of this token - if we end token capturing now, . // we'll want to append this token to the captured stream. . // . // If we consume any additional tokens, then this token . // is not needed (we'll capture the entire 'glued' token), . // and `next_tok` will set this field to `None` 2 ( 0.00%) self.token_cursor.break_last_token = true; . // Use the spacing of the glued token as the spacing . // of the unglued second token. 28 ( 0.00%) self.bump_with((Token::new(second, second_span), self.token_spacing)); . true . } . _ => { 43,896 ( 0.00%) self.expected_tokens.push(TokenType::Token(expected)); . false . } . } 191,638 ( 0.00%) } . . /// Eats `+` possibly breaking tokens like `+=` in process. . fn eat_plus(&mut self) -> bool { 8 ( 0.00%) self.break_and_eat(token::BinOp(token::Plus)) . } . . /// Eats `&` possibly breaking tokens like `&&` in process. . /// Signals an error if `&` is not eaten. . fn expect_and(&mut self) -> PResult<'a, ()> { 384 ( 0.00%) if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `|` possibly breaking tokens like `||` in process. . /// Signals an error if `|` was not eaten. . fn expect_or(&mut self) -> PResult<'a, ()> { 66 ( 0.00%) if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `<` possibly breaking tokens like `<<` in process. 518 ( 0.00%) fn eat_lt(&mut self) -> bool { 44,098 ( 0.00%) let ate = self.break_and_eat(token::Lt); 29,376 ( 0.00%) if ate { . // See doc comment for `unmatched_angle_bracket_count`. 164 ( 0.00%) self.unmatched_angle_bracket_count += 1; 173 ( 0.00%) self.max_angle_bracket_count += 1; . debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); . } . ate 518 ( 0.00%) } . . /// Eats `<` possibly breaking tokens like `<<` in process. . /// Signals an error if `<` was not eaten. . fn expect_lt(&mut self) -> PResult<'a, ()> { . if self.eat_lt() { Ok(()) } else { self.unexpected() } . } . . /// Eats `>` possibly breaking tokens like `>>` in process. . /// Signals an error if `>` was not eaten. . fn expect_gt(&mut self) -> PResult<'a, ()> { 246 ( 0.00%) if self.break_and_eat(token::Gt) { . // See doc comment for `unmatched_angle_bracket_count`. 123 ( 0.00%) if self.unmatched_angle_bracket_count > 0 { 82 ( 0.00%) self.unmatched_angle_bracket_count -= 1; . debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count); . } . Ok(()) . } else { . self.unexpected() . } . } . . fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool { . kets.iter().any(|k| match expect { 107,724 ( 0.00%) TokenExpectType::Expect => self.check(k), 165 ( 0.00%) TokenExpectType::NoExpect => self.token == **k, . }) . } . . fn parse_seq_to_before_tokens( . &mut self, . kets: &[&TokenKind], . sep: SeqSep, . expect: TokenExpectType, -- line 759 ---------------------------------------- -- line 761 ---------------------------------------- . ) -> PResult<'a, (Vec, bool /* trailing */, bool /* recovered */)> { . let mut first = true; . let mut recovered = false; . let mut trailing = false; . let mut v = vec![]; . let unclosed_delims = !self.unclosed_delims.is_empty(); . . while !self.expect_any_with_type(kets, expect) { 107,577 ( 0.00%) if let token::CloseDelim(..) | token::Eof = self.token.kind { . break; . } 71,545 ( 0.00%) if let Some(ref t) = sep.sep { 72,157 ( 0.00%) if first { . first = false; . } else { 93,683 ( 0.00%) match self.expect(t) { . Ok(false) => { . self.current_closure.take(); . } . Ok(true) => { . self.current_closure.take(); . recovered = true; . break; . } -- line 784 ---------------------------------------- -- line 857 ---------------------------------------- . e.cancel(); . break; . } . } . } . } . } . } 39,856 ( 0.00%) if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) { . trailing = true; . break; . } . 20,092 ( 0.00%) let t = f(self)?; 366 ( 0.00%) v.push(t); . } . 32,316 ( 0.00%) Ok((v, trailing, recovered)) . } . . fn recover_missing_braces_around_closure_body( . &mut self, . closure_spans: ClosureSpans, . mut expect_err: DiagnosticBuilder<'_>, . ) -> PResult<'a, ()> { . let initial_semicolon = self.token.span; -- line 882 ---------------------------------------- -- line 937 ---------------------------------------- . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. . fn parse_seq_to_before_end( . &mut self, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool, bool)> { 30,375 ( 0.00%) self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f) . } . . /// Parses a sequence, including the closing delimiter. The function . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. 60,230 ( 0.00%) fn parse_seq_to_end( . &mut self, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool /* trailing */)> { 22,167 ( 0.00%) let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; 10,105 ( 0.00%) if !recovered { . self.eat(ket); . } 58,441 ( 0.00%) Ok((val, trailing)) 48,184 ( 0.00%) } . . /// Parses a sequence, including the closing delimiter. The function . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. . fn parse_unspanned_seq( . &mut self, . bra: &TokenKind, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { 18,230 ( 0.00%) self.expect(bra)?; 48,184 ( 0.00%) self.parse_seq_to_end(ket, sep, f) . } . . fn parse_delim_comma_seq( . &mut self, . delim: DelimToken, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { . self.parse_unspanned_seq( 6,122 ( 0.00%) &token::OpenDelim(delim), 6,222 ( 0.00%) &token::CloseDelim(delim), . SeqSep::trailing_allowed(token::Comma), . f, . ) . } . . fn parse_paren_comma_seq( . &mut self, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { . self.parse_delim_comma_seq(token::Paren, f) . } . . /// Advance the parser by one token using provided token as the next one. 1,642,680 ( 0.03%) fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) { . // Bumping after EOF is a bad sign, usually an infinite loop. 758,160 ( 0.02%) if self.prev_token.kind == TokenKind::Eof { . let msg = "attempted to bump the parser past EOF (may be stuck in a loop)"; . self.span_bug(self.token.span, msg); . } . . // Update the current and previous tokens. 505,440 ( 0.01%) self.prev_token = mem::replace(&mut self.token, next_token); 126,360 ( 0.00%) self.token_spacing = next_spacing; . . // Diagnostics. 126,360 ( 0.00%) self.expected_tokens.clear(); . } . . /// Advance the parser by one token. 1,010,864 ( 0.02%) pub fn bump(&mut self) { 505,432 ( 0.01%) let next_token = self.next_tok(self.token.span); 758,148 ( 0.02%) self.bump_with(next_token); 1,010,864 ( 0.02%) } . . /// Look-ahead `dist` tokens of `self.token` and get access to that token there. . /// When `dist == 0` then the current token is looked at. . pub fn look_ahead(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R { 914 ( 0.00%) if dist == 0 { 415 ( 0.00%) return looker(&self.token); . } . 57,244 ( 0.00%) let frame = &self.token_cursor.frame; 86,592 ( 0.00%) if frame.delim != DelimToken::NoDelim { . let all_normal = (0..dist).all(|i| { 247,836 ( 0.01%) let token = frame.tree_cursor.look_ahead(i); 371,234 ( 0.01%) !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _))) . }); . if all_normal { 426,175 ( 0.01%) return match frame.tree_cursor.look_ahead(dist - 1) { 156,681 ( 0.00%) Some(tree) => match tree { 60,646 ( 0.00%) TokenTree::Token(token) => looker(token), . TokenTree::Delimited(dspan, delim, _) => { 124,187 ( 0.00%) looker(&Token::new(token::OpenDelim(*delim), dspan.open)) . } . }, 56,591 ( 0.00%) None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)), . }; . } . } . . let mut cursor = self.token_cursor.clone(); . let mut i = 0; 193 ( 0.00%) let mut token = Token::dummy(); 114 ( 0.00%) while i < dist { 1,399 ( 0.00%) token = cursor.next().0; 653 ( 0.00%) if matches!( 386 ( 0.00%) token.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 60 ( 0.00%) i += 1; . } 4 ( 0.00%) return looker(&token); . } . . /// Returns whether any of the given keywords are `dist` tokens ahead of the current one. 3,888 ( 0.00%) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool { 1,002 ( 0.00%) self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw))) 3,888 ( 0.00%) } . . /// Parses asyncness: `async` or nothing. . fn parse_asyncness(&mut self) -> Async { . if self.eat_keyword(kw::Async) { . let span = self.prev_token.uninterpolated_span(); . Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID } . } else { . Async::No . } . } . . /// Parses unsafety: `unsafe` or nothing. 104 ( 0.00%) fn parse_unsafety(&mut self) -> Unsafe { . if self.eat_keyword(kw::Unsafe) { . Unsafe::Yes(self.prev_token.uninterpolated_span()) . } else { . Unsafe::No . } 416 ( 0.00%) } . . /// Parses constness: `const` or nothing. 1,736 ( 0.00%) fn parse_constness(&mut self) -> Const { . // Avoid const blocks to be parsed as const items 493 ( 0.00%) if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace)) . && self.eat_keyword(kw::Const) . { 10 ( 0.00%) Const::Yes(self.prev_token.uninterpolated_span()) . } else { . Const::No . } 3,038 ( 0.00%) } . . /// Parses inline const expressions. . fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P> { . if pat { . self.sess.gated_spans.gate(sym::inline_const_pat, span); . } else { . self.sess.gated_spans.gate(sym::inline_const, span); . } -- line 1104 ---------------------------------------- -- line 1108 ---------------------------------------- . id: DUMMY_NODE_ID, . value: self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()), . }; . let blk_span = anon_const.value.span; . Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::new())) . } . . /// Parses mutability (`mut` or nothing). 12 ( 0.00%) fn parse_mutability(&mut self) -> Mutability { . if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not } 153 ( 0.00%) } . . /// Possibly parses mutability (`const` or `mut`). . fn parse_const_or_mut(&mut self) -> Option { . if self.eat_keyword(kw::Mut) { . Some(Mutability::Mut) . } else if self.eat_keyword(kw::Const) { . Some(Mutability::Not) . } else { . None . } . } . . fn parse_field_name(&mut self) -> PResult<'a, Ident> { 35,046 ( 0.00%) if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind . { . self.expect_no_suffix(self.token.span, "a tuple index", suffix); . self.bump(); . Ok(Ident::new(symbol, self.prev_token.span)) . } else { 52,569 ( 0.00%) self.parse_ident_common(true) . } . } . . fn parse_mac_args(&mut self) -> PResult<'a, P> { 23 ( 0.00%) self.parse_mac_args_common(true).map(P) . } . . fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> { 66 ( 0.00%) self.parse_mac_args_common(false) . } . 279 ( 0.00%) fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> { 248 ( 0.00%) Ok( 199 ( 0.00%) if self.check(&token::OpenDelim(DelimToken::Paren)) 33 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Bracket)) 33 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Brace)) . { 80 ( 0.00%) match self.parse_token_tree() { 100 ( 0.00%) TokenTree::Delimited(dspan, delim, tokens) => . // We've confirmed above that there is a delimiter so unwrapping is OK. . { 40 ( 0.00%) MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens) . } . _ => unreachable!(), . } 22 ( 0.00%) } else if !delimited_only { . if self.eat(&token::Eq) { . let eq_span = self.prev_token.span; . . // Collect tokens because they are used during lowering to HIR. . let expr = self.parse_expr_force_collect()?; . let span = expr.span; . . let token_kind = token::Interpolated(Lrc::new(token::NtExpr(expr))); -- line 1172 ---------------------------------------- -- line 1173 ---------------------------------------- . MacArgs::Eq(eq_span, Token::new(token_kind, span)) . } else { . MacArgs::Empty . } . } else { . return self.unexpected(); . }, . ) 217 ( 0.00%) } . . fn parse_or_use_outer_attributes( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, AttrWrapper> { 114,343 ( 0.00%) if let Some(attrs) = already_parsed_attrs { . Ok(attrs) . } else { 75,682 ( 0.00%) self.parse_outer_attributes() . } . } . . /// Parses a single token tree from the input. 1,048 ( 0.00%) pub(crate) fn parse_token_tree(&mut self) -> TokenTree { 733 ( 0.00%) match self.token.kind { . token::OpenDelim(..) => { . let depth = self.token_cursor.stack.len(); . . // We keep advancing the token cursor until we hit . // the matching `CloseDelim` token. 1,322 ( 0.00%) while !(depth == self.token_cursor.stack.len() . && matches!(self.token.kind, token::CloseDelim(_))) . { . // Advance one token at a time, so `TokenCursor::next()` . // can capture these tokens if necessary. 746 ( 0.00%) self.bump(); . } . // We are still inside the frame corresponding . // to the delimited stream we captured, so grab . // the tokens from this frame. . let frame = &self.token_cursor.frame; 92 ( 0.00%) let stream = frame.tree_cursor.stream.clone(); 92 ( 0.00%) let span = frame.span; 46 ( 0.00%) let delim = frame.delim; . // Consume close delimiter 92 ( 0.00%) self.bump(); 230 ( 0.00%) TokenTree::Delimited(span, delim, stream) . } . token::CloseDelim(_) | token::Eof => unreachable!(), . _ => { 170 ( 0.00%) self.bump(); 425 ( 0.00%) TokenTree::Token(self.prev_token.clone()) . } . } 917 ( 0.00%) } . . /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF. . pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec> { . let mut tts = Vec::new(); . while self.token != token::Eof { . tts.push(self.parse_token_tree()); . } . Ok(tts) -- line 1234 ---------------------------------------- -- line 1244 ---------------------------------------- . } . TokenStream::new(result) . } . . /// Evaluates the closure with restrictions in place. . /// . /// Afters the closure is evaluated, restrictions are reset. . fn with_res(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T { 38,161 ( 0.00%) let old = self.restrictions; 38,637 ( 0.00%) self.restrictions = res; . let res = f(self); 38,585 ( 0.00%) self.restrictions = old; . res . } . 3,248 ( 0.00%) fn is_crate_vis(&self) -> bool { 2,030 ( 0.00%) self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep) 3,654 ( 0.00%) } . . /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`, . /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`. . /// If the following element can't be a tuple (i.e., it's a function definition), then . /// it's not a tuple struct field), and the contents within the parentheses aren't valid, . /// so emit a proper diagnostic. . // Public for rustfmt usage. 2,710 ( 0.00%) pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> { 542 ( 0.00%) maybe_whole!(self, NtVis, |x| x); . 271 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw::Crate)); 1,084 ( 0.00%) if self.is_crate_vis() { . self.bump(); // `crate` . self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span); . return Ok(Visibility { . span: self.prev_token.span, . kind: VisibilityKind::Crate(CrateSugar::JustCrate), . tokens: None, . }); . } . . if !self.eat_keyword(kw::Pub) { . // We need a span for our `Spanned`, but there's inherently no . // keyword to grab a span from for inherited visibility; an empty span at the . // beginning of the current token would seem to be the "Schelling span". 244 ( 0.00%) return Ok(Visibility { 732 ( 0.00%) span: self.token.span.shrink_to_lo(), . kind: VisibilityKind::Inherited, . tokens: None, . }); . } 27 ( 0.00%) let lo = self.prev_token.span; . 135 ( 0.00%) if self.check(&token::OpenDelim(token::Paren)) { . // We don't `self.bump()` the `(` yet because this might be a struct definition where . // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`. . // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so . // by the following tokens. 45 ( 0.00%) if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep) . // account for `pub(crate::foo)` . { . // Parse `pub(crate)`. 15 ( 0.00%) self.bump(); // `(` 10 ( 0.00%) self.bump(); // `crate` 15 ( 0.00%) self.expect(&token::CloseDelim(token::Paren))?; // `)` 5 ( 0.00%) let vis = VisibilityKind::Crate(CrateSugar::PubCrate); . return Ok(Visibility { 15 ( 0.00%) span: lo.to(self.prev_token.span), . kind: vis, . tokens: None, . }); . } else if self.is_keyword_ahead(1, &[kw::In]) { . // Parse `pub(in path)`. . self.bump(); // `(` . self.bump(); // `in` . let path = self.parse_path(PathStyle::Mod)?; // `path` -- line 1317 ---------------------------------------- -- line 1338 ---------------------------------------- . } else if let FollowedByType::No = fbt { . // Provide this diagnostic if a type cannot follow; . // in particular, if this is not a tuple struct. . self.recover_incorrect_vis_restriction()?; . // Emit diagnostic, but continue with public visibility. . } . } . 66 ( 0.00%) Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None }) 2,439 ( 0.00%) } . . /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }` . fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> { . self.bump(); // `(` . let path = self.parse_path(PathStyle::Mod)?; . self.expect(&token::CloseDelim(token::Paren))?; // `)` . . let msg = "incorrect visibility restriction"; -- line 1355 ---------------------------------------- -- line 1370 ---------------------------------------- . ) . .emit(); . . Ok(()) . } . . /// Parses `extern string_literal?`. . fn parse_extern(&mut self) -> Extern { 37 ( 0.00%) if self.eat_keyword(kw::Extern) { Extern::from_abi(self.parse_abi()) } else { Extern::None } . } . . /// Parses a string literal as an ABI spec. . fn parse_abi(&mut self) -> Option { . match self.parse_str_lit() { . Ok(str_lit) => Some(str_lit), . Err(Some(lit)) => match lit.kind { . ast::LitKind::Err(_) => None, -- line 1386 ---------------------------------------- -- line 1395 ---------------------------------------- . .emit(); . None . } . }, . Err(None) => None, . } . } . 30 ( 0.00%) pub fn collect_tokens_no_attrs( . &mut self, . f: impl FnOnce(&mut Self) -> PResult<'a, R>, . ) -> PResult<'a, R> { . // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use . // `ForceCollect::Yes` . self.collect_tokens_trailing_token( . AttrWrapper::empty(), . ForceCollect::Yes, 3 ( 0.00%) |this, _attrs| Ok((f(this)?, TrailingToken::None)), . ) 30 ( 0.00%) } . . /// `::{` or `::*` 119,288 ( 0.00%) fn is_import_coupler(&mut self) -> bool { 59,644 ( 0.00%) self.check(&token::ModSep) . && self.look_ahead(1, |t| { 1,521 ( 0.00%) *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star) . }) 133,425 ( 0.00%) } . . pub fn clear_expected_tokens(&mut self) { . self.expected_tokens.clear(); . } . } . . crate fn make_unclosed_delims_error( . unmatched: UnmatchedBrace, -- line 1430 ---------------------------------------- -- line 1450 ---------------------------------------- . err.span_label(sp, "closing delimiter possibly meant for this"); . } . if let Some(sp) = unmatched.unclosed_span { . err.span_label(sp, "unclosed delimiter"); . } . Some(err) . } . 592 ( 0.00%) pub fn emit_unclosed_delims(unclosed_delims: &mut Vec, sess: &ParseSess) { 296 ( 0.00%) *sess.reached_eof.borrow_mut() |= . unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()); 296 ( 0.00%) for unmatched in unclosed_delims.drain(..) { . if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) { . e.emit(); . } . } 592 ( 0.00%) } . . /// A helper struct used when building an `AttrAnnotatedTokenStream` from . /// a `LazyTokenStream`. Both delimiter and non-delimited tokens . /// are stored as `FlatToken::Token`. A vector of `FlatToken`s . /// is then 'parsed' to build up an `AttrAnnotatedTokenStream` with nested . /// `AttrAnnotatedTokenTree::Delimited` tokens . #[derive(Debug, Clone)] . pub enum FlatToken { -- line 1474 ---------------------------------------- 795,857 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs -------------------------------------------------------------------------------- Ir -- line 22 ---------------------------------------- . . /// An entity in the Rust type system, which can be one of . /// several kinds (types, lifetimes, and consts). . /// To reduce memory usage, a `GenericArg` is an interned pointer, . /// with the lowest 2 bits being reserved for a tag to . /// indicate the type (`Ty`, `Region`, or `Const`) it points to. . #[derive(Copy, Clone, PartialEq, Eq, Hash)] . pub struct GenericArg<'tcx> { 334,556 ( 0.01%) ptr: NonZeroUsize, 618,890 ( 0.01%) marker: PhantomData<(Ty<'tcx>, ty::Region<'tcx>, &'tcx ty::Const<'tcx>)>, . } . . const TAG_MASK: usize = 0b11; . const TYPE_TAG: usize = 0b00; . const REGION_TAG: usize = 0b01; . const CONST_TAG: usize = 0b10; . 86,272 ( 0.00%) #[derive(Debug, TyEncodable, TyDecodable, PartialEq, Eq, PartialOrd, Ord, HashStable)] . pub enum GenericArgKind<'tcx> { . Lifetime(ty::Region<'tcx>), . Type(Ty<'tcx>), . Const(&'tcx ty::Const<'tcx>), . } . . impl<'tcx> GenericArgKind<'tcx> { 21,151 ( 0.00%) fn pack(self) -> GenericArg<'tcx> { 21,151 ( 0.00%) let (tag, ptr) = match self { . GenericArgKind::Lifetime(lt) => { . // Ensure we can use the tag bits. . assert_eq!(mem::align_of_val(lt) & TAG_MASK, 0); . (REGION_TAG, lt as *const _ as usize) . } . GenericArgKind::Type(ty) => { . // Ensure we can use the tag bits. . assert_eq!(mem::align_of_val(ty) & TAG_MASK, 0); -- line 56 ---------------------------------------- -- line 58 ---------------------------------------- . } . GenericArgKind::Const(ct) => { . // Ensure we can use the tag bits. . assert_eq!(mem::align_of_val(ct) & TAG_MASK, 0); . (CONST_TAG, ct as *const _ as usize) . } . }; . 53,460 ( 0.00%) GenericArg { ptr: unsafe { NonZeroUsize::new_unchecked(ptr | tag) }, marker: PhantomData } 21,151 ( 0.00%) } . } . . impl<'tcx> fmt::Debug for GenericArg<'tcx> { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . match self.unpack() { . GenericArgKind::Lifetime(lt) => lt.fmt(f), . GenericArgKind::Type(ty) => ty.fmt(f), . GenericArgKind::Const(ct) => ct.fmt(f), -- line 75 ---------------------------------------- -- line 85 ---------------------------------------- . . impl<'tcx> PartialOrd for GenericArg<'tcx> { . fn partial_cmp(&self, other: &GenericArg<'_>) -> Option { . Some(self.cmp(&other)) . } . } . . impl<'tcx> From> for GenericArg<'tcx> { 20,707 ( 0.00%) fn from(r: ty::Region<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Lifetime(r).pack() 20,707 ( 0.00%) } . } . . impl<'tcx> From> for GenericArg<'tcx> { 276,058 ( 0.01%) fn from(ty: Ty<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Type(ty).pack() 276,058 ( 0.01%) } . } . . impl<'tcx> From<&'tcx ty::Const<'tcx>> for GenericArg<'tcx> { 329 ( 0.00%) fn from(c: &'tcx ty::Const<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Const(c).pack() 329 ( 0.00%) } . } . . impl<'tcx> GenericArg<'tcx> { . #[inline] . pub fn unpack(self) -> GenericArgKind<'tcx> { . let ptr = self.ptr.get(); . unsafe { 4,013,607 ( 0.08%) match ptr & TAG_MASK { 25,510 ( 0.00%) REGION_TAG => GenericArgKind::Lifetime(&*((ptr & !TAG_MASK) as *const _)), 967,046 ( 0.02%) TYPE_TAG => GenericArgKind::Type(&*((ptr & !TAG_MASK) as *const _)), 561 ( 0.00%) CONST_TAG => GenericArgKind::Const(&*((ptr & !TAG_MASK) as *const _)), . _ => intrinsics::unreachable(), . } . } . } . . /// Unpack the `GenericArg` as a type when it is known certainly to be a type. . /// This is true in cases where `Substs` is used in places where the kinds are known . /// to be limited (e.g. in tuples, where the only parameters are type parameters). . pub fn expect_ty(self) -> Ty<'tcx> { . match self.unpack() { . GenericArgKind::Type(ty) => ty, . _ => bug!("expected a type, but found another kind"), . } 62,384 ( 0.00%) } . . /// Unpack the `GenericArg` as a const when it is known certainly to be a const. . pub fn expect_const(self) -> &'tcx ty::Const<'tcx> { . match self.unpack() { . GenericArgKind::Const(c) => c, . _ => bug!("expected a const, but found another kind"), . } . } -- line 140 ---------------------------------------- -- line 155 ---------------------------------------- . impl<'tcx> TypeFoldable<'tcx> for GenericArg<'tcx> { . fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { . match self.unpack() { . GenericArgKind::Lifetime(lt) => lt.try_fold_with(folder).map(Into::into), . GenericArgKind::Type(ty) => ty.try_fold_with(folder).map(Into::into), 3 ( 0.00%) GenericArgKind::Const(ct) => ct.try_fold_with(folder).map(Into::into), . } . } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { . match self.unpack() { . GenericArgKind::Lifetime(lt) => lt.visit_with(visitor), . GenericArgKind::Type(ty) => ty.visit_with(visitor), . GenericArgKind::Const(ct) => ct.visit_with(visitor), . } . } . } . . impl<'tcx, E: TyEncoder<'tcx>> Encodable for GenericArg<'tcx> { . fn encode(&self, e: &mut E) -> Result<(), E::Error> { 5,615 ( 0.00%) self.unpack().encode(e) . } . } . . impl<'tcx, D: TyDecoder<'tcx>> Decodable for GenericArg<'tcx> { 105,755 ( 0.00%) fn decode(d: &mut D) -> GenericArg<'tcx> { 105,755 ( 0.00%) GenericArgKind::decode(d).pack() . } . } . . /// A substitution mapping generic parameters to new values. . pub type InternalSubsts<'tcx> = List>; . . pub type SubstsRef<'tcx> = &'tcx InternalSubsts<'tcx>; . . impl<'a, 'tcx> InternalSubsts<'tcx> { . /// Interpret these substitutions as the substitutions of a closure type. . /// Closure substitutions have a particular structure controlled by the . /// compiler that encodes information like the signature and closure kind; . /// see `ty::ClosureSubsts` struct for more comments. 1,464 ( 0.00%) pub fn as_closure(&'a self) -> ClosureSubsts<'a> { . ClosureSubsts { substs: self } 1,464 ( 0.00%) } . . /// Interpret these substitutions as the substitutions of a generator type. . /// Generator substitutions have a particular structure controlled by the . /// compiler that encodes information like the signature and generator kind; . /// see `ty::GeneratorSubsts` struct for more comments. . pub fn as_generator(&'tcx self) -> GeneratorSubsts<'tcx> { . GeneratorSubsts { substs: self } . } -- line 208 ---------------------------------------- -- line 211 ---------------------------------------- . /// Inline const substitutions have a particular structure controlled by the . /// compiler that encodes information like the inferred type; . /// see `ty::InlineConstSubsts` struct for more comments. . pub fn as_inline_const(&'tcx self) -> InlineConstSubsts<'tcx> { . InlineConstSubsts { substs: self } . } . . /// Creates an `InternalSubsts` that maps each generic parameter to itself. 3,280 ( 0.00%) pub fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: DefId) -> SubstsRef<'tcx> { 560 ( 0.00%) Self::for_item(tcx, def_id, |param, _| tcx.mk_param_from_def(param)) 2,952 ( 0.00%) } . . /// Creates an `InternalSubsts` for generic parameter definitions, . /// by calling closures to obtain each kind. . /// The closures get to observe the `InternalSubsts` as they're . /// being built, which can be used to correctly . /// substitute defaults of generic parameters. 104,127 ( 0.00%) pub fn for_item(tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx> . where . F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, . { . let defs = tcx.generics_of(def_id); . let count = defs.count(); . let mut substs = SmallVec::with_capacity(count); 36,036 ( 0.00%) Self::fill_item(&mut substs, tcx, defs, &mut mk_kind); 21,310 ( 0.00%) tcx.intern_substs(&substs) 104,544 ( 0.00%) } . . pub fn extend_to(&self, tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx> . where . F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, . { . Self::for_item(tcx, def_id, |param, substs| { . self.get(param.index as usize).cloned().unwrap_or_else(|| mk_kind(param, substs)) . }) . } . 124,756 ( 0.00%) pub fn fill_item( . substs: &mut SmallVec<[GenericArg<'tcx>; 8]>, . tcx: TyCtxt<'tcx>, . defs: &ty::Generics, . mk_kind: &mut F, . ) where . F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, . { 50,936 ( 0.00%) if let Some(def_id) = defs.parent { . let parent_defs = tcx.generics_of(def_id); 2,101 ( 0.00%) Self::fill_item(substs, tcx, parent_defs, mk_kind); . } . Self::fill_single(substs, defs, mk_kind) 98,896 ( 0.00%) } . 16 ( 0.00%) pub fn fill_single( . substs: &mut SmallVec<[GenericArg<'tcx>; 8]>, . defs: &ty::Generics, . mk_kind: &mut F, . ) where . F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, . { . substs.reserve(defs.params.len()); . for param in &defs.params { 16 ( 0.00%) let kind = mk_kind(param, substs); 70,944 ( 0.00%) assert_eq!(param.index as usize, substs.len()); . substs.push(kind); . } 16 ( 0.00%) } . . #[inline] . pub fn types(&'a self) -> impl DoubleEndedIterator> + 'a { . self.iter() . .filter_map(|k| if let GenericArgKind::Type(ty) = k.unpack() { Some(ty) } else { None }) . } . . #[inline] -- line 284 ---------------------------------------- -- line 302 ---------------------------------------- . self.iter().filter_map(|k| match k.unpack() { . GenericArgKind::Lifetime(_) => None, . generic => Some(generic), . }) . } . . #[inline] . pub fn type_at(&self, i: usize) -> Ty<'tcx> { 167,715 ( 0.00%) if let GenericArgKind::Type(ty) = self[i].unpack() { . ty . } else { . bug!("expected type for param #{} in {:?}", i, self); . } . } . . #[inline] . pub fn region_at(&self, i: usize) -> ty::Region<'tcx> { -- line 318 ---------------------------------------- -- line 350 ---------------------------------------- . /// impl X for U { fn f() {} } . /// ``` . /// . /// * If `self` is `[Self, S, T]`: the identity substs of `f` in the trait. . /// * If `source_ancestor` is the def_id of the trait. . /// * If `target_substs` is `[U]`, the substs for the impl. . /// * Then we will return `[U, T]`, the subst for `f` in the impl that . /// are needed for it to match the trait. 5,579 ( 0.00%) pub fn rebase_onto( . &self, . tcx: TyCtxt<'tcx>, . source_ancestor: DefId, . target_substs: SubstsRef<'tcx>, . ) -> SubstsRef<'tcx> { . let defs = tcx.generics_of(source_ancestor); 1,594 ( 0.00%) tcx.mk_substs(target_substs.iter().chain(self.iter().skip(defs.params.len()))) 6,376 ( 0.00%) } . 1,035 ( 0.00%) pub fn truncate_to(&self, tcx: TyCtxt<'tcx>, generics: &ty::Generics) -> SubstsRef<'tcx> { . tcx.mk_substs(self.iter().take(generics.count())) 2,070 ( 0.00%) } . } . . impl<'tcx> TypeFoldable<'tcx> for SubstsRef<'tcx> { 15,526 ( 0.00%) fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { . // This code is hot enough that it's worth specializing for the most . // common length lists, to avoid the overhead of `SmallVec` creation. . // The match arms are in order of frequency. The 1, 2, and 0 cases are . // typically hit in 90--99.99% of cases. When folding doesn't change . // the substs, it's faster to reuse the existing substs rather than . // calling `intern_substs`. 854,138 ( 0.02%) match self.len() { . 1 => { 58,033 ( 0.00%) let param0 = self[0].try_fold_with(folder)?; 190,801 ( 0.00%) if param0 == self[0] { Ok(self) } else { Ok(folder.tcx().intern_substs(&[param0])) } . } . 2 => { 103,053 ( 0.00%) let param0 = self[0].try_fold_with(folder)?; 292,259 ( 0.01%) let param1 = self[1].try_fold_with(folder)?; 353,958 ( 0.01%) if param0 == self[0] && param1 == self[1] { . Ok(self) . } else { 418,054 ( 0.01%) Ok(folder.tcx().intern_substs(&[param0, param1])) . } . } . 0 => Ok(self), . _ => { . let params: SmallVec<[_; 8]> = 4,491 ( 0.00%) self.iter().map(|k| k.try_fold_with(folder)).collect::>()?; 287 ( 0.00%) if params[..] == self[..] { . Ok(self) . } else { 1,095 ( 0.00%) Ok(folder.tcx().intern_substs(¶ms)) . } . } . } 23,852 ( 0.00%) } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { 71,316 ( 0.00%) self.iter().try_for_each(|t| t.visit_with(visitor)) . } . } . . /////////////////////////////////////////////////////////////////////////// . // Public trait `Subst` . // . // Just call `foo.subst(tcx, substs)` to perform a substitution across . // `foo`. Or use `foo.subst_spanned(tcx, substs, Some(span))` when -- line 420 ---------------------------------------- -- line 435 ---------------------------------------- . . impl<'tcx, T: TypeFoldable<'tcx>> Subst<'tcx> for T { . fn subst_spanned( . self, . tcx: TyCtxt<'tcx>, . substs: &[GenericArg<'tcx>], . span: Option, . ) -> T { 1,913,531 ( 0.04%) let mut folder = SubstFolder { tcx, substs, span, binders_passed: 0 }; . self.fold_with(&mut folder) . } . } . . /////////////////////////////////////////////////////////////////////////// . // The actual substitution engine itself is a type folder. . . struct SubstFolder<'a, 'tcx> { -- line 451 ---------------------------------------- -- line 456 ---------------------------------------- . span: Option, . . /// Number of region binders we have passed through while doing the substitution . binders_passed: u32, . } . . impl<'a, 'tcx> TypeFolder<'tcx> for SubstFolder<'a, 'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { 84,637 ( 0.00%) self.tcx . } . . fn fold_binder>( . &mut self, . t: ty::Binder<'tcx, T>, . ) -> ty::Binder<'tcx, T> { 58,618 ( 0.00%) self.binders_passed += 1; 3,867 ( 0.00%) let t = t.super_fold_with(self); 58,618 ( 0.00%) self.binders_passed -= 1; . t . } . 113,214 ( 0.00%) fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { . // Note: This routine only handles regions that are bound on . // type declarations and other outer declarations, not those . // bound in *fn types*. Region substitution of the bound . // regions that appear in a function signature is done using . // the specialized routine `ty::replace_late_regions()`. 37,738 ( 0.00%) match *r { 16,708 ( 0.00%) ty::ReEarlyBound(data) => { 16,708 ( 0.00%) let rk = self.substs.get(data.index as usize).map(|k| k.unpack()); . match rk { 8,354 ( 0.00%) Some(GenericArgKind::Lifetime(lt)) => self.shift_region_through_binders(lt), . _ => { . let span = self.span.unwrap_or(DUMMY_SP); . let msg = format!( . "Region parameter out of range \ . when substituting in region {} (index={})", . data.name, data.index . ); . span_bug!(span, "{}", msg); . } . } . } . _ => r, . } 132,083 ( 0.00%) } . 1,278,417 ( 0.03%) fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 426,139 ( 0.01%) if !t.needs_subst() { . return t; . } . 242,668 ( 0.00%) match *t.kind() { 335,545 ( 0.01%) ty::Param(p) => self.ty_for_param(p, t), 325,350 ( 0.01%) _ => t.super_fold_with(self), . } 1,859,570 ( 0.04%) } . 206,822 ( 0.00%) fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 60,492 ( 0.00%) if let ty::ConstKind::Param(p) = c.val { . self.const_for_param(p, c) . } else { 263,394 ( 0.01%) c.super_fold_with(self) . } 2,240 ( 0.00%) } . . #[inline] . fn fold_mir_const(&mut self, c: mir::ConstantKind<'tcx>) -> mir::ConstantKind<'tcx> { . c.super_fold_with(self) . } . } . . impl<'a, 'tcx> SubstFolder<'a, 'tcx> { . fn ty_for_param(&self, p: ty::ParamTy, source_ty: Ty<'tcx>) -> Ty<'tcx> { . // Look up the type in the substitutions. It really should be in there. 134,218 ( 0.00%) let opt_ty = self.substs.get(p.index as usize).map(|k| k.unpack()); . let ty = match opt_ty { . Some(GenericArgKind::Type(ty)) => ty, . Some(kind) => { . let span = self.span.unwrap_or(DUMMY_SP); . span_bug!( . span, . "expected type for `{:?}` ({:?}/{}) but found {:?} \ . when substituting, substs={:?}", -- line 539 ---------------------------------------- -- line 562 ---------------------------------------- . } . . fn const_for_param( . &self, . p: ParamConst, . source_ct: &'tcx ty::Const<'tcx>, . ) -> &'tcx ty::Const<'tcx> { . // Look up the const in the substitutions. It really should be in there. 560 ( 0.00%) let opt_ct = self.substs.get(p.index as usize).map(|k| k.unpack()); . let ct = match opt_ct { . Some(GenericArgKind::Const(ct)) => ct, . Some(kind) => { . let span = self.span.unwrap_or(DUMMY_SP); . span_bug!( . span, . "expected const for `{:?}` ({:?}/{}) but found {:?} \ . when substituting substs={:?}", -- line 578 ---------------------------------------- -- line 645 ---------------------------------------- . fn shift_vars_through_binders>(&self, val: T) -> T { . debug!( . "shift_vars(val={:?}, binders_passed={:?}, has_escaping_bound_vars={:?})", . val, . self.binders_passed, . val.has_escaping_bound_vars() . ); . 227,086 ( 0.00%) if self.binders_passed == 0 || !val.has_escaping_bound_vars() { . return val; . } . . let result = ty::fold::shift_vars(self.tcx(), val, self.binders_passed); . debug!("shift_vars: shifted result = {:?}", result); . . result . } . . fn shift_region_through_binders(&self, region: ty::Region<'tcx>) -> ty::Region<'tcx> { 18,054 ( 0.00%) if self.binders_passed == 0 || !region.has_escaping_bound_vars() { . return region; . } . ty::fold::shift_region(self.tcx, region, self.binders_passed) . } . } . . /// Stores the user-given substs to reach some fully qualified path . /// (e.g., `::Item` or `::Item`). . #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] 622 ( 0.00%) #[derive(HashStable, TypeFoldable, Lift)] . pub struct UserSubsts<'tcx> { . /// The substitutions for the item as given by the user. . pub substs: SubstsRef<'tcx>, . . /// The self type, in the case of a `::Item` path (when applied . /// to an inherent impl). See `UserSelfTy` below. 140 ( 0.00%) pub user_self_ty: Option>, . } . . /// Specifies the user-given self type. In the case of a path that . /// refers to a member in an inherent impl, this self type is . /// sometimes needed to constrain the type parameters on the impl. For . /// example, in this code: . /// . /// ``` -- line 689 ---------------------------------------- -- line 696 ---------------------------------------- . /// self type `Foo`. Then we can instantiate the parameters of . /// the impl (with the substs from `UserSubsts`) and apply those to . /// the self type, giving `Foo`. Finally, we unify that with . /// the self type here, which contains `?A` to be `&'static u32` . #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] . #[derive(HashStable, TypeFoldable, Lift)] . pub struct UserSelfTy<'tcx> { . pub impl_def_id: DefId, 57 ( 0.00%) pub self_ty: Ty<'tcx>, . } 1,300,615 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs -------------------------------------------------------------------------------- Ir -- line 12 ---------------------------------------- . use rustc_data_structures::sync::Lrc; . use rustc_macros::HashStable_Generic; . use rustc_span::symbol::{kw, sym}; . use rustc_span::symbol::{Ident, Symbol}; . use rustc_span::{self, edition::Edition, Span, DUMMY_SP}; . use std::borrow::Cow; . use std::{fmt, mem}; . 17,612 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum CommentKind { . Line, . Block, . } . 71 ( 0.00%) #[derive(Clone, PartialEq, Encodable, Decodable, Hash, Debug, Copy)] . #[derive(HashStable_Generic)] . pub enum BinOpToken { . Plus, . Minus, . Star, . Slash, . Percent, . Caret, . And, . Or, . Shl, . Shr, . } . . /// A delimiter token. 101,579 ( 0.00%) #[derive(Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug, Copy)] . #[derive(HashStable_Generic)] . pub enum DelimToken { . /// A round parenthesis (i.e., `(` or `)`). . Paren, . /// A square bracket (i.e., `[` or `]`). . Bracket, . /// A curly brace (i.e., `{` or `}`). . Brace, . /// An empty delimiter. . NoDelim, . } . 2,138 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum LitKind { . Bool, // AST only, must never appear in a `Token` . Byte, . Char, . Integer, . Float, . Str, . StrRaw(u16), // raw string delimited by `n` hash symbols . ByteStr, . ByteStrRaw(u16), // raw byte string delimited by `n` hash symbols . Err, . } . . /// A literal token. 50,771 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Lit { . pub kind: LitKind, . pub symbol: Symbol, . pub suffix: Option, . } . . impl fmt::Display for Lit { 15 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 27 ( 0.00%) let Lit { kind, symbol, suffix } = *self; . match kind { . Byte => write!(f, "b'{}'", symbol)?, . Char => write!(f, "'{}'", symbol)?, 3 ( 0.00%) Str => write!(f, "\"{}\"", symbol)?, . StrRaw(n) => write!( . f, . "r{delim}\"{string}\"{delim}", . delim = "#".repeat(n as usize), . string = symbol . )?, . ByteStr => write!(f, "b\"{}\"", symbol)?, . ByteStrRaw(n) => write!( . f, . "br{delim}\"{string}\"{delim}", . delim = "#".repeat(n as usize), . string = symbol . )?, 6 ( 0.00%) Integer | Float | Bool | Err => write!(f, "{}", symbol)?, . } . 6 ( 0.00%) if let Some(suffix) = suffix { . write!(f, "{}", suffix)?; . } . . Ok(()) 15 ( 0.00%) } . } . . impl LitKind { . /// An English article for the literal token kind. . pub fn article(self) -> &'static str { . match self { . Integer | Err => "an", . _ => "a", -- line 113 ---------------------------------------- -- line 130 ---------------------------------------- . crate fn may_have_suffix(self) -> bool { . matches!(self, Integer | Float | Err) . } . } . . impl Lit { . pub fn new(kind: LitKind, symbol: Symbol, suffix: Option) -> Lit { . Lit { kind, symbol, suffix } 273 ( 0.00%) } . } . 120 ( 0.00%) pub fn ident_can_begin_expr(name: Symbol, span: Span, is_raw: bool) -> bool { 210 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 105 ( 0.00%) !ident_token.is_reserved_ident() . || ident_token.is_path_segment_keyword() . || [ . kw::Async, . kw::Do, . kw::Box, . kw::Break, . kw::Const, . kw::Continue, -- line 152 ---------------------------------------- -- line 161 ---------------------------------------- . kw::True, . kw::Try, . kw::Unsafe, . kw::While, . kw::Yield, . kw::Static, . ] . .contains(&name) 150 ( 0.00%) } . . fn ident_can_begin_type(name: Symbol, span: Span, is_raw: bool) -> bool { 156 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 56 ( 0.00%) !ident_token.is_reserved_ident() . || ident_token.is_path_segment_keyword() . || [kw::Underscore, kw::For, kw::Impl, kw::Fn, kw::Unsafe, kw::Extern, kw::Typeof, kw::Dyn] . .contains(&name) . } . 12,386,502 ( 0.25%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum TokenKind { . /* Expression-operator symbols. */ . Eq, . Lt, . Le, . EqEq, . Ne, . Ge, . Gt, . AndAnd, . OrOr, . Not, . Tilde, 48,354 ( 0.00%) BinOp(BinOpToken), 78 ( 0.00%) BinOpEq(BinOpToken), . . /* Structural symbols */ . At, . Dot, . DotDot, . DotDotDot, . DotDotEq, . Comma, -- line 203 ---------------------------------------- -- line 208 ---------------------------------------- . LArrow, . FatArrow, . Pound, . Dollar, . Question, . /// Used by proc macros for representing lifetimes, not generated by lexer right now. . SingleQuote, . /// An opening delimiter (e.g., `{`). 161,490 ( 0.00%) OpenDelim(DelimToken), . /// A closing delimiter (e.g., `}`). 120,591 ( 0.00%) CloseDelim(DelimToken), . . /* Literals */ 68,587 ( 0.00%) Literal(Lit), . . /// Identifier token. . /// Do not forget about `NtIdent` when you want to match on identifiers. . /// It's recommended to use `Token::(ident,uninterpolate,uninterpolated_span)` to . /// treat regular and interpolated identifiers in the same way. 34,809 ( 0.00%) Ident(Symbol, /* is_raw */ bool), . /// Lifetime identifier token. . /// Do not forget about `NtLifetime` when you want to match on lifetime identifiers. . /// It's recommended to use `Token::(lifetime,uninterpolate,uninterpolated_span)` to . /// treat regular and interpolated lifetime identifiers in the same way. 108 ( 0.00%) Lifetime(Symbol), . 9 ( 0.00%) Interpolated(Lrc), . . /// A doc comment token. . /// `Symbol` is the doc comment's data excluding its "quotes" (`///`, `/**`, etc) . /// similarly to symbols in string literal tokens. 243 ( 0.00%) DocComment(CommentKind, ast::AttrStyle, Symbol), . . Eof, . } . . // `TokenKind` is used a lot. Make sure it doesn't unintentionally get bigger. . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(TokenKind, 16); . 465,976 ( 0.01%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Token { 8,137 ( 0.00%) pub kind: TokenKind, . pub span: Span, . } . . impl TokenKind { . pub fn lit(kind: LitKind, symbol: Symbol, suffix: Option) -> TokenKind { . Literal(Lit::new(kind, symbol, suffix)) . } . . // An approximation to proc-macro-style single-character operators used by rustc parser. . // If the operator token can be broken into two tokens, the first of which is single-character, . // then this function performs that operation, otherwise it returns `None`. 14,634 ( 0.00%) pub fn break_two_token_op(&self) -> Option<(TokenKind, TokenKind)> { 58,554 ( 0.00%) Some(match *self { . Le => (Lt, Eq), . EqEq => (Eq, Eq), . Ne => (Not, Eq), . Ge => (Gt, Eq), . AndAnd => (BinOp(And), BinOp(And)), . OrOr => (BinOp(Or), BinOp(Or)), . BinOp(Shl) => (Lt, Lt), . BinOp(Shr) => (Gt, Gt), -- line 271 ---------------------------------------- -- line 280 ---------------------------------------- . BinOpEq(Shl) => (Lt, Le), . BinOpEq(Shr) => (Gt, Ge), . DotDot => (Dot, Dot), . DotDotDot => (Dot, DotDot), . ModSep => (Colon, Colon), . RArrow => (BinOp(Minus), Gt), . LArrow => (Lt, BinOp(Minus)), . FatArrow => (Eq, Gt), 14,632 ( 0.00%) _ => return None, . }) 14,634 ( 0.00%) } . . /// Returns tokens that are likely to be typed accidentally instead of the current token. . /// Enables better error recovery when the wrong token is found. . pub fn similar_tokens(&self) -> Option> { . match *self { . Comma => Some(vec![Dot, Lt, Semi]), . Semi => Some(vec![Colon, Comma]), . FatArrow => Some(vec![Eq, RArrow]), . _ => None, . } . } . . pub fn should_end_const_arg(&self) -> bool { 140 ( 0.00%) matches!(self, Gt | Ge | BinOp(Shr) | BinOpEq(Shr)) 32 ( 0.00%) } . } . . impl Token { 151,989 ( 0.00%) pub fn new(kind: TokenKind, span: Span) -> Self { 457,013 ( 0.01%) Token { kind, span } 151,989 ( 0.00%) } . . /// Some token that will be thrown away later. 274 ( 0.00%) pub fn dummy() -> Self { . Token::new(TokenKind::Question, DUMMY_SP) 274 ( 0.00%) } . . /// Recovers a `Token` from an `Ident`. This creates a raw identifier if necessary. . pub fn from_ast_ident(ident: Ident) -> Self { 152 ( 0.00%) Token::new(Ident(ident.name, ident.is_raw_guess()), ident.span) . } . . /// Return this token by value and leave a dummy token in its place. 97,777 ( 0.00%) pub fn take(&mut self) -> Self { . mem::replace(self, Token::dummy()) 97,777 ( 0.00%) } . . /// For interpolated tokens, returns a span of the fragment to which the interpolated . /// token refers. For all other tokens this is just a regular span. . /// It is particularly important to use this for identifiers and lifetimes . /// for which spans affect name resolution and edition checks. . /// Note that keywords are also identifiers, so they should use this . /// if they keep spans or perform edition checks. . pub fn uninterpolated_span(&self) -> Span { 522 ( 0.00%) match &self.kind { . Interpolated(nt) => nt.span(), 261 ( 0.00%) _ => self.span, . } 261 ( 0.00%) } . . pub fn is_op(&self) -> bool { 293,331 ( 0.01%) !matches!( 97,777 ( 0.00%) self.kind, . OpenDelim(..) . | CloseDelim(..) . | Literal(..) . | DocComment(..) . | Ident(..) . | Lifetime(..) . | Interpolated(..) . | Eof . ) 97,777 ( 0.00%) } . . pub fn is_like_plus(&self) -> bool { 1,801 ( 0.00%) matches!(self.kind, BinOp(Plus) | BinOpEq(Plus)) 359 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of an expression. 48 ( 0.00%) pub fn can_begin_expr(&self) -> bool { 240 ( 0.00%) match self.uninterpolate().kind { 270 ( 0.00%) Ident(name, is_raw) => 90 ( 0.00%) ident_can_begin_expr(name, self.span, is_raw), // value name or keyword . OpenDelim(..) | // tuple, array or block . Literal(..) | // literal . Not | // operator not . BinOp(Minus) | // unary minus . BinOp(Star) | // dereference . BinOp(Or) | OrOr | // closure . BinOp(And) | // reference . AndAnd | // double reference -- line 371 ---------------------------------------- -- line 376 ---------------------------------------- . Lifetime(..) | // labeled loop . Pound => true, // expression attributes . Interpolated(ref nt) => matches!(**nt, NtLiteral(..) | . NtExpr(..) | . NtBlock(..) | . NtPath(..)), . _ => false, . } 96 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a type. 164 ( 0.00%) pub fn can_begin_type(&self) -> bool { 265 ( 0.00%) match self.uninterpolate().kind { 234 ( 0.00%) Ident(name, is_raw) => 26 ( 0.00%) ident_can_begin_type(name, self.span, is_raw), // type name or keyword . OpenDelim(Paren) | // tuple . OpenDelim(Bracket) | // array . Not | // never . BinOp(Star) | // raw pointer . BinOp(And) | // reference . AndAnd | // double reference . Question | // maybe bound in trait object . Lifetime(..) | // lifetime bound in trait object . Lt | BinOp(Shl) | // associated path . ModSep => true, // global path . Interpolated(ref nt) => matches!(**nt, NtTy(..) | NtPath(..)), . _ => false, . } 246 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a const param. . pub fn can_begin_const_arg(&self) -> bool { 175 ( 0.00%) match self.kind { . OpenDelim(Brace) => true, . Interpolated(ref nt) => matches!(**nt, NtExpr(..) | NtBlock(..) | NtLiteral(..)), 35 ( 0.00%) _ => self.can_begin_literal_maybe_minus(), . } . } . . /// Returns `true` if the token can appear at the start of a generic bound. . pub fn can_begin_bound(&self) -> bool { . self.is_path_start() . || self.is_lifetime() . || self.is_keyword(kw::For) -- line 419 ---------------------------------------- -- line 427 ---------------------------------------- . } . . /// Returns `true` if the token is any literal, a minus (which can prefix a literal, . /// for example a '-42', or one of the boolean idents). . /// . /// In other words, would this token be a valid start of `parse_literal_maybe_minus`? . /// . /// Keep this in sync with and `Lit::from_token`, excluding unary negation. 43 ( 0.00%) pub fn can_begin_literal_maybe_minus(&self) -> bool { 345 ( 0.00%) match self.uninterpolate().kind { . Literal(..) | BinOp(Minus) => true, 104 ( 0.00%) Ident(name, false) if name.is_bool_lit() => true, . Interpolated(ref nt) => match &**nt { . NtLiteral(_) => true, . NtExpr(e) => match &e.kind { . ast::ExprKind::Lit(_) => true, . ast::ExprKind::Unary(ast::UnOp::Neg, e) => { . matches!(&e.kind, ast::ExprKind::Lit(_)) . } . _ => false, . }, . _ => false, . }, . _ => false, . } 86 ( 0.00%) } . . // A convenience function for matching on identifiers during parsing. . // Turns interpolated identifier (`$i: ident`) or lifetime (`$l: lifetime`) token . // into the regular identifier or lifetime token it refers to, . // otherwise returns the original token. 38,487 ( 0.00%) pub fn uninterpolate(&self) -> Cow<'_, Token> { 721,944 ( 0.01%) match &self.kind { 18 ( 0.00%) Interpolated(nt) => match **nt { . NtIdent(ident, is_raw) => { . Cow::Owned(Token::new(Ident(ident.name, is_raw), ident.span)) . } . NtLifetime(ident) => Cow::Owned(Token::new(Lifetime(ident.name), ident.span)), . _ => Cow::Borrowed(self), . }, . _ => Cow::Borrowed(self), . } 38,487 ( 0.00%) } . . /// Returns an identifier if this token is an identifier. 179,606 ( 0.00%) pub fn ident(&self) -> Option<(Ident, /* is_raw */ bool)> { . let token = self.uninterpolate(); 534,827 ( 0.01%) match token.kind { 1,670,628 ( 0.03%) Ident(name, is_raw) => Some((Ident::new(name, token.span), is_raw)), . _ => None, . } 1,229,701 ( 0.02%) } . . /// Returns a lifetime identifier if this token is a lifetime. 277 ( 0.00%) pub fn lifetime(&self) -> Option { . let token = self.uninterpolate(); 876 ( 0.00%) match token.kind { 374 ( 0.00%) Lifetime(name) => Some(Ident::new(name, token.span)), . _ => None, . } 1,939 ( 0.00%) } . . /// Returns `true` if the token is an identifier. . pub fn is_ident(&self) -> bool { . self.ident().is_some() 6,367 ( 0.00%) } . . /// Returns `true` if the token is a lifetime. 161 ( 0.00%) pub fn is_lifetime(&self) -> bool { . self.lifetime().is_some() 322 ( 0.00%) } . . /// Returns `true` if the token is an identifier whose name is the given . /// string slice. 14,541 ( 0.00%) pub fn is_ident_named(&self, name: Symbol) -> bool { . self.ident().map_or(false, |(ident, _)| ident.name == name) 29,082 ( 0.00%) } . . /// Returns `true` if the token is an interpolated path. . fn is_path(&self) -> bool { 60,408 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtPath(..) = **nt { . return true; . } . } . false . } . . /// Would `maybe_whole_expr` in `parser.rs` return `Ok(..)`? -- line 515 ---------------------------------------- -- line 522 ---------------------------------------- . } . } . . false . } . . // Is the token an interpolated block (`$b:block`)? . pub fn is_whole_block(&self) -> bool { 50 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtBlock(..) = **nt { . return true; . } . } . false 25 ( 0.00%) } . . /// Returns `true` if the token is either the `mut` or `const` keyword. . pub fn is_mutability(&self) -> bool { . self.is_keyword(kw::Mut) || self.is_keyword(kw::Const) . } . 270 ( 0.00%) pub fn is_qpath_start(&self) -> bool { 30,474 ( 0.00%) self == &Lt || self == &BinOp(Shl) . } . 60,408 ( 0.00%) pub fn is_path_start(&self) -> bool { 90,538 ( 0.00%) self == &ModSep . || self.is_qpath_start() . || self.is_path() . || self.is_path_segment_keyword() 15,036 ( 0.00%) || self.is_ident() && !self.is_reserved_ident() 75,510 ( 0.00%) } . . /// Returns `true` if the token is a given keyword, `kw`. 28,744 ( 0.00%) pub fn is_keyword(&self, kw: Symbol) -> bool { . self.is_non_raw_ident_where(|id| id.name == kw) 57,488 ( 0.00%) } . 225 ( 0.00%) pub fn is_path_segment_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_path_segment_keyword) . } . . // Returns true for reserved identifiers used internally for elided lifetimes, . // unnamed method parameters, crate root module, error recovery etc. 19 ( 0.00%) pub fn is_special_ident(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_special) . } . . /// Returns `true` if the token is a keyword used in the language. 19 ( 0.00%) pub fn is_used_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_used_keyword) . } . . /// Returns `true` if the token is a keyword reserved for possible future use. 19 ( 0.00%) pub fn is_unused_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_unused_keyword) . } . . /// Returns `true` if the token is either a special identifier or a keyword. . pub fn is_reserved_ident(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_reserved) . } . . /// Returns `true` if the token is the identifier `true` or `false`. 225 ( 0.00%) pub fn is_bool_lit(&self) -> bool { 450 ( 0.00%) self.is_non_raw_ident_where(|id| id.name.is_bool_lit()) . } . . pub fn is_numeric_lit(&self) -> bool { . matches!( . self.kind, . Literal(Lit { kind: LitKind::Integer, .. }) | Literal(Lit { kind: LitKind::Float, .. }) . ) . } . . /// Returns `true` if the token is a non-raw identifier for which `pred` holds. 4 ( 0.00%) pub fn is_non_raw_ident_where(&self, pred: impl FnOnce(Ident) -> bool) -> bool { 764,065 ( 0.02%) match self.ident() { 15,002 ( 0.00%) Some((id, false)) => pred(id), . _ => false, . } 5 ( 0.00%) } . 343,740 ( 0.01%) pub fn glue(&self, joint: &Token) -> Option { 171,870 ( 0.00%) let kind = match self.kind { 309 ( 0.00%) Eq => match joint.kind { . Eq => EqEq, . Gt => FatArrow, . _ => return None, . }, 12 ( 0.00%) Lt => match joint.kind { . Eq => Le, . Lt => BinOp(Shl), . Le => BinOpEq(Shl), . BinOp(Minus) => LArrow, . _ => return None, . }, 57 ( 0.00%) Gt => match joint.kind { . Eq => Ge, . Gt => BinOp(Shr), . Ge => BinOpEq(Shr), . _ => return None, . }, 2 ( 0.00%) Not => match joint.kind { . Eq => Ne, . _ => return None, . }, 586 ( 0.00%) BinOp(op) => match joint.kind { . Eq => BinOpEq(op), 7 ( 0.00%) BinOp(And) if op == And => AndAnd, 15 ( 0.00%) BinOp(Or) if op == Or => OrOr, 35 ( 0.00%) Gt if op == Minus => RArrow, . _ => return None, . }, 42 ( 0.00%) Dot => match joint.kind { . Dot => DotDot, . DotDot => DotDotDot, . _ => return None, . }, 21 ( 0.00%) DotDot => match joint.kind { . Dot => DotDotDot, . Eq => DotDotEq, . _ => return None, . }, 216 ( 0.00%) Colon => match joint.kind { . Colon => ModSep, . _ => return None, . }, . SingleQuote => match joint.kind { . Ident(name, false) => Lifetime(Symbol::intern(&format!("'{}", name))), . _ => return None, . }, . . Le | EqEq | Ne | Ge | AndAnd | OrOr | Tilde | BinOpEq(..) | At | DotDotDot . | DotDotEq | Comma | Semi | ModSep | RArrow | LArrow | FatArrow | Pound | Dollar . | Question | OpenDelim(..) | CloseDelim(..) | Literal(..) | Ident(..) . | Lifetime(..) | Interpolated(..) | DocComment(..) | Eof => return None, . }; . 3,770 ( 0.00%) Some(Token::new(kind, self.span.to(joint.span))) 309,366 ( 0.01%) } . } . . impl PartialEq for Token { . fn eq(&self, rhs: &TokenKind) -> bool { 703,706 ( 0.01%) self.kind == *rhs . } . } . . #[derive(Clone, Encodable, Decodable)] . /// For interpolation during macro expansion. . pub enum Nonterminal { . NtItem(P), . NtBlock(P), -- line 675 ---------------------------------------- -- line 711 ---------------------------------------- . Path, . Vis, . TT, . } . . impl NonterminalKind { . /// The `edition` closure is used to get the edition for the given symbol. Doing . /// `span.edition()` is expensive, so we do it lazily. 56 ( 0.00%) pub fn from_symbol( . symbol: Symbol, . edition: impl FnOnce() -> Edition, . ) -> Option { 120 ( 0.00%) Some(match symbol { . sym::item => NonterminalKind::Item, . sym::block => NonterminalKind::Block, . sym::stmt => NonterminalKind::Stmt, . sym::pat => match edition() { . Edition::Edition2015 | Edition::Edition2018 => { . NonterminalKind::PatParam { inferred: true } . } . Edition::Edition2021 => NonterminalKind::PatWithOr, -- line 731 ---------------------------------------- -- line 737 ---------------------------------------- . sym::lifetime => NonterminalKind::Lifetime, . sym::literal => NonterminalKind::Literal, . sym::meta => NonterminalKind::Meta, . sym::path => NonterminalKind::Path, . sym::vis => NonterminalKind::Vis, . sym::tt => NonterminalKind::TT, . _ => return None, . }) 56 ( 0.00%) } . fn symbol(self) -> Symbol { . match self { . NonterminalKind::Item => sym::item, . NonterminalKind::Block => sym::block, . NonterminalKind::Stmt => sym::stmt, . NonterminalKind::PatParam { inferred: false } => sym::pat_param, . NonterminalKind::PatParam { inferred: true } | NonterminalKind::PatWithOr => sym::pat, . NonterminalKind::Expr => sym::expr, -- line 753 ---------------------------------------- 4,102,058 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs -------------------------------------------------------------------------------- Ir -- line 91 ---------------------------------------- . // maximum of number bytes needed to fill an 8-byte-sized element on which . // SipHash operates. Note that for variable-sized copies which are known to be . // less than 8 bytes, this function will perform more work than necessary unless . // the compiler is able to optimize the extra work away. . #[inline] . unsafe fn copy_nonoverlapping_small(src: *const u8, dst: *mut u8, count: usize) { . debug_assert!(count <= 8); . 53,734 ( 0.00%) if count == 8 { . ptr::copy_nonoverlapping(src, dst, 8); . return; . } . . let mut i = 0; 64,588 ( 0.00%) if i + 3 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 4); . i += 4; . } . 137,280 ( 0.00%) if i + 1 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 2); 18,891 ( 0.00%) i += 2 . } . 64,588 ( 0.00%) if i < count { 32,838 ( 0.00%) *dst.add(i) = *src.add(i); . i += 1; . } . . debug_assert_eq!(i, count); . } . . // # Implementation . // -- line 124 ---------------------------------------- -- line 201 ---------------------------------------- . . hasher . } . . // A specialized write function for values with size <= 8. . #[inline] . fn short_write(&mut self, x: T) { . let size = mem::size_of::(); 943,610 ( 0.02%) let nbuf = self.nbuf; . debug_assert!(size <= 8); . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + size < BUFFER_WITH_SPILL_SIZE); . 6,176,478 ( 0.13%) if nbuf + size < BUFFER_SIZE { . unsafe { . // The memcpy call is optimized away because the size is known. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . ptr::copy_nonoverlapping(&x as *const _ as *const u8, dst, size); . } . 1,872,289 ( 0.04%) self.nbuf = nbuf + size; . . return; . } . 270,457 ( 0.01%) unsafe { self.short_write_process_buffer(x) } . } . . // A specialized write function for values with size <= 8 that should only . // be called when the write would cause the buffer to fill. . // . // SAFETY: the write of `x` into `self.buf` starting at byte offset . // `self.nbuf` must cause `self.buf` to become fully initialized (and not . // overflow) if it wasn't already. . #[inline(never)] 89,533 ( 0.00%) unsafe fn short_write_process_buffer(&mut self, x: T) { . let size = mem::size_of::(); 89,533 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(size <= 8); . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + size >= BUFFER_SIZE); . debug_assert!(nbuf + size < BUFFER_WITH_SPILL_SIZE); . . // Copy first part of input into end of buffer, possibly into spill . // element. The memcpy call is optimized away because the size is known. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . ptr::copy_nonoverlapping(&x as *const _ as *const u8, dst, size); . . // Process buffer. . for i in 0..BUFFER_CAPACITY { 895,330 ( 0.02%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 716,264 ( 0.01%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 805,797 ( 0.02%) self.state.v0 ^= elem; . } . . // Copy remaining input into start of buffer by copying size - 1 . // elements from spill (at most size - 1 bytes could have overflowed . // into the spill). The memcpy call is optimized away because the size . // is known. And the whole copy is optimized away for size == 1. . let src = self.buf.get_unchecked(BUFFER_SPILL_INDEX) as *const _ as *const u8; . ptr::copy_nonoverlapping(src, self.buf.as_mut_ptr() as *mut u8, size - 1); . . // This function should only be called when the write fills the buffer. . // Therefore, when size == 1, the new `self.nbuf` must be zero. The size . // is statically known, so the branch is optimized away. 429,181 ( 0.01%) self.nbuf = if size == 1 { 0 } else { nbuf + size - BUFFER_SIZE }; 358,132 ( 0.01%) self.processed += BUFFER_SIZE; 179,066 ( 0.00%) } . . // A write function for byte slices. . #[inline] . fn slice_write(&mut self, msg: &[u8]) { . let length = msg.len(); 31,731 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(nbuf < BUFFER_SIZE); . 307,823 ( 0.01%) if nbuf + length < BUFFER_SIZE { . unsafe { . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . 76,442 ( 0.00%) if length <= 8 { . copy_nonoverlapping_small(msg.as_ptr(), dst, length); . } else { . // This memcpy is *not* optimized away. . ptr::copy_nonoverlapping(msg.as_ptr(), dst, length); . } . } . 65,896 ( 0.00%) self.nbuf = nbuf + length; . . return; . } . 49,769 ( 0.00%) unsafe { self.slice_write_process_buffer(msg) } . } . . // A write function for byte slices that should only be called when the . // write would cause the buffer to fill. . // . // SAFETY: `self.buf` must be initialized up to the byte offset `self.nbuf`, . // and `msg` must contain enough bytes to initialize the rest of the element . // containing the byte offset `self.nbuf`. . #[inline(never)] 47,730 ( 0.00%) unsafe fn slice_write_process_buffer(&mut self, msg: &[u8]) { . let length = msg.len(); 9,546 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + length >= BUFFER_SIZE); . . // Always copy first part of input into current element of buffer. . // This function should only be called when the write fills the buffer, . // so we know that there is enough input to fill the current element. 28,638 ( 0.00%) let valid_in_elem = nbuf % ELEM_SIZE; 9,546 ( 0.00%) let needed_in_elem = ELEM_SIZE - valid_in_elem; . . let src = msg.as_ptr(); . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . copy_nonoverlapping_small(src, dst, needed_in_elem); . . // Process buffer. . . // Using `nbuf / ELEM_SIZE + 1` rather than `(nbuf + needed_in_elem) / . // ELEM_SIZE` to show the compiler that this loop's upper bound is > 0. . // We know that is true, because last step ensured we have a full . // element in the buffer. 19,092 ( 0.00%) let last = nbuf / ELEM_SIZE + 1; . . for i in 0..last { 71,954 ( 0.00%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 81,500 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 143,908 ( 0.00%) self.state.v0 ^= elem; . } . . // Process the remaining element-sized chunks of input. . let mut processed = needed_in_elem; 19,092 ( 0.00%) let input_left = length - processed; 22,665 ( 0.00%) let elems_left = input_left / ELEM_SIZE; . let extra_bytes_left = input_left % ELEM_SIZE; . . for _ in 0..elems_left { 9,490 ( 0.00%) let elem = (msg.as_ptr().add(processed) as *const u64).read_unaligned().to_le(); 9,490 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 9,490 ( 0.00%) self.state.v0 ^= elem; 18,980 ( 0.00%) processed += ELEM_SIZE; . } . . // Copy remaining input into start of buffer. . let src = msg.as_ptr().add(processed); . let dst = self.buf.as_mut_ptr() as *mut u8; . copy_nonoverlapping_small(src, dst, extra_bytes_left); . 9,546 ( 0.00%) self.nbuf = extra_bytes_left; 47,730 ( 0.00%) self.processed += nbuf + processed; 57,276 ( 0.00%) } . . #[inline] . pub fn finish128(mut self) -> (u64, u64) { . debug_assert!(self.nbuf < BUFFER_SIZE); . . // Process full elements in buffer. 17,502 ( 0.00%) let last = self.nbuf / ELEM_SIZE; . . // Since we're consuming self, avoid updating members for a potential . // performance gain. 23,336 ( 0.00%) let mut state = self.state; . . for i in 0..last { 17,565 ( 0.00%) let elem = unsafe { self.buf.get_unchecked(i).assume_init().to_le() }; 17,565 ( 0.00%) state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut state); 17,565 ( 0.00%) state.v0 ^= elem; . } . . // Get remaining partial element. 11,668 ( 0.00%) let elem = if self.nbuf % ELEM_SIZE != 0 { . unsafe { . // Ensure element is initialized by writing zero bytes. At most . // `ELEM_SIZE - 1` are required given the above check. It's safe . // to write this many because we have the spill and we maintain . // `self.nbuf` such that this write will start before the spill. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(self.nbuf); . ptr::write_bytes(dst, 0, ELEM_SIZE - 1); 4,237 ( 0.00%) self.buf.get_unchecked(last).assume_init().to_le() . } . } else { . 0 . }; . . // Finalize the hash. 14,842 ( 0.00%) let length = self.processed + self.nbuf; 9,516 ( 0.00%) let b: u64 = ((length as u64 & 0xff) << 56) | elem; . 4,758 ( 0.00%) state.v3 ^= b; . Sip24Rounds::c_rounds(&mut state); 4,758 ( 0.00%) state.v0 ^= b; . 4,758 ( 0.00%) state.v2 ^= 0xee; . Sip24Rounds::d_rounds(&mut state); 17,184 ( 0.00%) let _0 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; . 7,664 ( 0.00%) state.v1 ^= 0xdd; . Sip24Rounds::d_rounds(&mut state); 7,664 ( 0.00%) let _1 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; . . (_0, _1) . } . } . . impl Hasher for SipHasher128 { . #[inline] . fn write_u8(&mut self, i: u8) { -- line 414 ---------------------------------------- -- line 471 ---------------------------------------- . } . . #[derive(Debug, Clone, Default)] . struct Sip24Rounds; . . impl Sip24Rounds { . #[inline] . fn c_rounds(state: &mut State) { 3,398,295 ( 0.07%) compress!(state); 3,764,585 ( 0.08%) compress!(state); . } . . #[inline] . fn d_rounds(state: &mut State) { 34,360 ( 0.00%) compress!(state); 34,360 ( 0.00%) compress!(state); 34,360 ( 0.00%) compress!(state); 29,604 ( 0.00%) compress!(state); . } . } 697,395 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 38 ---------------------------------------- . #[derive(Debug)] . pub struct Token { . pub kind: TokenKind, . pub len: usize, . } . . impl Token { . fn new(kind: TokenKind, len: usize) -> Token { 1,686,483 ( 0.03%) Token { kind, len } . } . } . . /// Enum representing common lexeme types. . // perf note: Changing all `usize` to `u32` doesn't change performance. See #77629 334,490 ( 0.01%) #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] . pub enum TokenKind { . // Multi-char tokens: . /// "// comment" . LineComment { doc_style: Option }, . /// `/* block comment */` . /// . /// Block comments can be recursive, so the sequence like `/* /* */` . /// will not be considered terminated and will result in a parsing error. -- line 60 ---------------------------------------- -- line 192 ---------------------------------------- . /// Literal starts with "0x". . Hexadecimal, . /// Literal doesn't contain a prefix. . Decimal, . } . . /// `rustc` allows files to have a shebang, e.g. "#!/usr/bin/rustrun", . /// but shebang isn't a part of rust syntax. 28 ( 0.00%) pub fn strip_shebang(input: &str) -> Option { . // Shebang must start with `#!` literally, without any preceding whitespace. . // For simplicity we consider any line starting with `#!` a shebang, . // regardless of restrictions put on shebangs by specific platforms. . if let Some(input_tail) = input.strip_prefix("#!") { . // Ok, this is a shebang but if the next non-whitespace token is `[`, . // then it may be valid Rust code, so consider it Rust code. . let next_non_whitespace_token = tokenize(input_tail).map(|tok| tok.kind).find(|tok| { . !matches!( -- line 208 ---------------------------------------- -- line 213 ---------------------------------------- . ) . }); . if next_non_whitespace_token != Some(TokenKind::OpenBracket) { . // No other choice than to consider this a shebang. . return Some(2 + input_tail.lines().next().unwrap_or_default().len()); . } . } . None 32 ( 0.00%) } . . /// Parses the first token from the provided input string. 562,161 ( 0.01%) pub fn first_token(input: &str) -> Token { . debug_assert!(!input.is_empty()); 187,387 ( 0.00%) Cursor::new(input).advance_token() 749,548 ( 0.02%) } . . /// Creates an iterator that produces tokens from the input string. . pub fn tokenize(input: &str) -> impl Iterator + '_ { . let mut cursor = Cursor::new(input); . std::iter::from_fn(move || { . if cursor.is_eof() { . None . } else { -- line 235 ---------------------------------------- -- line 243 ---------------------------------------- . /// See [Rust language reference](https://doc.rust-lang.org/reference/whitespace.html) . /// for definitions of these classes. . pub fn is_whitespace(c: char) -> bool { . // This is Pattern_White_Space. . // . // Note that this set is stable (ie, it doesn't change with different . // Unicode versions), so it's ok to just hard-code the values. . 342,154 ( 0.01%) matches!( . c, . // Usual ASCII suspects . '\u{0009}' // \t . | '\u{000A}' // \n . | '\u{000B}' // vertical tab . | '\u{000C}' // form feed . | '\u{000D}' // \r . | '\u{0020}' // space -- line 259 ---------------------------------------- -- line 271 ---------------------------------------- . ) . } . . /// True if `c` is valid as a first character of an identifier. . /// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for . /// a formal definition of valid identifier name. . pub fn is_id_start(c: char) -> bool { . // This is XID_Start OR '_' (which formally is not a XID_Start). 46,632 ( 0.00%) c == '_' || unicode_xid::UnicodeXID::is_xid_start(c) . } . . /// True if `c` is valid as a non-first character of an identifier. . /// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for . /// a formal definition of valid identifier name. . pub fn is_id_continue(c: char) -> bool { . unicode_xid::UnicodeXID::is_xid_continue(c) . } . . /// The passed string is lexically an identifier. 5 ( 0.00%) pub fn is_ident(string: &str) -> bool { . let mut chars = string.chars(); . if let Some(start) = chars.next() { . is_id_start(start) && chars.all(is_id_continue) . } else { . false . } 7 ( 0.00%) } . . impl Cursor<'_> { . /// Parses a token from the input string. 1,499,096 ( 0.03%) fn advance_token(&mut self) -> Token { . let first_char = self.bump().unwrap(); 644,366 ( 0.01%) let token_kind = match first_char { . // Slash, comment or block comment. 736 ( 0.00%) '/' => match self.first() { . '/' => self.line_comment(), . '*' => self.block_comment(), 22 ( 0.00%) _ => Slash, . }, . . // Whitespace sequence. . c if is_whitespace(c) => self.whitespace(), . . // Raw identifier, raw string literal or identifier. 184 ( 0.00%) 'r' => match (self.first(), self.second()) { . ('#', c1) if is_id_start(c1) => self.raw_ident(), . ('#', _) | ('"', _) => { . let (n_hashes, err) = self.raw_double_quoted_string(1); . let suffix_start = self.len_consumed(); . if err.is_none() { . self.eat_literal_suffix(); . } . let kind = RawStr { n_hashes, err }; . Literal { kind, suffix_start } . } . _ => self.ident_or_unknown_prefix(), . }, . . // Byte literal, byte string literal, raw byte string literal or identifier. 158,309 ( 0.00%) 'b' => match (self.first(), self.second()) { . ('\'', _) => { . self.bump(); 33 ( 0.00%) let terminated = self.single_quoted_string(); . let suffix_start = self.len_consumed(); 22 ( 0.00%) if terminated { . self.eat_literal_suffix(); . } . let kind = Byte { terminated }; 22 ( 0.00%) Literal { kind, suffix_start } . } . ('"', _) => { . self.bump(); . let terminated = self.double_quoted_string(); . let suffix_start = self.len_consumed(); . if terminated { . self.eat_literal_suffix(); . } -- line 347 ---------------------------------------- -- line 361 ---------------------------------------- . _ => self.ident_or_unknown_prefix(), . }, . . // Identifier (this should be checked after other variant that can . // start as identifier). . c if is_id_start(c) => self.ident_or_unknown_prefix(), . . // Numeric literal. 277,677 ( 0.01%) c @ '0'..='9' => { . let literal_kind = self.number(c); . let suffix_start = self.len_consumed(); . self.eat_literal_suffix(); 97,155 ( 0.00%) TokenKind::Literal { kind: literal_kind, suffix_start } . } . . // One-symbol tokens. 464 ( 0.00%) ';' => Semi, 47,482 ( 0.00%) ',' => Comma, 442 ( 0.00%) '.' => Dot, 16,168 ( 0.00%) '(' => OpenParen, 16,168 ( 0.00%) ')' => CloseParen, 12,080 ( 0.00%) '{' => OpenBrace, 12,080 ( 0.00%) '}' => CloseBrace, 86 ( 0.00%) '[' => OpenBracket, 86 ( 0.00%) ']' => CloseBracket, 6 ( 0.00%) '@' => At, 44 ( 0.00%) '#' => Pound, . '~' => Tilde, 10 ( 0.00%) '?' => Question, 35,606 ( 0.00%) ':' => Colon, . '$' => Dollar, 524 ( 0.00%) '=' => Eq, 56 ( 0.00%) '!' => Bang, 104 ( 0.00%) '<' => Lt, 282 ( 0.00%) '>' => Gt, 122 ( 0.00%) '-' => Minus, 176 ( 0.00%) '&' => And, 162 ( 0.00%) '|' => Or, 82 ( 0.00%) '+' => Plus, 40 ( 0.00%) '*' => Star, . '^' => Caret, 4 ( 0.00%) '%' => Percent, . . // Lifetime or character literal. 5,913 ( 0.00%) '\'' => self.lifetime_or_char(), . . // String literal. . '"' => { 60 ( 0.00%) let terminated = self.double_quoted_string(); . let suffix_start = self.len_consumed(); 40 ( 0.00%) if terminated { . self.eat_literal_suffix(); . } . let kind = Str { terminated }; 40 ( 0.00%) Literal { kind, suffix_start } . } . // Identifier starting with an emoji. Only lexed for graceful error recovery. . c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => { . self.fake_ident_or_unknown_prefix() . } . _ => Unknown, . }; . Token::new(token_kind, self.len_consumed()) 1,686,483 ( 0.03%) } . . fn line_comment(&mut self) -> TokenKind { . debug_assert!(self.prev() == '/' && self.first() == '/'); . self.bump(); . 596 ( 0.00%) let doc_style = match self.first() { . // `//!` is an inner line doc comment. . '!' => Some(DocStyle::Inner), . // `////` (more than 3 slashes) is not considered a doc comment. 144 ( 0.00%) '/' if self.second() != '/' => Some(DocStyle::Outer), . _ => None, . }; . 7,634 ( 0.00%) self.eat_while(|c| c != '\n'); 519 ( 0.00%) LineComment { doc_style } . } . . fn block_comment(&mut self) -> TokenKind { . debug_assert!(self.prev() == '/' && self.first() == '*'); . self.bump(); . . let doc_style = match self.first() { . // `/*!` is an inner block doc comment. -- line 447 ---------------------------------------- -- line 474 ---------------------------------------- . } . . BlockComment { doc_style, terminated: depth == 0 } . } . . fn whitespace(&mut self) -> TokenKind { . debug_assert!(is_whitespace(self.prev())); . self.eat_while(is_whitespace); 61,184 ( 0.00%) Whitespace . } . . fn raw_ident(&mut self) -> TokenKind { . debug_assert!(self.prev() == 'r' && self.first() == '#' && is_id_start(self.second())); . // Eat "#" symbol. . self.bump(); . // Eat the identifier part of RawIdent. . self.eat_identifier(); . RawIdent . } . 167,245 ( 0.00%) fn ident_or_unknown_prefix(&mut self) -> TokenKind { . debug_assert!(is_id_start(self.prev())); . // Start is already eaten, eat the rest of identifier. 66,898 ( 0.00%) self.eat_while(is_id_continue); . // Known prefixes must have been handled earlier. So if . // we see a prefix here, it is definitely an unknown prefix. 66,898 ( 0.00%) match self.first() { . '#' | '"' | '\'' => UnknownPrefix, 33,449 ( 0.00%) c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => { . self.fake_ident_or_unknown_prefix() . } 33,449 ( 0.00%) _ => Ident, . } 133,796 ( 0.00%) } . . fn fake_ident_or_unknown_prefix(&mut self) -> TokenKind { . // Start is already eaten, eat the rest of identifier. . self.eat_while(|c| { . unicode_xid::UnicodeXID::is_xid_continue(c) . || (!c.is_ascii() && unic_emoji_char::is_emoji(c)) . || c == '\u{200d}' . }); -- line 515 ---------------------------------------- -- line 519 ---------------------------------------- . '#' | '"' | '\'' => UnknownPrefix, . _ => InvalidIdent, . } . } . . fn number(&mut self, first_digit: char) -> LiteralKind { . debug_assert!('0' <= self.prev() && self.prev() <= '9'); . let mut base = Base::Decimal; 38,862 ( 0.00%) if first_digit == '0' { . // Attempt to parse encoding base. 5,728 ( 0.00%) let has_digits = match self.first() { . 'b' => { . base = Base::Binary; . self.bump(); . self.eat_decimal_digits() . } . 'o' => { . base = Base::Octal; . self.bump(); -- line 537 ---------------------------------------- -- line 538 ---------------------------------------- . self.eat_decimal_digits() . } . 'x' => { . base = Base::Hexadecimal; . self.bump(); . self.eat_hexadecimal_digits() . } . // Not a base prefix. 3,435 ( 0.00%) '0'..='9' | '_' | '.' | 'e' | 'E' => { . self.eat_decimal_digits(); . true . } . // Just a 0. . _ => return Int { base, empty_int: false }, . }; . // Base prefix was provided, but there were no digits . // after it, e.g. "0x". -- line 554 ---------------------------------------- -- line 555 ---------------------------------------- . if !has_digits { . return Int { base, empty_int: true }; . } . } else { . // No base prefix, parse number in the usual way. . self.eat_decimal_digits(); . }; . 109,710 ( 0.00%) match self.first() { . // Don't be greedy if this is actually an . // integer literal followed by field/method access or a range pattern . // (`0..2` and `12.foo()`) 6 ( 0.00%) '.' if self.second() != '.' && !is_id_start(self.second()) => { . // might have stuff after the ., and if it does, it needs to start . // with a number . self.bump(); . let mut empty_exponent = false; . if self.first().is_digit(10) { . self.eat_decimal_digits(); . match self.first() { . 'e' | 'E' => { -- line 575 ---------------------------------------- -- line 585 ---------------------------------------- . self.bump(); . let empty_exponent = !self.eat_float_exponent(); . Float { base, empty_exponent } . } . _ => Int { base, empty_int: false }, . } . } . 13,797 ( 0.00%) fn lifetime_or_char(&mut self) -> TokenKind { . debug_assert!(self.prev() == '\''); . 3,942 ( 0.00%) let can_be_a_lifetime = if self.second() == '\'' { . // It's surely not a lifetime. . false . } else { . // If the first symbol is valid for identifier, it can be a lifetime. . // Also check if it's a number for a better error reporting (so '0 will . // be reported as invalid lifetime and not as unterminated char literal). . is_id_start(self.first()) || self.first().is_digit(10) . }; . 1,882 ( 0.00%) if !can_be_a_lifetime { 5,838 ( 0.00%) let terminated = self.single_quoted_string(); . let suffix_start = self.len_consumed(); 3,892 ( 0.00%) if terminated { . self.eat_literal_suffix(); . } . let kind = Char { terminated }; 7,784 ( 0.00%) return Literal { kind, suffix_start }; . } . . // Either a lifetime or a character literal with . // length greater than 1. . . let starts_with_number = self.first().is_digit(10); . . // Skip the literal contents. . // First symbol can be a number (which isn't a valid identifier start), . // so skip it without any checks. . self.bump(); 50 ( 0.00%) self.eat_while(is_id_continue); . . // Check if after skipping literal contents we've met a closing . // single quote (which means that user attempted to create a . // string with single quotes). 50 ( 0.00%) if self.first() == '\'' { . self.bump(); . let kind = Char { terminated: true }; . Literal { kind, suffix_start: self.len_consumed() } . } else { 50 ( 0.00%) Lifetime { starts_with_number } . } 11,826 ( 0.00%) } . . fn single_quoted_string(&mut self) -> bool { . debug_assert!(self.prev() == '\''); . // Check if it's a one-symbol literal. 4,064 ( 0.00%) if self.second() == '\'' && self.first() != '\\' { . self.bump(); . self.bump(); . return true; . } . . // Literal has more than one symbol. . . // Parse until either quotes are terminated or error is detected. . loop { 89,762 ( 0.00%) match self.first() { . // Quotes are terminated, finish parsing. . '\'' => { . self.bump(); . return true; . } . // Probably beginning of the comment, which we don't want to include . // to the error report. . '/' => break, -- line 660 ---------------------------------------- -- line 670 ---------------------------------------- . // Skip the character. . _ => { . self.bump(); . } . } . } . // String was not terminated. . false 1,957 ( 0.00%) } . . /// Eats double-quoted string and returns true . /// if string is terminated. . fn double_quoted_string(&mut self) -> bool { . debug_assert!(self.prev() == '"'); . while let Some(c) = self.bump() { 232,267 ( 0.00%) match c { . '"' => { . return true; . } 42,452 ( 0.00%) '\\' if self.first() == '\\' || self.first() == '"' => { . // Bump again to skip escaped character. . self.bump(); . } . _ => (), . } . } . // End of file reached. . false 20 ( 0.00%) } . . /// Eats the double-quoted string and returns `n_hashes` and an error if encountered. . fn raw_double_quoted_string(&mut self, prefix_len: usize) -> (u16, Option) { . // Wrap the actual function to handle the error with too many hashes. . // This way, it eats the whole raw string. . let (n_hashes, err) = self.raw_string_unvalidated(prefix_len); . // Only up to 65535 `#`s are allowed in raw strings . match u16::try_from(n_hashes) { -- line 706 ---------------------------------------- -- line 773 ---------------------------------------- . max_hashes = n_end_hashes; . } . } . } . . fn eat_decimal_digits(&mut self) -> bool { . let mut has_digits = false; . loop { 74,366 ( 0.00%) match self.first() { . '_' => { . self.bump(); . } 111,549 ( 0.00%) '0'..='9' => { . has_digits = true; . self.bump(); . } . _ => break, . } . } . has_digits 36,572 ( 0.00%) } . . fn eat_hexadecimal_digits(&mut self) -> bool { . let mut has_digits = false; . loop { 6 ( 0.00%) match self.first() { . '_' => { . self.bump(); . } 12 ( 0.00%) '0'..='9' | 'a'..='f' | 'A'..='F' => { . has_digits = true; . self.bump(); . } . _ => break, . } . } . has_digits 2 ( 0.00%) } . . /// Eats the float exponent. Returns true if at least one digit was met, . /// and returns false otherwise. . fn eat_float_exponent(&mut self) -> bool { . debug_assert!(self.prev() == 'e' || self.prev() == 'E'); . if self.first() == '-' || self.first() == '+' { . self.bump(); . } . self.eat_decimal_digits() . } . . // Eats the suffix of the literal, e.g. "_u8". . fn eat_literal_suffix(&mut self) { 42,816 ( 0.00%) self.eat_identifier(); . } . . // Eats the identifier. 64,224 ( 0.00%) fn eat_identifier(&mut self) { . if !is_id_start(self.first()) { . return; . } . self.bump(); . . self.eat_while(is_id_continue); 85,632 ( 0.00%) } . } 2,297,483 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs -------------------------------------------------------------------------------- Ir -- line 27 ---------------------------------------- . impl CacheEntry { . #[inline] . fn update( . &mut self, . new_file_and_idx: Option<(Lrc, usize)>, . pos: BytePos, . time_stamp: usize, . ) { 11,633 ( 0.00%) if let Some((file, file_idx)) = new_file_and_idx { 884 ( 0.00%) self.file = file; 1,066 ( 0.00%) self.file_index = file_idx; . } . 10,801 ( 0.00%) let line_index = self.file.lookup_line(pos).unwrap(); . let line_bounds = self.file.line_bounds(line_index); 22,902 ( 0.00%) self.line_number = line_index + 1; 34,379 ( 0.00%) self.line = line_bounds; . self.touch(time_stamp); . } . . #[inline] . fn touch(&mut self, time_stamp: usize) { 261,515 ( 0.01%) self.time_stamp = time_stamp; . } . } . . #[derive(Clone)] . pub struct CachingSourceMapView<'sm> { . source_map: &'sm SourceMap, . line_cache: [CacheEntry; 3], . time_stamp: usize, . } . . impl<'sm> CachingSourceMapView<'sm> { 518 ( 0.00%) pub fn new(source_map: &'sm SourceMap) -> CachingSourceMapView<'sm> { . let files = source_map.files(); 259 ( 0.00%) let first_file = files[0].clone(); . let entry = CacheEntry { . time_stamp: 0, . line_number: 0, . line: BytePos(0)..BytePos(0), . file: first_file, . file_index: 0, . }; . 1,295 ( 0.00%) CachingSourceMapView { . source_map, 1,813 ( 0.00%) line_cache: [entry.clone(), entry.clone(), entry], . time_stamp: 0, . } 1,036 ( 0.00%) } . . pub fn byte_pos_to_line_and_col( . &mut self, . pos: BytePos, . ) -> Option<(Lrc, usize, BytePos)> { . self.time_stamp += 1; . . // Check if the position is in one of the cached lines -- line 85 ---------------------------------------- -- line 106 ---------------------------------------- . }; . . let cache_entry = &mut self.line_cache[oldest]; . cache_entry.update(new_file_and_idx, pos, self.time_stamp); . . Some((cache_entry.file.clone(), cache_entry.line_number, pos - cache_entry.line.start)) . } . 954,562 ( 0.02%) pub fn span_data_to_lines_and_cols( . &mut self, . span_data: &SpanData, . ) -> Option<(Lrc, usize, BytePos, usize, BytePos)> { 545,464 ( 0.01%) self.time_stamp += 1; . . // Check if lo and hi are in the cached lines. 136,366 ( 0.00%) let lo_cache_idx = self.cache_entry_index(span_data.lo); 136,366 ( 0.00%) let hi_cache_idx = self.cache_entry_index(span_data.hi); . 250,348 ( 0.01%) if lo_cache_idx != -1 && hi_cache_idx != -1 { . // Cache hit for span lo and hi. Check if they belong to the same file. . let result = { 250,298 ( 0.01%) let lo = &self.line_cache[lo_cache_idx as usize]; . let hi = &self.line_cache[hi_cache_idx as usize]; . 750,894 ( 0.02%) if lo.file_index != hi.file_index { . return None; . } . . ( 250,298 ( 0.01%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 125,149 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . ) . }; . 125,149 ( 0.00%) self.line_cache[lo_cache_idx as usize].touch(self.time_stamp); 125,149 ( 0.00%) self.line_cache[hi_cache_idx as usize].touch(self.time_stamp); . 500,596 ( 0.01%) return Some(result); . } . . // No cache hit or cache hit for only one of span lo and hi. 22,384 ( 0.00%) let oldest = if lo_cache_idx != -1 || hi_cache_idx != -1 { . let avoid_idx = if lo_cache_idx != -1 { lo_cache_idx } else { hi_cache_idx }; . self.oldest_cache_entry_index_avoid(avoid_idx as usize) . } else { . self.oldest_cache_entry_index() . }; . . // If the entry doesn't point to the correct file, get the new file and index. . // Return early if the file containing beginning of span doesn't contain end of span. 89,700 ( 0.00%) let new_file_and_idx = if !file_contains(&self.line_cache[oldest].file, span_data.lo) { 2,080 ( 0.00%) let new_file_and_idx = self.file_for_position(span_data.lo)?; 2,496 ( 0.00%) if !file_contains(&new_file_and_idx.0, span_data.hi) { . return None; . } . 1,664 ( 0.00%) Some(new_file_and_idx) . } else { . let file = &self.line_cache[oldest].file; 32,403 ( 0.00%) if !file_contains(&file, span_data.hi) { . return None; . } . 32,403 ( 0.00%) None . }; . . // Update the cache entries. 56,085 ( 0.00%) let (lo_idx, hi_idx) = match (lo_cache_idx, hi_cache_idx) { . // Oldest cache entry is for span_data.lo line. . (-1, -1) => { . let lo = &mut self.line_cache[oldest]; . lo.update(new_file_and_idx, span_data.lo, self.time_stamp); . 32,952 ( 0.00%) if !lo.line.contains(&span_data.hi) { . let new_file_and_idx = Some((lo.file.clone(), lo.file_index)); . let next_oldest = self.oldest_cache_entry_index_avoid(oldest); . let hi = &mut self.line_cache[next_oldest]; . hi.update(new_file_and_idx, span_data.hi, self.time_stamp); . (oldest, next_oldest) . } else { . (oldest, oldest) . } . } . // Oldest cache entry is for span_data.lo line. . (-1, _) => { . let lo = &mut self.line_cache[oldest]; . lo.update(new_file_and_idx, span_data.lo, self.time_stamp); 50 ( 0.00%) let hi = &mut self.line_cache[hi_cache_idx as usize]; 75 ( 0.00%) hi.touch(self.time_stamp); . (oldest, hi_cache_idx as usize) . } . // Oldest cache entry is for span_data.hi line. . (_, -1) => { . let hi = &mut self.line_cache[oldest]; 208 ( 0.00%) hi.update(new_file_and_idx, span_data.hi, self.time_stamp); 416 ( 0.00%) let lo = &mut self.line_cache[lo_cache_idx as usize]; 832 ( 0.00%) lo.touch(self.time_stamp); . (lo_cache_idx as usize, oldest) . } . _ => { . panic!(); . } . }; . . let lo = &self.line_cache[lo_idx]; . let hi = &self.line_cache[hi_idx]; . . // Span lo and hi may equal line end when last line doesn't . // end in newline, hence the inclusive upper bounds below. 22,434 ( 0.00%) assert!(span_data.lo >= lo.line.start); 11,217 ( 0.00%) assert!(span_data.lo <= lo.line.end); 22,434 ( 0.00%) assert!(span_data.hi >= hi.line.start); 11,217 ( 0.00%) assert!(span_data.hi <= hi.line.end); 56,085 ( 0.00%) assert!(lo.file.contains(span_data.lo)); 33,651 ( 0.00%) assert!(lo.file.contains(span_data.hi)); 33,651 ( 0.00%) assert_eq!(lo.file_index, hi.file_index); . 33,651 ( 0.00%) Some(( 11,217 ( 0.00%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 11,217 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . )) 1,227,294 ( 0.02%) } . . fn cache_entry_index(&self, pos: BytePos) -> isize { . for (idx, cache_entry) in self.line_cache.iter().enumerate() { 1,686,155 ( 0.03%) if cache_entry.line.contains(&pos) { . return idx as isize; . } . } . . -1 . } . . fn oldest_cache_entry_index(&self) -> usize { . let mut oldest = 0; . . for idx in 1..self.line_cache.len() { 65,904 ( 0.00%) if self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp { . oldest = idx; . } . } . . oldest . } . . fn oldest_cache_entry_index_avoid(&self, avoid_idx: usize) -> usize { . let mut oldest = if avoid_idx != 0 { 0 } else { 1 }; . . for idx in 0..self.line_cache.len() { 2,827 ( 0.00%) if idx != avoid_idx 1,603 ( 0.00%) && self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp . { . oldest = idx; . } . } . . oldest . } . 2,080 ( 0.00%) fn file_for_position(&self, pos: BytePos) -> Option<(Lrc, usize)> { 416 ( 0.00%) if !self.source_map.files().is_empty() { 832 ( 0.00%) let file_idx = self.source_map.lookup_source_file_idx(pos); . let file = &self.source_map.files()[file_idx]; . 3,328 ( 0.00%) if file_contains(file, pos) { . return Some((file.clone(), file_idx)); . } . } . . None 2,080 ( 0.00%) } . } . . #[inline] . fn file_contains(file: &SourceFile, pos: BytePos) -> bool { . // `SourceMap::lookup_source_file_idx` and `SourceFile::contains` both consider the position . // one past the end of a file to belong to it. Normally, that's what we want. But for the . // purposes of converting a byte position to a line and column number, we can't come up with a . // line and column number if the file is empty, because an empty file doesn't contain any -- line 290 ---------------------------------------- 1,562,914 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs -------------------------------------------------------------------------------- Ir -- line 41 ---------------------------------------- . fn from(val: ScalarMaybeUninit) -> Self { . Immediate::Scalar(val) . } . } . . impl From> for Immediate { . #[inline(always)] . fn from(val: Scalar) -> Self { 13 ( 0.00%) Immediate::Scalar(val.into()) . } . } . . impl<'tcx, Tag: Provenance> Immediate { . pub fn from_pointer(p: Pointer, cx: &impl HasDataLayout) -> Self { . Immediate::Scalar(ScalarMaybeUninit::from_pointer(p, cx)) . } . . pub fn from_maybe_pointer(p: Pointer>, cx: &impl HasDataLayout) -> Self { . Immediate::Scalar(ScalarMaybeUninit::from_maybe_pointer(p, cx)) . } . 244 ( 0.00%) pub fn new_slice(val: Scalar, len: u64, cx: &impl HasDataLayout) -> Self { 735 ( 0.00%) Immediate::ScalarPair(val.into(), Scalar::from_machine_usize(len, cx).into()) 366 ( 0.00%) } . . pub fn new_dyn_trait( . val: Scalar, . vtable: Pointer>, . cx: &impl HasDataLayout, . ) -> Self { . Immediate::ScalarPair(val.into(), ScalarMaybeUninit::from_maybe_pointer(vtable, cx)) . } . . #[inline] . pub fn to_scalar_or_uninit(self) -> ScalarMaybeUninit { 166,118 ( 0.00%) match self { 235,052 ( 0.00%) Immediate::Scalar(val) => val, . Immediate::ScalarPair(..) => bug!("Got a scalar pair where a scalar was expected"), . } . } . . #[inline] 4 ( 0.00%) pub fn to_scalar(self) -> InterpResult<'tcx, Scalar> { . self.to_scalar_or_uninit().check_init() 6 ( 0.00%) } . . #[inline] . pub fn to_scalar_pair(self) -> InterpResult<'tcx, (Scalar, Scalar)> { . match self { . Immediate::ScalarPair(val1, val2) => Ok((val1.check_init()?, val2.check_init()?)), . Immediate::Scalar(..) => { . bug!("Got a scalar where a scalar pair was expected") . } -- line 93 ---------------------------------------- -- line 159 ---------------------------------------- . fn deref(&self) -> &Immediate { . &self.imm . } . } . . /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate, . /// or still in memory. The latter is an optimization, to delay reading that chunk of . /// memory and to avoid having to store arbitrary-sized data here. 105 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, HashStable, Hash, Debug)] . pub enum Operand { . Immediate(Immediate), . Indirect(MemPlace), . } . . #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] . pub struct OpTy<'tcx, Tag: Provenance = AllocId> { . op: Operand, // Keep this private; it helps enforce invariants. -- line 175 ---------------------------------------- -- line 185 ---------------------------------------- . fn deref(&self) -> &Operand { . &self.op . } . } . . impl<'tcx, Tag: Provenance> From> for OpTy<'tcx, Tag> { . #[inline(always)] . fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self { 2,294 ( 0.00%) OpTy { op: Operand::Indirect(*mplace), layout: mplace.layout } . } . } . . impl<'tcx, Tag: Provenance> From<&'_ MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> { . #[inline(always)] . fn from(mplace: &MPlaceTy<'tcx, Tag>) -> Self { . OpTy { op: Operand::Indirect(**mplace), layout: mplace.layout } . } -- line 201 ---------------------------------------- -- line 206 ---------------------------------------- . fn from(val: ImmTy<'tcx, Tag>) -> Self { . OpTy { op: Operand::Immediate(val.imm), layout: val.layout } . } . } . . impl<'tcx, Tag: Provenance> ImmTy<'tcx, Tag> { . #[inline] . pub fn from_scalar(val: Scalar, layout: TyAndLayout<'tcx>) -> Self { 265 ( 0.00%) ImmTy { imm: val.into(), layout } . } . . #[inline] . pub fn from_immediate(imm: Immediate, layout: TyAndLayout<'tcx>) -> Self { . ImmTy { imm, layout } . } . . #[inline] . pub fn try_from_uint(i: impl Into, layout: TyAndLayout<'tcx>) -> Option { . Some(Self::from_scalar(Scalar::try_from_uint(i, layout.size)?, layout)) . } . #[inline] 28 ( 0.00%) pub fn from_uint(i: impl Into, layout: TyAndLayout<'tcx>) -> Self { 24 ( 0.00%) Self::from_scalar(Scalar::from_uint(i, layout.size), layout) 28 ( 0.00%) } . . #[inline] . pub fn try_from_int(i: impl Into, layout: TyAndLayout<'tcx>) -> Option { . Some(Self::from_scalar(Scalar::try_from_int(i, layout.size)?, layout)) . } . . #[inline] . pub fn from_int(i: impl Into, layout: TyAndLayout<'tcx>) -> Self { -- line 237 ---------------------------------------- -- line 248 ---------------------------------------- . . impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { . /// Try reading an immediate in memory; this is interesting particularly for `ScalarPair`. . /// Returns `None` if the layout does not permit loading this as a value. . fn try_read_immediate_from_mplace( . &self, . mplace: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Option>> { 126,948 ( 0.00%) if mplace.layout.is_unsized() { . // Don't touch unsized . return Ok(None); . } . 297,474 ( 0.01%) let alloc = match self.get_alloc(mplace)? { 495,730 ( 0.01%) Some(ptr) => ptr, . None => { . return Ok(Some(ImmTy { . // zero-sized type 108 ( 0.00%) imm: Scalar::ZST.into(), . layout: mplace.layout, . })); . } . }; . 788,818 ( 0.02%) match mplace.layout.abi { . Abi::Scalar(..) => { 83,088 ( 0.00%) let scalar = alloc.read_scalar(alloc_range(Size::ZERO, mplace.layout.size))?; . Ok(Some(ImmTy { imm: scalar.into(), layout: mplace.layout })) . } 6,525 ( 0.00%) Abi::ScalarPair(a, b) => { . // We checked `ptr_align` above, so all fields will have the alignment they need. . // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`, . // which `ptr.offset(b_offset)` cannot possibly fail to satisfy. . let (a, b) = (a.value, b.value); . let (a_size, b_size) = (a.size(self), b.size(self)); . let b_offset = a_size.align_to(b.align(self).abi); 4,350 ( 0.00%) assert!(b_offset.bytes() > 0); // we later use the offset to tell apart the fields . let a_val = alloc.read_scalar(alloc_range(Size::ZERO, a_size))?; 6,525 ( 0.00%) let b_val = alloc.read_scalar(alloc_range(b_offset, b_size))?; 10,875 ( 0.00%) Ok(Some(ImmTy { imm: Immediate::ScalarPair(a_val, b_val), layout: mplace.layout })) . } . _ => Ok(None), . } . } . . /// Try returning an immediate for the operand. . /// If the layout does not permit loading this as an immediate, return where in memory . /// we can find the data. . /// Note that for a given layout, this operation will either always fail or always . /// succeed! Whether it succeeds depends on whether the layout can be represented . /// in an `Immediate`, not on which data is stored there currently. 1,092,843 ( 0.02%) pub fn try_read_immediate( . &self, . src: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Result, MPlaceTy<'tcx, M::PointerTag>>> { 2,185,686 ( 0.04%) Ok(match src.try_as_mplace() { . Ok(ref mplace) => { 198,316 ( 0.00%) if let Some(val) = self.try_read_immediate_from_mplace(mplace)? { . Ok(val) . } else { . Err(*mplace) . } . } 222,690 ( 0.00%) Err(val) => Ok(val), . }) 1,092,843 ( 0.02%) } . . /// Read an immediate from a place, asserting that that is possible with the given layout. . #[inline(always)] . pub fn read_immediate( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> { 275,800 ( 0.01%) if let Ok(imm) = self.try_read_immediate(op)? { 475,234 ( 0.01%) Ok(imm) . } else { . span_bug!(self.cur_span(), "primitive read failed for type: {:?}", op.layout.ty); . } . } . . /// Read a scalar from a place 646,393 ( 0.01%) pub fn read_scalar( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, ScalarMaybeUninit> { 58,763 ( 0.00%) Ok(self.read_immediate(op)?.to_scalar_or_uninit()) 528,867 ( 0.01%) } . . /// Read a pointer from a place. . pub fn read_pointer( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Pointer>> { . Ok(self.scalar_to_ptr(self.read_scalar(op)?.check_init()?)) . } -- line 342 ---------------------------------------- -- line 345 ---------------------------------------- . pub fn read_str(&self, mplace: &MPlaceTy<'tcx, M::PointerTag>) -> InterpResult<'tcx, &str> { . let len = mplace.len(self)?; . let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len))?; . let str = std::str::from_utf8(bytes).map_err(|err| err_ub!(InvalidStr(err)))?; . Ok(str) . } . . /// Projection functions 945,370 ( 0.02%) pub fn operand_field( . &self, . op: &OpTy<'tcx, M::PointerTag>, . field: usize, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . let base = match op.try_as_mplace() { . Ok(ref mplace) => { . // We can reuse the mplace field computation logic for indirect operands. . let field = self.mplace_field(mplace, field)?; 1,039,621 ( 0.02%) return Ok(field.into()); . } 182 ( 0.00%) Err(value) => value, . }; . 100 ( 0.00%) let field_layout = op.layout.field(self, field); . if field_layout.is_zst() { . let immediate = Scalar::ZST.into(); . return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout }); . } 78 ( 0.00%) let offset = op.layout.fields.offset(field); 52 ( 0.00%) let immediate = match *base { . // the field covers the entire type 156 ( 0.00%) _ if offset.bytes() == 0 && field_layout.size == op.layout.size => *base, . // extract fields from types with `ScalarPair` ABI . Immediate::ScalarPair(a, b) => { 26 ( 0.00%) let val = if offset.bytes() == 0 { a } else { b }; . Immediate::from(val) . } . Immediate::Scalar(val) => span_bug!( . self.cur_span(), . "field access on non aggregate {:#?}, {:#?}", . val, . op.layout . ), . }; 364 ( 0.00%) Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout }) 850,833 ( 0.02%) } . . pub fn operand_index( . &self, . op: &OpTy<'tcx, M::PointerTag>, . index: u64, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . if let Ok(index) = usize::try_from(index) { . // We can just treat this as a field. -- line 397 ---------------------------------------- -- line 398 ---------------------------------------- . self.operand_field(op, index) . } else { . // Indexing into a big array. This must be an mplace. . let mplace = op.assert_mem_place(); . Ok(self.mplace_index(&mplace, index)?.into()) . } . } . 177,287 ( 0.00%) pub fn operand_downcast( . &self, . op: &OpTy<'tcx, M::PointerTag>, . variant: VariantIdx, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . // Downcasts only change the layout 273,989 ( 0.01%) Ok(match op.try_as_mplace() { 161,170 ( 0.00%) Ok(ref mplace) => self.mplace_downcast(mplace, variant)?.into(), . Err(..) => { . let layout = op.layout.for_variant(self, variant); . OpTy { layout, ..*op } . } . }) 145,053 ( 0.00%) } . 368 ( 0.00%) pub fn operand_projection( . &self, . base: &OpTy<'tcx, M::PointerTag>, . proj_elem: mir::PlaceElem<'tcx>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . use rustc_middle::mir::ProjectionElem::*; 1,439 ( 0.00%) Ok(match proj_elem { 162 ( 0.00%) Field(field, _) => self.operand_field(base, field.index())?, . Downcast(_, variant) => self.operand_downcast(base, variant)?, 35 ( 0.00%) Deref => self.deref_operand(base)?.into(), . Subslice { .. } | ConstantIndex { .. } | Index(_) => { . // The rest should only occur as mplace, we do not use Immediates for types . // allowing such operations. This matches place_projection forcing an allocation. . let mplace = base.assert_mem_place(); 24 ( 0.00%) self.mplace_projection(&mplace, proj_elem)?.into() . } . }) 368 ( 0.00%) } . . /// Converts a repr(simd) operand into an operand where `place_index` accesses the SIMD elements. . /// Also returns the number of elements. . pub fn operand_to_simd( . &self, . base: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, u64)> { . // Basically we just transmute this place into an array following simd_size_and_type. -- line 446 ---------------------------------------- -- line 449 ---------------------------------------- . self.mplace_to_simd(&base.assert_mem_place()) . } . . /// Read from a local. Will not actually access the local if reading from a ZST. . /// Will not access memory, instead an indirect `Operand` is returned. . /// . /// This is public because it is used by [priroda](https://github.com/oli-obk/priroda) to get an . /// OpTy from a local 163,407 ( 0.00%) pub fn access_local( . &self, . frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>, . local: mir::Local, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . let layout = self.layout_of_local(frame, local, layout)?; 13,979 ( 0.00%) let op = if layout.is_zst() { . // Do not read from ZST, they might not be initialized 75 ( 0.00%) Operand::Immediate(Scalar::ZST.into()) . } else { 4,962 ( 0.00%) M::access_local(&self, frame, local)? . }; 212,849 ( 0.00%) Ok(OpTy { op, layout }) 142,499 ( 0.00%) } . . /// Every place can be read from, so we can turn them into an operand. . /// This will definitely return `Indirect` if the place is a `Ptr`, i.e., this . /// will never actually read from memory. . #[inline(always)] . pub fn place_to_op( . &self, . place: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { 54 ( 0.00%) let op = match **place { 21 ( 0.00%) Place::Ptr(mplace) => Operand::Indirect(mplace), . Place::Local { frame, local } => { 216 ( 0.00%) *self.access_local(&self.stack()[frame], local, None)? . } . }; 70 ( 0.00%) Ok(OpTy { op, layout: place.layout }) . } . . // Evaluate a place with the goal of reading from it. This lets us sometimes . // avoid allocations. 139,616 ( 0.00%) pub fn eval_place_to_op( . &self, . place: mir::Place<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . // Do not use the layout passed in as argument if the base we are looking at . // here is not the entire place. 17,452 ( 0.00%) let layout = if place.projection.is_empty() { layout } else { None }; . 52,356 ( 0.00%) let base_op = self.access_local(self.frame(), place.local, layout)?; . . let op = place . .projection . .iter() 828 ( 0.00%) .try_fold(base_op, |op, elem| self.operand_projection(&op, elem))?; . . trace!("eval_place_to_op: got {:?}", *op); . // Sanity-check the type we ended up with. . debug_assert!(mir_assign_valid_types( . *self.tcx, . self.param_env, . self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions( . place.ty(&self.frame().body.local_decls, *self.tcx).ty . )?)?, . op.layout, . )); 48,699 ( 0.00%) Ok(op) 157,068 ( 0.00%) } . . /// Evaluate the operand, returning a place where you can then find the data. . /// If you already know the layout, you can save two table lookups . /// by passing it in here. . #[inline] 335,050 ( 0.01%) pub fn eval_operand( . &self, . mir_op: &mir::Operand<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . use rustc_middle::mir::Operand::*; 77,584 ( 0.00%) let op = match *mir_op { . // FIXME: do some more logic on `move` to invalidate the old location 84,112 ( 0.00%) Copy(place) | Move(place) => self.eval_place_to_op(place, layout)?, . . Constant(ref constant) => { . let val = 325,229 ( 0.01%) self.subst_from_current_frame_and_normalize_erasing_regions(constant.literal)?; . // This can still fail: . // * During ConstProp, with `TooGeneric` or since the `requried_consts` were not all . // checked yet. . // * During CTFE, since promoteds in `const`/`static` initializer bodies can fail. . 969 ( 0.00%) self.mir_const_to_op(&val, layout)? . } . }; . trace!("{:?}: {:?}", mir_op, *op); 487,690 ( 0.01%) Ok(op) 223,375 ( 0.00%) } . . /// Evaluate a bunch of operands at once . pub(super) fn eval_operands( . &self, . ops: &[mir::Operand<'tcx>], . ) -> InterpResult<'tcx, Vec>> { . ops.iter().map(|op| self.eval_operand(op, None)).collect() . } . . // Used when the miri-engine runs into a constant and for extracting information from constants . // in patterns via the `const_eval` module . /// The `val` and `layout` are assumed to already be in our interpreter . /// "universe" (param_env). 256,764 ( 0.01%) pub fn const_to_op( . &self, . val: &ty::Const<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { 111,275 ( 0.00%) match val.val { . ty::ConstKind::Param(_) | ty::ConstKind::Bound(..) => throw_inval!(TooGeneric), . ty::ConstKind::Error(_) => throw_inval!(AlreadyReported(ErrorReported)), 76 ( 0.00%) ty::ConstKind::Unevaluated(uv) => { . let instance = self.resolve(uv.def, uv.substs)?; 209 ( 0.00%) Ok(self.eval_to_allocation(GlobalId { instance, promoted: uv.promoted })?.into()) . } . ty::ConstKind::Infer(..) | ty::ConstKind::Placeholder(..) => { . span_bug!(self.cur_span(), "const_to_op: Unexpected ConstKind {:?}", val) . } 219,004 ( 0.00%) ty::ConstKind::Value(val_val) => self.const_val_to_op(val_val, val.ty, layout), . } 192,573 ( 0.00%) } . 9,438 ( 0.00%) pub fn mir_const_to_op( . &self, . val: &mir::ConstantKind<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { 44,510 ( 0.00%) match val { 87,304 ( 0.00%) mir::ConstantKind::Ty(ct) => self.const_to_op(ct, layout), . mir::ConstantKind::Val(val, ty) => self.const_val_to_op(*val, ty, layout), . } 7,722 ( 0.00%) } . 222,360 ( 0.00%) crate fn const_val_to_op( . &self, . val_val: ConstValue<'tcx>, . ty: Ty<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . // Other cases need layout. . let tag_scalar = |scalar| -> InterpResult<'tcx, _> { 132,936 ( 0.00%) Ok(match scalar { . Scalar::Ptr(ptr, size) => Scalar::Ptr(self.global_base_pointer(ptr)?, size), 66,237 ( 0.00%) Scalar::Int(int) => Scalar::Int(int), . }) . }; 2,202 ( 0.00%) let layout = from_known_layout(self.tcx, self.param_env, layout, || self.layout_of(ty))?; 66,868 ( 0.00%) let op = match val_val { 12 ( 0.00%) ConstValue::ByRef { alloc, offset } => { 12 ( 0.00%) let id = self.tcx.create_memory_alloc(alloc); . // We rely on mutability being set correctly in that allocation to prevent writes . // where none should happen. . let ptr = self.global_base_pointer(Pointer::new(id, offset))?; 24 ( 0.00%) Operand::Indirect(MemPlace::from_ptr(ptr.into(), layout.align.abi)) . } 200,177 ( 0.00%) ConstValue::Scalar(x) => Operand::Immediate(tag_scalar(x)?.into()), 222 ( 0.00%) ConstValue::Slice { data, start, end } => { . // We rely on mutability being set correctly in `data` to prevent writes . // where none should happen. . let ptr = Pointer::new( 222 ( 0.00%) self.tcx.create_memory_alloc(data), . Size::from_bytes(start), // offset: `start` . ); 1,403 ( 0.00%) Operand::Immediate(Immediate::new_slice( . Scalar::from_pointer(self.global_base_pointer(ptr)?, &*self.tcx), . u64::try_from(end.checked_sub(start).unwrap()).unwrap(), // len: `end - start` . self, . )) . } . }; 466,956 ( 0.01%) Ok(OpTy { op, layout }) 177,888 ( 0.00%) } . . /// Read discriminant, return the runtime value as well as the variant index. . /// Can also legally be called on non-enums (e.g. through the discriminant_value intrinsic)! 241,830 ( 0.00%) pub fn read_discriminant( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, (Scalar, VariantIdx)> { . trace!("read_discriminant_value {:#?}", op.layout); . // Get type and layout of the discriminant. 290,196 ( 0.01%) let discr_layout = self.layout_of(op.layout.ty.discriminant_ty(*self.tcx))?; . trace!("discriminant type: {:?}", discr_layout.ty); . . // We use "discriminant" to refer to the value associated with a particular enum variant. . // This is not to be confused with its "variant index", which is just determining its position in the . // declared list of variants -- they can differ with explicitly assigned discriminants. . // We use "tag" to refer to how the discriminant is encoded in memory, which can be either . // straight-forward (`TagEncoding::Direct`) or with a niche (`TagEncoding::Niche`). 72,549 ( 0.00%) let (tag_scalar_layout, tag_encoding, tag_field) = match op.layout.variants { . Variants::Single { index } => { . let discr = match op.layout.ty.discriminant_for_variant(*self.tcx, index) { . Some(discr) => { . // This type actually has discriminants. . assert_eq!(discr.ty, discr_layout.ty); . Scalar::from_uint(discr.val, discr_layout.size) . } . None => { . // On a type without actual discriminants, variant is 0. . assert_eq!(index.as_u32(), 0); . Scalar::from_uint(index.as_u32(), discr_layout.size) . } . }; . return Ok((discr, index)); . } 48,366 ( 0.00%) Variants::Multiple { tag, ref tag_encoding, tag_field, .. } => { . (tag, tag_encoding, tag_field) . } . }; . . // There are *three* layouts that come into play here: . // - The discriminant has a type for typechecking. This is `discr_layout`, and is used for . // the `Scalar` we return. . // - The tag (encoded discriminant) has layout `tag_layout`. This is always an integer type, . // and used to interpret the value we read from the tag field. . // For the return value, a cast to `discr_layout` is performed. . // - The field storing the tag has a layout, which is very similar to `tag_layout` but . // may be a pointer. This is `tag_val.layout`; we just use it for sanity checks. . . // Get layout for tag. 145,098 ( 0.00%) let tag_layout = self.layout_of(tag_scalar_layout.value.to_int_ty(*self.tcx))?; . . // Read tag and sanity-check `tag_layout`. 169,281 ( 0.00%) let tag_val = self.read_immediate(&self.operand_field(op, tag_field)?)?; 48,366 ( 0.00%) assert_eq!(tag_layout.size, tag_val.layout.size); 193,464 ( 0.00%) assert_eq!(tag_layout.abi.is_signed(), tag_val.layout.abi.is_signed()); . let tag_val = tag_val.to_scalar()?; . trace!("tag value: {:?}", tag_val); . . // Figure out which discriminant and variant this corresponds to. 217,647 ( 0.00%) Ok(match *tag_encoding { . TagEncoding::Direct => { 483,620 ( 0.01%) let tag_bits = tag_val . .try_to_int() . .map_err(|dbg_val| err_ub!(InvalidTag(dbg_val)))? . .assert_bits(tag_layout.size); . // Cast bits from tag layout to discriminant layout. 193,448 ( 0.00%) let discr_val = self.cast_from_scalar(tag_bits, tag_layout, discr_layout.ty); 48,362 ( 0.00%) let discr_bits = discr_val.assert_bits(discr_layout.size); . // Convert discriminant to variant index, and catch invalid discriminants. 120,905 ( 0.00%) let index = match *op.layout.ty.kind() { 24,181 ( 0.00%) ty::Adt(adt, _) => { 458,814 ( 0.01%) adt.discriminants(*self.tcx).find(|(_, var)| var.val == discr_bits) . } . ty::Generator(def_id, substs, _) => { . let substs = substs.as_generator(); . substs . .discriminants(def_id, *self.tcx) . .find(|(_, var)| var.val == discr_bits) . } . _ => span_bug!(self.cur_span(), "tagged layout for non-adt non-generator"), . } . .ok_or_else(|| err_ub!(InvalidTag(Scalar::from_uint(tag_bits, tag_layout.size))))?; . // Return the cast value, and the index. 96,724 ( 0.00%) (discr_val, index.0) . } 12 ( 0.00%) TagEncoding::Niche { dataful_variant, ref niche_variants, niche_start } => { . // Compute the variant this niche value/"tag" corresponds to. With niche layout, . // discriminant (encoded in niche/tag) and variant index are the same. . let variants_start = niche_variants.start().as_u32(); 4 ( 0.00%) let variants_end = niche_variants.end().as_u32(); 8 ( 0.00%) let variant = match tag_val.try_to_int() { . Err(dbg_val) => { . // So this is a pointer then, and casting to an int failed. . // Can only happen during CTFE. . let ptr = self.scalar_to_ptr(tag_val); . // The niche must be just 0, and the ptr not null, then we know this is . // okay. Everything else, we conservatively reject. . let ptr_valid = niche_start == 0 . && variants_start == variants_end . && !self.memory.ptr_may_be_null(ptr); . if !ptr_valid { . throw_ub!(InvalidTag(dbg_val)) . } . dataful_variant . } . Ok(tag_bits) => { 34 ( 0.00%) let tag_bits = tag_bits.assert_bits(tag_layout.size); . // We need to use machine arithmetic to get the relative variant idx: . // variant_index_relative = tag_val - niche_start_val 12 ( 0.00%) let tag_val = ImmTy::from_uint(tag_bits, tag_layout); 14 ( 0.00%) let niche_start_val = ImmTy::from_uint(niche_start, tag_layout); . let variant_index_relative_val = 8 ( 0.00%) self.binary_op(mir::BinOp::Sub, &tag_val, &niche_start_val)?; 14 ( 0.00%) let variant_index_relative = variant_index_relative_val . .to_scalar()? 4 ( 0.00%) .assert_bits(tag_val.layout.size); . // Check if this is in the range that indicates an actual discriminant. 10 ( 0.00%) if variant_index_relative <= u128::from(variants_end - variants_start) { . let variant_index_relative = u32::try_from(variant_index_relative) . .expect("we checked that this fits into a u32"); . // Then computing the absolute variant idx should not overflow any more. . let variant_index = variants_start . .checked_add(variant_index_relative) . .expect("overflow computing absolute variant idx"); 2 ( 0.00%) let variants_len = op . .layout . .ty . .ty_adt_def() . .expect("tagged layout for non adt") . .variants . .len(); 4 ( 0.00%) assert!(usize::try_from(variant_index).unwrap() < variants_len); . VariantIdx::from_u32(variant_index) . } else { . dataful_variant . } . } . }; . // Compute the size of the scalar we need to return. . // No need to cast, because the variant index directly serves as discriminant and is . // encoded in the tag. 14 ( 0.00%) (Scalar::from_uint(variant.as_u32(), discr_layout.size), variant) . } . }) 217,647 ( 0.00%) } . } 3,112,091 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs -------------------------------------------------------------------------------- Ir -- line 141 ---------------------------------------- . /// ``` . /// let a = [1, 2, 3]; . /// assert!(!a.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.39.0")] . #[inline] . pub const fn is_empty(&self) -> bool { 1,142,813 ( 0.02%) self.len() == 0 . } . . /// Returns the first element of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; -- line 157 ---------------------------------------- -- line 159 ---------------------------------------- . /// . /// let w: &[i32] = &[]; . /// assert_eq!(None, w.first()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn first(&self) -> Option<&T> { 6,663 ( 0.00%) if let [first, ..] = self { Some(first) } else { None } . } . . /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 175 ---------------------------------------- -- line 178 ---------------------------------------- . /// *first = 5; . /// } . /// assert_eq!(x, &[5, 1, 2]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")] . #[inline] . pub const fn first_mut(&mut self) -> Option<&mut T> { 480 ( 0.00%) if let [first, ..] = self { Some(first) } else { None } . } . . /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &[0, 1, 2]; -- line 194 ---------------------------------------- -- line 237 ---------------------------------------- . /// assert_eq!(last, &2); . /// assert_eq!(elements, &[0, 1]); . /// } . /// ``` . #[stable(feature = "slice_splits", since = "1.5.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn split_last(&self) -> Option<(&T, &[T])> { 20,129 ( 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,009,630 ( 0.02%) 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> { 212,097 ( 0.00%) if let [.., last] = self { Some(last) } else { None } . } . . /// Returns a reference to an element or subslice depending on the type of . /// index. . /// . /// - If given a position, returns a reference to the element at that . /// position or `None` if out of bounds. . /// - If given a range, returns the subslice corresponding to that range, -- line 311 ---------------------------------------- -- line 448 ---------------------------------------- . /// } . /// ``` . /// . /// [`as_mut_ptr`]: slice::as_mut_ptr . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")] . #[inline] . pub const fn as_ptr(&self) -> *const T { 1,022,592 ( 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 { 4 ( 0.00%) self as *mut [T] as *mut T . } . . /// Returns the two raw pointers spanning the slice. . /// . /// The returned range is half-open, which means that the end pointer . /// points *one past* the last element of the slice. This way, an empty . /// slice is represented by two equal pointers, and the difference between . /// the two pointers represents the size of the slice. -- line 492 ---------------------------------------- -- line 582 ---------------------------------------- . /// v.swap(2, 4); . /// assert!(v == ["a", "b", "e", "d", "c"]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] . #[inline] . #[track_caller] . pub const fn swap(&mut self, a: usize, b: usize) { 39,926 ( 0.00%) let _ = &self[a]; 51,723 ( 0.00%) let _ = &self[b]; . . // SAFETY: we just checked that both `a` and `b` are in bounds . unsafe { self.swap_unchecked(a, b) } . } . . /// Swaps two elements in the slice, without doing bounds checking. . /// . /// For a safe alternative see [`swap`]. -- line 599 ---------------------------------------- -- line 677 ---------------------------------------- . . // Because this function is first compiled in isolation, . // this check tells LLVM that the indexing below is . // in-bounds. Then after inlining -- once the actual . // lengths of the slices are known -- it's removed. . let (a, b) = (&mut a[..n], &mut b[..n]); . . for i in 0..n { 4,530 ( 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]) { 7,904 ( 0.00%) assert!(mid <= self.len()); . // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which . // fulfills the requirements of `from_raw_parts_mut`. . unsafe { self.split_at_mut_unchecked(mid) } . } . . /// Divides one slice into two at an index, without doing bounds checking. . /// . /// The first will contain all indices from `[0, mid)` (excluding -- line 1546 ---------------------------------------- -- line 1628 ---------------------------------------- . pub unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut [T], &mut [T]) { . let len = self.len(); . let ptr = self.as_mut_ptr(); . . // SAFETY: Caller has to check that `0 <= mid <= self.len()`. . // . // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference . // is fine. 1,909 ( 0.00%) unsafe { (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid)) } . } . . /// Divides one slice into an array and a remainder slice at an index. . /// . /// The array will contain all indices from `[0, N)` (excluding . /// the index `N` itself) and the slice will contain all . /// indices from `[N, len)` (excluding the index `len` itself). . /// -- line 1644 ---------------------------------------- -- line 2113 ---------------------------------------- . /// assert!(!v.iter().any(|e| e == "hi")); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn contains(&self, x: &T) -> bool . where . T: PartialEq, . { 80 ( 0.00%) cmp::SliceContains::slice_contains(x, self) . } . . /// Returns `true` if `needle` is a prefix of the slice. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; -- line 2129 ---------------------------------------- -- line 2142 ---------------------------------------- . /// assert!(v.starts_with(&[])); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn starts_with(&self, needle: &[T]) -> bool . where . T: PartialEq, . { . let n = needle.len(); 10,123 ( 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()); 23,471 ( 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; 4,940,227 ( 0.10%) while left < right { 6,212,018 ( 0.13%) 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. 745,746 ( 0.02%) 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. 1,581,120 ( 0.03%) if cmp == Less { 4,219,199 ( 0.09%) left = mid + 1; 694,645 ( 0.01%) } else if cmp == Greater { . right = mid; . } else { . // SAFETY: same as the `get_unchecked` above . unsafe { crate::intrinsics::assume(mid < self.len()) }; . return Ok(mid); . } . 4,715,469 ( 0.10%) 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, . ); . } . 35,900 ( 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! 3,898 ( 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::()) }; 3,898 ( 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), 3,898 ( 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 ---------------------------------------- 3,251,250 ( 0.07%) -------------------------------------------------------------------------------- -- 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 . // . 4,151,770 ( 0.08%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 3,113,826 ( 0.06%) 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. 119,652 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 179,478 ( 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) { 1,067,845 ( 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 { 212,036 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 424,072 ( 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_parse/src/lexer/mod.rs -------------------------------------------------------------------------------- Ir -- line 26 ---------------------------------------- . pub struct UnmatchedBrace { . pub expected_delim: token::DelimToken, . pub found_delim: Option, . pub found_span: Span, . pub unclosed_span: Option, . pub candidate_span: Option, . } . 56 ( 0.00%) crate fn parse_token_trees<'a>( . sess: &'a ParseSess, . src: &'a str, . start_pos: BytePos, . override_span: Option, . ) -> (PResult<'a, TokenStream>, Vec) { . StringReader { sess, start_pos, pos: start_pos, end_src_index: src.len(), src, override_span } . .into_token_trees() 36 ( 0.00%) } . . struct StringReader<'a> { . sess: &'a ParseSess, . /// Initial position, read-only. . start_pos: BytePos, . /// The absolute offset within the source_map of the current character. . pos: BytePos, . /// Stop reading src at this index. -- line 50 ---------------------------------------- -- line 51 ---------------------------------------- . end_src_index: usize, . /// Source text to tokenize. . src: &'a str, . override_span: Option, . } . . impl<'a> StringReader<'a> { . fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span { 159,568 ( 0.00%) self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi)) . } . . /// Returns the next token, and info about preceding whitespace, if any. 882,805 ( 0.02%) fn next_token(&mut self) -> (Spacing, Token) { . let mut spacing = Spacing::Joint; . . // Skip `#!` at the start of the file 252,230 ( 0.01%) let start_src_index = self.src_index(self.pos); 378,345 ( 0.01%) let text: &str = &self.src[start_src_index..self.end_src_index]; . let is_beginning_of_file = self.pos == self.start_pos; 126,115 ( 0.00%) if is_beginning_of_file { 16 ( 0.00%) if let Some(shebang_len) = rustc_lexer::strip_shebang(text) { . self.pos = self.pos + BytePos::from_usize(shebang_len); . spacing = Spacing::Alone; . } . } . . // Skip trivial (whitespace & comments) tokens . loop { 248,667 ( 0.01%) let start_src_index = self.src_index(self.pos); 562,173 ( 0.01%) let text: &str = &self.src[start_src_index..self.end_src_index]; . 187,391 ( 0.00%) if text.is_empty() { . let span = self.mk_sp(self.pos, self.pos); 20 ( 0.00%) return (spacing, Token::new(token::Eof, span)); . } . 562,161 ( 0.01%) let token = rustc_lexer::first_token(text); . 374,774 ( 0.01%) let start = self.pos; 187,387 ( 0.00%) self.pos = self.pos + BytePos::from_usize(token.len); . . debug!("next_token: {:?}({:?})", token.kind, self.str_from(start)); . 1,499,420 ( 0.03%) match self.cook_lexer_token(token.kind, start) { 1,008,888 ( 0.02%) Some(kind) => { . let span = self.mk_sp(start, self.pos); 756,666 ( 0.02%) return (spacing, Token::new(kind, span)); . } . None => spacing = Spacing::Alone, . } . } 1,135,035 ( 0.02%) } . . /// Report a fatal lexical error with a given span. . fn fatal_span(&self, sp: Span, m: &str) -> FatalError { . self.sess.span_diagnostic.span_fatal(sp, m) . } . . /// Report a lexical error with a given span. . fn err_span(&self, sp: Span, m: &str) { -- line 110 ---------------------------------------- -- line 130 ---------------------------------------- . ) -> DiagnosticBuilder<'a> { . self.sess . .span_diagnostic . .struct_span_fatal(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c))) . } . . /// Detect usages of Unicode codepoints changing the direction of the text on screen and loudly . /// complain about it. 644 ( 0.00%) fn lint_unicode_text_flow(&self, start: BytePos) { . // Opening delimiter of the length 2 is not included into the comment text. . let content_start = start + BytePos(2); . let content = self.str_from(content_start); . if contains_text_flow_control_chars(content) { . let span = self.mk_sp(start, self.pos); . self.sess.buffer_lint_with_diagnostic( . &TEXT_DIRECTION_CODEPOINT_IN_COMMENT, . span, . ast::CRATE_NODE_ID, . "unicode codepoint changing visible direction of text present in comment", . BuiltinLintDiagnostics::UnicodeTextFlow(span, content.to_string()), . ); . } 736 ( 0.00%) } . . /// Turns simple `rustc_lexer::TokenKind` enum into a rich . /// `rustc_ast::TokenKind`. This turns strings into interned . /// symbols and runs additional validation. . fn cook_lexer_token(&self, token: rustc_lexer::TokenKind, start: BytePos) -> Option { 936,935 ( 0.02%) Some(match token { 173 ( 0.00%) rustc_lexer::TokenKind::LineComment { doc_style } => { . // Skip non-doc comments 589 ( 0.00%) let doc_style = if let Some(doc_style) = doc_style { . doc_style . } else { . self.lint_unicode_text_flow(start); . return None; . }; . . // Opening delimiter of the length 3 is not included into the symbol. . let content_start = start + BytePos(3); . let content = self.str_from(content_start); 405 ( 0.00%) self.cook_doc_comment(content_start, content, CommentKind::Line, doc_style) . } . rustc_lexer::TokenKind::BlockComment { doc_style, terminated } => { . if !terminated { . let msg = match doc_style { . Some(_) => "unterminated block doc-comment", . None => "unterminated block comment", . }; . let last_bpos = self.pos; -- line 179 ---------------------------------------- -- line 198 ---------------------------------------- . let content_end = self.pos - BytePos(if terminated { 2 } else { 0 }); . let content = self.str_from_to(content_start, content_end); . self.cook_doc_comment(content_start, content, CommentKind::Block, doc_style) . } . rustc_lexer::TokenKind::Whitespace => return None, . rustc_lexer::TokenKind::Ident . | rustc_lexer::TokenKind::RawIdent . | rustc_lexer::TokenKind::UnknownPrefix => { 133,796 ( 0.00%) let is_raw_ident = token == rustc_lexer::TokenKind::RawIdent; 167,245 ( 0.00%) let is_unknown_prefix = token == rustc_lexer::TokenKind::UnknownPrefix; . let mut ident_start = start; 66,898 ( 0.00%) if is_raw_ident { . ident_start = ident_start + BytePos(2); . } 100,347 ( 0.00%) if is_unknown_prefix { . self.report_unknown_prefix(start); . } 167,245 ( 0.00%) let sym = nfc_normalize(self.str_from(ident_start)); . let span = self.mk_sp(start, self.pos); 133,796 ( 0.00%) self.sess.symbol_gallery.insert(sym, span); 66,898 ( 0.00%) if is_raw_ident { . if !sym.can_be_raw() { . self.err_span(span, &format!("`{}` cannot be a raw identifier", sym)); . } . self.sess.raw_identifier_spans.borrow_mut().push(span); . } 234,143 ( 0.00%) token::Ident(sym, is_raw_ident) . } . rustc_lexer::TokenKind::InvalidIdent . // Do not recover an identifier with emoji if the codepoint is a confusable . // with a recoverable substitution token, like `âž–`. . if UNICODE_ARRAY . .iter() . .find(|&&(c, _, _)| { . let sym = self.str_from(start); -- line 232 ---------------------------------------- -- line 234 ---------------------------------------- . }) . .is_none() => . { . let sym = nfc_normalize(self.str_from(start)); . let span = self.mk_sp(start, self.pos); . self.sess.bad_unicode_identifiers.borrow_mut().entry(sym).or_default().push(span); . token::Ident(sym, false) . } 342,528 ( 0.01%) rustc_lexer::TokenKind::Literal { kind, suffix_start } => { . let suffix_start = start + BytePos(suffix_start as u32); . let (kind, symbol) = self.cook_lexer_literal(start, suffix_start, kind); 64,224 ( 0.00%) let suffix = if suffix_start < self.pos { . let string = self.str_from(suffix_start); . if string == "_" { . self.sess . .span_diagnostic . .struct_span_warn( . self.mk_sp(suffix_start, self.pos), . "underscore literal suffix is not allowed", . ) -- line 253 ---------------------------------------- -- line 264 ---------------------------------------- . .emit(); . None . } else { . Some(Symbol::intern(string)) . } . } else { . None . }; 171,264 ( 0.00%) token::Literal(token::Lit { kind, symbol, suffix }) . } 50 ( 0.00%) rustc_lexer::TokenKind::Lifetime { starts_with_number } => { . // Include the leading `'` in the real identifier, for macro . // expansion purposes. See #12512 for the gory details of why . // this is necessary. . let lifetime_name = self.str_from(start); 25 ( 0.00%) if starts_with_number { . self.err_span_(start, self.pos, "lifetimes cannot start with a number"); . } 75 ( 0.00%) let ident = Symbol::intern(lifetime_name); 100 ( 0.00%) token::Lifetime(ident) . } . rustc_lexer::TokenKind::Semi => token::Semi, . rustc_lexer::TokenKind::Comma => token::Comma, . rustc_lexer::TokenKind::Dot => token::Dot, . rustc_lexer::TokenKind::OpenParen => token::OpenDelim(token::Paren), . rustc_lexer::TokenKind::CloseParen => token::CloseDelim(token::Paren), . rustc_lexer::TokenKind::OpenBrace => token::OpenDelim(token::Brace), . rustc_lexer::TokenKind::CloseBrace => token::CloseDelim(token::Brace), -- line 291 ---------------------------------------- -- line 324 ---------------------------------------- . err.help("source files must contain UTF-8 encoded text, unexpected null bytes might occur when a different encoding is used"); . } . err.emit(); . token? . } . }) . } . 972 ( 0.00%) fn cook_doc_comment( . &self, . content_start: BytePos, . content: &str, . comment_kind: CommentKind, . doc_style: DocStyle, . ) -> TokenKind { 81 ( 0.00%) if content.contains('\r') { . for (idx, _) in content.char_indices().filter(|&(_, c)| c == '\r') { . self.err_span_( . content_start + BytePos(idx as u32), . content_start + BytePos(idx as u32 + 1), . match comment_kind { . CommentKind::Line => "bare CR not allowed in doc-comment", . CommentKind::Block => "bare CR not allowed in block doc-comment", . }, -- line 347 ---------------------------------------- -- line 349 ---------------------------------------- . } . } . . let attr_style = match doc_style { . DocStyle::Outer => AttrStyle::Outer, . DocStyle::Inner => AttrStyle::Inner, . }; . 243 ( 0.00%) token::DocComment(comment_kind, attr_style, Symbol::intern(content)) 1,215 ( 0.00%) } . . fn cook_lexer_literal( . &self, . start: BytePos, . suffix_start: BytePos, . kind: rustc_lexer::LiteralKind, . ) -> (token::LitKind, Symbol) { . // prefix means `"` or `br"` or `r###"`, ... . let (lit_kind, mode, prefix_len, postfix_len) = match kind { 1,946 ( 0.00%) rustc_lexer::LiteralKind::Char { terminated } => { 1,946 ( 0.00%) if !terminated { . self.sess.span_diagnostic.span_fatal_with_code( . self.mk_sp(start, suffix_start), . "unterminated character literal", . error_code!(E0762), . ) . } . (token::Char, Mode::Char, 1, 1) // ' ' . } 11 ( 0.00%) rustc_lexer::LiteralKind::Byte { terminated } => { 11 ( 0.00%) if !terminated { . self.sess.span_diagnostic.span_fatal_with_code( . self.mk_sp(start + BytePos(1), suffix_start), . "unterminated byte constant", . error_code!(E0763), . ) . } . (token::Byte, Mode::Byte, 2, 1) // b' ' . } 20 ( 0.00%) rustc_lexer::LiteralKind::Str { terminated } => { 20 ( 0.00%) if !terminated { . self.sess.span_diagnostic.span_fatal_with_code( . self.mk_sp(start, suffix_start), . "unterminated double quote string", . error_code!(E0765), . ) . } . (token::Str, Mode::Str, 1, 1) // " " . } -- line 397 ---------------------------------------- -- line 410 ---------------------------------------- . let n = u32::from(n_hashes); . (token::StrRaw(n_hashes), Mode::RawStr, 2 + n, 1 + n) // r##" "## . } . rustc_lexer::LiteralKind::RawByteStr { n_hashes, err } => { . self.report_raw_str_error(start, err); . let n = u32::from(n_hashes); . (token::ByteStrRaw(n_hashes), Mode::RawByteStr, 3 + n, 1 + n) // br##" "## . } 38,862 ( 0.00%) rustc_lexer::LiteralKind::Int { base, empty_int } => { 19,431 ( 0.00%) return if empty_int { . self.sess . .span_diagnostic . .struct_span_err_with_code( . self.mk_sp(start, suffix_start), . "no valid digits found for number", . error_code!(E0768), . ) . .emit(); . (token::Integer, sym::integer(0)) . } else { . self.validate_int_literal(base, start, suffix_start); 58,293 ( 0.00%) (token::Integer, self.symbol_from_to(start, suffix_start)) . }; . } . rustc_lexer::LiteralKind::Float { base, empty_exponent } => { . if empty_exponent { . self.err_span_(start, self.pos, "expected at least one digit in exponent"); . } . . match base { -- line 439 ---------------------------------------- -- line 452 ---------------------------------------- . } . . let id = self.symbol_from_to(start, suffix_start); . return (token::Float, id); . } . }; . let content_start = start + BytePos(prefix_len); . let content_end = suffix_start - BytePos(postfix_len); 5,931 ( 0.00%) let id = self.symbol_from_to(content_start, content_end); . self.validate_literal_escape(mode, content_start, content_end, prefix_len, postfix_len); . (lit_kind, id) . } . . #[inline] . fn src_index(&self, pos: BytePos) -> usize { . (pos - self.start_pos).to_usize() . } . . /// Slice of the source text from `start` up to but excluding `self.pos`, . /// meaning the slice does not include the character `self.ch`. . fn str_from(&self, start: BytePos) -> &str { 202,565 ( 0.00%) self.str_from_to(start, self.pos) . } . . /// As symbol_from, with an explicit endpoint. . fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol { . debug!("taking an ident from {:?} to {:?}", start, end); 159,741 ( 0.00%) Symbol::intern(self.str_from_to(start, end)) . } . . /// Slice of the source text spanning from `start` up to but excluding `end`. 57,032 ( 0.00%) fn str_from_to(&self, start: BytePos, end: BytePos) -> &str { . &self.src[self.src_index(start)..self.src_index(end)] 228,128 ( 0.00%) } . . fn report_raw_str_error(&self, start: BytePos, opt_err: Option) { . match opt_err { . Some(RawStrError::InvalidStarter { bad_char }) => { . self.report_non_started_raw_string(start, bad_char) . } . Some(RawStrError::NoTerminator { expected, found, possible_terminator_offset }) => self . .report_unterminated_raw_string(start, expected, possible_terminator_offset, found), -- line 493 ---------------------------------------- -- line 609 ---------------------------------------- . fn validate_literal_escape( . &self, . mode: Mode, . content_start: BytePos, . content_end: BytePos, . prefix_len: u32, . postfix_len: u32, . ) { 11,862 ( 0.00%) let lit_content = self.str_from_to(content_start, content_end); 103,526 ( 0.00%) unescape::unescape_literal(lit_content, mode, &mut |range, result| { . // Here we only check for errors. The actual unescaping is done later. 15,008 ( 0.00%) if let Err(err) = result { . let span_with_quotes = self . .mk_sp(content_start - BytePos(prefix_len), content_end + BytePos(postfix_len)); . let (start, end) = (range.start as u32, range.end as u32); . let lo = content_start + BytePos(start); . let hi = lo + BytePos(end - start); . let span = self.mk_sp(lo, hi); . emit_unescape_error( . &self.sess.span_diagnostic, -- line 628 ---------------------------------------- -- line 629 ---------------------------------------- . lit_content, . span_with_quotes, . span, . mode, . range, . err, . ); . } 67,536 ( 0.00%) }); . } . . fn validate_int_literal(&self, base: Base, content_start: BytePos, content_end: BytePos) { 77,724 ( 0.00%) let base = match base { . Base::Binary => 2, . Base::Octal => 8, . _ => return, . }; . let s = self.str_from_to(content_start + BytePos(2), content_end); . for (idx, c) in s.char_indices() { . let idx = idx as u32; . if c != '_' && c.to_digit(base).is_none() { -- line 649 ---------------------------------------- -- line 650 ---------------------------------------- . let lo = content_start + BytePos(2 + idx); . let hi = content_start + BytePos(2 + idx + c.len_utf8() as u32); . self.err_span_(lo, hi, &format!("invalid digit for a base {} literal", base)); . } . } . } . } . 301,041 ( 0.01%) pub fn nfc_normalize(string: &str) -> Symbol { . use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization}; 66,898 ( 0.00%) match is_nfc_quick(string.chars()) { 334,490 ( 0.01%) IsNormalized::Yes => Symbol::intern(string), . _ => { . let normalized_str: String = string.chars().nfc().collect(); . Symbol::intern(&normalized_str) . } . } . } 602,870 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs -------------------------------------------------------------------------------- Ir -- line 8 ---------------------------------------- . }; . use rustc_ast_pretty::pprust::token_to_string; . use rustc_data_structures::fx::FxHashMap; . use rustc_errors::PResult; . use rustc_span::Span; . . impl<'a> StringReader<'a> { . pub(super) fn into_token_trees(self) -> (PResult<'a, TokenStream>, Vec) { 76 ( 0.00%) let mut tt_reader = TokenTreesReader { . string_reader: self, 4 ( 0.00%) token: Token::dummy(), . open_braces: Vec::new(), . unmatched_braces: Vec::new(), . matching_delim_spans: Vec::new(), . last_unclosed_found_span: None, . last_delim_empty_block_spans: FxHashMap::default(), . matching_block_spans: Vec::new(), . }; 4 ( 0.00%) let res = tt_reader.parse_all_token_trees(); 24 ( 0.00%) (res, tt_reader.unmatched_braces) . } . } . . struct TokenTreesReader<'a> { . string_reader: StringReader<'a>, . token: Token, . /// Stack of open delimiters and their spans. Used for error message. . open_braces: Vec<(token::DelimToken, Span)>, -- line 35 ---------------------------------------- -- line 43 ---------------------------------------- . last_delim_empty_block_spans: FxHashMap, . /// Collect the spans of braces (Open, Close). Used only . /// for detecting if blocks are empty and only braces. . matching_block_spans: Vec<(Span, Span)>, . } . . impl<'a> TokenTreesReader<'a> { . // Parse a stream of tokens into a list of `TokenTree`s, up to an `Eof`. 32 ( 0.00%) fn parse_all_token_trees(&mut self) -> PResult<'a, TokenStream> { . let mut buf = TokenStreamBuilder::default(); . . self.bump(); 1,148 ( 0.00%) while self.token != token::Eof { 4,560 ( 0.00%) buf.push(self.parse_token_tree()?); . } . . Ok(buf.into_token_stream()) 36 ( 0.00%) } . . // Parse a stream of tokens into a list of `TokenTree`s, up to a `CloseDelim`. . fn parse_token_trees_until_close_delim(&mut self) -> TokenStream { . let mut buf = TokenStreamBuilder::default(); . loop { 251,082 ( 0.01%) if let token::CloseDelim(..) = self.token.kind { . return buf.into_token_stream(); . } . 556,870 ( 0.01%) match self.parse_token_tree() { 1,002,366 ( 0.02%) Ok(tree) => buf.push(tree), . Err(mut e) => { . e.emit(); . return buf.into_token_stream(); . } . } . } . } . 1,007,496 ( 0.02%) fn parse_token_tree(&mut self) -> PResult<'a, TreeAndSpacing> { 223,888 ( 0.00%) let sm = self.string_reader.sess.source_map(); . 950,828 ( 0.02%) match self.token.kind { . token::Eof => { . let msg = "this file contains an unclosed delimiter"; . let mut err = . self.string_reader.sess.span_diagnostic.struct_span_err(self.token.span, msg); . for &(_, sp) in &self.open_braces { . err.span_label(sp, "unclosed delimiter"); . self.unmatched_braces.push(UnmatchedBrace { . expected_delim: token::DelimToken::Brace, -- line 91 ---------------------------------------- -- line 113 ---------------------------------------- . err.span_label( . *close_sp, . "...as it matches this but it has different indentation", . ); . } . } . Err(err) . } 14,167 ( 0.00%) token::OpenDelim(delim) => { . // The span for beginning of the delimited section 14,167 ( 0.00%) let pre_span = self.token.span; . . // Parse the open delimiter. 99,169 ( 0.00%) self.open_braces.push((delim, self.token.span)); . self.bump(); . . // Parse the token trees within the delimiters. . // We stop at any delimiter so we can try to recover if the user . // uses an incorrect delimiter. 14,167 ( 0.00%) let tts = self.parse_token_trees_until_close_delim(); . . // Expand to cover the entire delimited token tree 70,835 ( 0.00%) let delim_span = DelimSpan::from_pair(pre_span, self.token.span); . 28,334 ( 0.00%) match self.token.kind { . // Correct delimiter. 28,334 ( 0.00%) token::CloseDelim(d) if d == delim => { . let (open_brace, open_brace_span) = self.open_braces.pop().unwrap(); 28,334 ( 0.00%) let close_brace_span = self.token.span; . 42,501 ( 0.00%) if tts.is_empty() { 348 ( 0.00%) let empty_block_span = open_brace_span.to(close_brace_span); 464 ( 0.00%) if !sm.is_multiline(empty_block_span) { . // Only track if the block is in the form of `{}`, otherwise it is . // likely that it was written on purpose. . self.last_delim_empty_block_spans.insert(delim, empty_block_span); . } . } . . //only add braces 56,668 ( 0.00%) if let (DelimToken::Brace, DelimToken::Brace) = (open_brace, delim) { . self.matching_block_spans.push((open_brace_span, close_brace_span)); . } . 14,167 ( 0.00%) if self.open_braces.is_empty() { . // Clear up these spans to avoid suggesting them as we've found . // properly matched delimiters so far for an entire block. . self.matching_delim_spans.clear(); . } else { . self.matching_delim_spans.push(( . open_brace, . open_brace_span, . close_brace_span, -- line 165 ---------------------------------------- -- line 218 ---------------------------------------- . token::Eof => { . // Silently recover, the EOF token will be seen again . // and an error emitted then. Thus we don't pop from . // self.open_braces here. . } . _ => {} . } . 99,169 ( 0.00%) Ok(TokenTree::Delimited(delim_span, delim, tts).into()) . } . token::CloseDelim(delim) => { . // An unexpected closing delimiter (i.e., there is no . // matching opening delimiter). . let token_str = token_to_string(&self.token); . let msg = format!("unexpected closing delimiter: `{}`", token_str); . let mut err = . self.string_reader.sess.span_diagnostic.struct_span_err(self.token.span, &msg); -- line 234 ---------------------------------------- -- line 253 ---------------------------------------- . err.span_label(parent.1, "...matches this closing brace"); . } . } . . err.span_label(self.token.span, "unexpected closing delimiter"); . Err(err) . } . _ => { 488,885 ( 0.01%) let tt = TokenTree::Token(self.token.take()); . let mut spacing = self.bump(); 195,554 ( 0.00%) if !self.token.is_op() { . spacing = Alone; . } 586,662 ( 0.01%) Ok((tt, spacing)) . } . } 895,552 ( 0.02%) } . . fn bump(&mut self) -> Spacing { 1,064,188 ( 0.02%) let (spacing, token) = self.string_reader.next_token(); 559,756 ( 0.01%) self.token = token; . spacing . } . } . 14,167 ( 0.00%) #[derive(Default)] . struct TokenStreamBuilder { . buf: Vec, . } . . impl TokenStreamBuilder { 1,455,272 ( 0.03%) fn push(&mut self, (tree, joint): TreeAndSpacing) { 722,485 ( 0.01%) if let Some((TokenTree::Token(prev_token), Joint)) = self.buf.last() { 68,748 ( 0.00%) if let TokenTree::Token(token) = &tree { 104,282 ( 0.00%) if let Some(glued) = prev_token.glue(token) { . self.buf.pop(); 3,480 ( 0.00%) self.buf.push((TokenTree::Token(glued), joint)); . return; . } . } . } 558,270 ( 0.01%) self.buf.push((tree, joint)) 895,552 ( 0.02%) } . . fn into_token_stream(self) -> TokenStream { 141,706 ( 0.00%) TokenStream::new(self.buf) . } . } 393,029 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/coercion.rs -------------------------------------------------------------------------------- Ir -- line 73 ---------------------------------------- . /// See #47489 and #48598 . /// See docs on the "AllowTwoPhase" type for a more detailed discussion . allow_two_phase: AllowTwoPhase, . } . . impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> { . type Target = FnCtxt<'a, 'tcx>; . fn deref(&self) -> &Self::Target { 306,781 ( 0.01%) &self.fcx . } . } . . type CoerceResult<'tcx> = InferResult<'tcx, (Vec>, Ty<'tcx>)>; . . /// Coercing a mutable reference to an immutable works, while . /// coercing `&T` to `&mut T` should be forbidden. . fn coerce_mutbls<'tcx>( . from_mutbl: hir::Mutability, . to_mutbl: hir::Mutability, . ) -> RelateResult<'tcx, ()> { 666 ( 0.00%) match (from_mutbl, to_mutbl) { . (hir::Mutability::Mut, hir::Mutability::Mut | hir::Mutability::Not) . | (hir::Mutability::Not, hir::Mutability::Not) => Ok(()), . (hir::Mutability::Not, hir::Mutability::Mut) => Err(TypeError::Mutability), . } . } . . /// Do not require any adjustments, i.e. coerce `x -> x`. . fn identity(_: Ty<'_>) -> Vec> { . vec![] . } . . fn simple<'tcx>(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec> { 198 ( 0.00%) move |target| vec![Adjustment { kind, target }] . } . . /// This always returns `Ok(...)`. . fn success<'tcx>( . adj: Vec>, . target: Ty<'tcx>, . obligations: traits::PredicateObligations<'tcx>, . ) -> CoerceResult<'tcx> { 84,480 ( 0.00%) Ok(InferOk { value: (adj, target), obligations }) . } . . impl<'f, 'tcx> Coerce<'f, 'tcx> { . fn new( . fcx: &'f FnCtxt<'f, 'tcx>, . cause: ObligationCause<'tcx>, . allow_two_phase: AllowTwoPhase, . ) -> Self { 224,797 ( 0.00%) Coerce { fcx, cause, allow_two_phase, use_lub: false } . } . 612,194 ( 0.01%) fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> { . debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub); . self.commit_if_ok(|_| { 111,308 ( 0.00%) if self.use_lub { 98 ( 0.00%) self.at(&self.cause, self.fcx.param_env).lub(b, a) . } else { 111,210 ( 0.00%) self.at(&self.cause, self.fcx.param_env) . .sup(b, a) . .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations }) . } . }) 445,232 ( 0.01%) } . . /// Unify two types (using sub or lub) and produce a specific coercion. 111,596 ( 0.00%) fn unify_and(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F) -> CoerceResult<'tcx> . where . F: FnOnce(Ty<'tcx>) -> Vec>, . { 138,453 ( 0.00%) self.unify(&a, &b) 110,432 ( 0.00%) .and_then(|InferOk { value: ty, obligations }| success(f(ty), ty, obligations)) 83,697 ( 0.00%) } . 590,478 ( 0.01%) #[instrument(skip(self))] . fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { . // First, remove any resolved type variables (at the top level, at least): 28,118 ( 0.00%) let a = self.shallow_resolve(a); 28,118 ( 0.00%) let b = self.shallow_resolve(b); . debug!("Coerce.tys({:?} => {:?})", a, b); . . // Just ignore error types. 56,236 ( 0.00%) if a.references_error() || b.references_error() { . return success(vec![], self.fcx.tcx.ty_error(), vec![]); . } . . // Coercing from `!` to any type is allowed: 28,118 ( 0.00%) if a.is_never() { . return success(simple(Adjust::NeverToAny)(b), b, vec![]); . } . . // Coercing *from* an unresolved inference variable means that . // we have no information about the source type. This will always . // ultimately fall back to some form of subtyping. 28,214 ( 0.00%) if a.is_ty_var() { . return self.coerce_from_inference_variable(a, b, identity); . } . . // Consider coercing the subtype to a DST . // . // NOTE: this is wrapped in a `commit_if_ok` because it creates . // a "spurious" type variable, and we don't want to have that . // type variable in memory if the coercion fails. . let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b)); 112,084 ( 0.00%) match unsize { . Ok(_) => { . debug!("coerce: unsize successful"); 120 ( 0.00%) return unsize; . } . Err(TypeError::ObjectUnsafeCoercion(did)) => { . debug!("coerce: unsize not object safe"); . return Err(TypeError::ObjectUnsafeCoercion(did)); . } . Err(error) => { . debug!(?error, "coerce: unsize failed"); . } . } . . // Examine the supertype and consider auto-borrowing. 139,871 ( 0.00%) match *b.kind() { . ty::RawPtr(mt_b) => { . return self.coerce_unsafe_ptr(a, b, mt_b.mutbl); . } 214 ( 0.00%) ty::Ref(r_b, _, mutbl_b) => { 642 ( 0.00%) return self.coerce_borrowed_pointer(a, b, r_b, mutbl_b); . } . _ => {} . } . 195,370 ( 0.00%) match *a.kind() { . ty::FnDef(..) => { . // Function items are coercible to any closure . // type; function pointers are not (that would . // require double indirection). . // Additionally, we permit coercion of function . // items to drop the unsafe qualifier. . self.coerce_from_fn_item(a, b) . } . ty::FnPtr(a_f) => { . // We permit coercion of fn pointers to drop the . // unsafe qualifier. . self.coerce_from_fn_pointer(a, a_f, b) . } 33 ( 0.00%) ty::Closure(closure_def_id_a, substs_a) => { . // Non-capturing closures are coercible to . // function pointers or unsafe function pointers. . // It cannot convert closures that require unsafe. 88 ( 0.00%) self.coerce_closure_to_fn(a, closure_def_id_a, substs_a, b) . } . _ => { . // Otherwise, just use unification rules. 139,495 ( 0.00%) self.unify_and(a, b, identity) . } . } 56,236 ( 0.00%) } . . /// Coercing *from* an inference variable. In this case, we have no information . /// about the source type, so we can't really do a true coercion and we always . /// fall back to subtyping (`unify_and`). . fn coerce_from_inference_variable( . &self, . a: Ty<'tcx>, . b: Ty<'tcx>, . make_adjustments: impl FnOnce(Ty<'tcx>) -> Vec>, . ) -> CoerceResult<'tcx> { . debug!("coerce_from_inference_variable(a={:?}, b={:?})", a, b); 27 ( 0.00%) assert!(a.is_ty_var() && self.infcx.shallow_resolve(a) == a); 27 ( 0.00%) assert!(self.infcx.shallow_resolve(b) == b); . 29 ( 0.00%) if b.is_ty_var() { . // Two unresolved type variables: create a `Coerce` predicate. 3 ( 0.00%) let target_ty = if self.use_lub { . self.infcx.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::LatticeVariable, . span: self.cause.span, . }) . } else { . b . }; . . let mut obligations = Vec::with_capacity(2); . for &source_ty in &[a, b] { 2 ( 0.00%) if source_ty != target_ty { . obligations.push(Obligation::new( . self.cause.clone(), 1 ( 0.00%) self.param_env, 4 ( 0.00%) ty::Binder::dummy(ty::PredicateKind::Coerce(ty::CoercePredicate { . a: source_ty, . b: target_ty, . })) . .to_predicate(self.tcx()), . )); . } . } . . debug!( . "coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}", . target_ty, obligations . ); . let adjustments = make_adjustments(target_ty); 6 ( 0.00%) InferResult::Ok(InferOk { value: (adjustments, target_ty), obligations }) . } else { . // One unresolved type variable: just apply subtyping, we may be able . // to do something useful. . self.unify_and(a, b, make_adjustments) . } . } . . /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`. . /// To match `A` with `B`, autoderef will be performed, . /// calling `deref`/`deref_mut` where necessary. 1,070 ( 0.00%) fn coerce_borrowed_pointer( . &self, . a: Ty<'tcx>, . b: Ty<'tcx>, . r_b: ty::Region<'tcx>, . mutbl_b: hir::Mutability, . ) -> CoerceResult<'tcx> { . debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b); . . // If we have a parameter of type `&M T_a` and the value . // provided is `expr`, we will be adding an implicit borrow, . // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore, . // to type check, we will construct the type that `&M*expr` would . // yield. . 214 ( 0.00%) let (r_a, mt_a) = match *a.kind() { 321 ( 0.00%) ty::Ref(r_a, ty, mutbl) => { . let mt_a = ty::TypeAndMut { ty, mutbl }; . coerce_mutbls(mt_a.mutbl, mutbl_b)?; . (r_a, mt_a) . } . _ => return self.unify_and(a, b, identity), . }; . 214 ( 0.00%) let span = self.cause.span; . . let mut first_error = None; . let mut r_borrow_var = None; . let mut autoderef = self.autoderef(span, a); . let mut found = None; . 434 ( 0.00%) for (referent_ty, autoderefs) in autoderef.by_ref() { 434 ( 0.00%) if autoderefs == 0 { . // Don't let this pass, otherwise it would cause . // &T to autoref to &&T. . continue; . } . . // At this point, we have deref'd `a` to `referent_ty`. So . // imagine we are coercing from `&'a mut Vec` to `&'b mut [T]`. . // In the autoderef loop for `&'a mut Vec`, we would get -- line 326 ---------------------------------------- -- line 386 ---------------------------------------- . // this extra edge causes the region `'a` to be inferred to something . // too big, which then results in borrowck errors.) . // - We could track the innermost shared reference, but there is already . // code in regionck that has the job of creating links between . // the region of a borrow and the regions in the thing being . // borrowed (here, `'a` and `'x`), and it knows how to handle . // all the various cases. So instead we just make a region variable . // and let regionck figure it out. 220 ( 0.00%) let r = if !self.use_lub { . r_b // [2] above 6 ( 0.00%) } else if autoderefs == 1 { . r_a // [3] above . } else { 1 ( 0.00%) if r_borrow_var.is_none() { . // create var lazily, at most once . let coercion = Coercion(span); 5 ( 0.00%) let r = self.next_region_var(coercion); . r_borrow_var = Some(r); // [4] above . } . r_borrow_var.unwrap() . }; 110 ( 0.00%) let derefd_ty_a = self.tcx.mk_ref( . r, . TypeAndMut { . ty: referent_ty, . mutbl: mutbl_b, // [1] above . }, . ); 770 ( 0.00%) match self.unify(derefd_ty_a, b) { . Ok(ok) => { 428 ( 0.00%) found = Some(ok); . break; . } 9 ( 0.00%) Err(err) => { 3 ( 0.00%) if first_error.is_none() { 15 ( 0.00%) first_error = Some(err); . } . } . } . } . . // Extract type or return an error. We return the first error . // we got, which should be from relating the "base" type . // (e.g., in example above, the failure from relating `Vec` . // to the target type), since that should be the least . // confusing. 856 ( 0.00%) let InferOk { value: ty, mut obligations } = match found { . Some(d) => d, . None => { . let err = first_error.expect("coerce_borrowed_pointer had no error"); . debug!("coerce_borrowed_pointer: failed with err = {:?}", err); . return Err(err); . } . }; . 137 ( 0.00%) if ty == a && mt_a.mutbl == hir::Mutability::Not && autoderef.step_count() == 1 { . // As a special case, if we would produce `&'a *x`, that's . // a total no-op. We end up with the type `&'a T` just as . // we started with. In that case, just skip it . // altogether. This is just an optimization. . // . // Note that for `&mut`, we DO want to reborrow -- . // otherwise, this would be a move, which might be an . // error. For example `foo(self.x)` where `self` and . // `self.x` both have `&mut `type would be a move of . // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`, . // which is a borrow. 12 ( 0.00%) assert_eq!(mutbl_b, hir::Mutability::Not); // can only coerce &T -> &U 24 ( 0.00%) return success(vec![], ty, obligations); . } . 707 ( 0.00%) let InferOk { value: mut adjustments, obligations: o } = 101 ( 0.00%) self.adjust_steps_as_infer_ok(&autoderef); . obligations.extend(o); 1,919 ( 0.00%) obligations.extend(autoderef.into_obligations()); . . // Now apply the autoref. We have to extract the region out of . // the final ref type we got. 202 ( 0.00%) let r_borrow = match ty.kind() { . ty::Ref(r_borrow, _, _) => r_borrow, . _ => span_bug!(span, "expected a ref type, got {:?}", ty), . }; 404 ( 0.00%) let mutbl = match mutbl_b { . hir::Mutability::Not => AutoBorrowMutability::Not, . hir::Mutability::Mut => { . AutoBorrowMutability::Mut { allow_two_phase_borrow: self.allow_two_phase } . } . }; . adjustments.push(Adjustment { 101 ( 0.00%) kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)), . target: ty, . }); . . debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}", ty, adjustments); . 808 ( 0.00%) success(adjustments, ty, obligations) 856 ( 0.00%) } . . // &[T; n] or &mut [T; n] -> &[T] . // or &mut [T; n] -> &mut [T] . // or &Concrete -> &Trait, etc. . #[instrument(skip(self), level = "debug")] . fn coerce_unsized(&self, mut source: Ty<'tcx>, mut target: Ty<'tcx>) -> CoerceResult<'tcx> { . source = self.shallow_resolve(source); . target = self.shallow_resolve(target); -- line 490 ---------------------------------------- -- line 506 ---------------------------------------- . // would need to be generic over the self-type (`impl CoerceUnsized for T`) . // or generic over the `CoerceUnsized` type parameter (`impl CoerceUnsized for . // SomeType`). . // . // However, these are exactly the kinds of impls which are forbidden by . // the compiler! Therefore, we can be sure that coercion will always fail . // when either the source or target type is a type variable. This allows us . // to skip performing any trait selection, and immediately bail out. 28,133 ( 0.00%) if source.is_ty_var() { . debug!("coerce_unsized: source is a TyVar, bailing out"); . return Err(TypeError::Mismatch); . } 28,861 ( 0.00%) if target.is_ty_var() { . debug!("coerce_unsized: target is a TyVar, bailing out"); . return Err(TypeError::Mismatch); . } . . let traits = 331,296 ( 0.01%) (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait()); 110,432 ( 0.00%) let (Some(unsize_did), Some(coerce_unsized_did)) = traits else { . debug!("missing Unsize or CoerceUnsized traits"); . return Err(TypeError::Mismatch); . }; . . // Note, we want to avoid unnecessary unsizing. We don't want to coerce to . // a DST unless we have to. This currently comes out in the wash since . // we can't unify [T] with U. But to properly support DST, we need to allow . // that, at which point we will need extra checks on the target here. . . // Handle reborrows before selecting `Source: CoerceUnsized`. 55,561 ( 0.00%) let reborrow = match (source.kind(), target.kind()) { 345 ( 0.00%) (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => { . coerce_mutbls(mutbl_a, mutbl_b)?; . 115 ( 0.00%) let coercion = Coercion(self.cause.span); 575 ( 0.00%) let r_borrow = self.next_region_var(coercion); . let mutbl = match mutbl_b { . hir::Mutability::Not => AutoBorrowMutability::Not, . hir::Mutability::Mut => AutoBorrowMutability::Mut { . // We don't allow two-phase borrows here, at least for initial . // implementation. If it happens that this coercion is a function argument, . // the reborrow in coerce_borrowed_ptr will pick it up. . allow_two_phase_borrow: AllowTwoPhase::No, . }, . }; . Some(( . Adjustment { kind: Adjust::Deref(None), target: ty_a }, . Adjustment { . kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)), 115 ( 0.00%) target: self . .tcx . .mk_ref(r_borrow, ty::TypeAndMut { mutbl: mutbl_b, ty: ty_a }), . }, . )) . } . (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => { . coerce_mutbls(mt_a, mt_b)?; . -- line 563 ---------------------------------------- -- line 574 ---------------------------------------- . let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target); . . // Setup either a subtyping or a LUB relationship between . // the `CoerceUnsized` target type and the expected type. . // We only have the latter, so we use an inference variable . // for the former and let type inference do the rest. . let origin = TypeVariableOrigin { . kind: TypeVariableOriginKind::MiscVariable, 27,608 ( 0.00%) span: self.cause.span, . }; 138,040 ( 0.00%) let coerce_target = self.next_ty_var(origin); 110,432 ( 0.00%) let mut coercion = self.unify_and(coerce_target, target, |target| { . let unsize = Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target }; 55,216 ( 0.00%) match reborrow { 137,465 ( 0.00%) None => vec![unsize], 1,610 ( 0.00%) Some((ref deref, ref autoref)) => vec![deref.clone(), autoref.clone(), unsize], . } . })?; . 27,608 ( 0.00%) let mut selcx = traits::SelectionContext::new(self); . . // Create an obligation for `Source: CoerceUnsized`. . let cause = ObligationCause::new( 55,216 ( 0.00%) self.cause.span, 55,216 ( 0.00%) self.body_id, . ObligationCauseCode::Coercion { source, target }, . ); . . // Use a FIFO queue for this custom fulfillment procedure. . // . // A Vec (or SmallVec) is not a natural choice for a queue. However, . // this code path is hot, and this queue usually has a max length of 1 . // and almost never more than 3. By using a SmallVec we avoid an . // allocation, at the (very small) cost of (occasionally) having to . // shift subsequent elements down when removing the front element. 386,512 ( 0.01%) let mut queue: SmallVec<[_; 4]> = smallvec![traits::predicate_for_trait_def( 55,216 ( 0.00%) self.tcx, 27,608 ( 0.00%) self.fcx.param_env, 138,040 ( 0.00%) cause, . coerce_unsized_did, . 0, . coerce_source, 138,040 ( 0.00%) &[coerce_target.into()] . )]; . . let mut has_unsized_tuple_coercion = false; . let mut has_trait_upcasting_coercion = false; . . // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid . // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where . // inference might unify those two inner type variables later. . let traits = [coerce_unsized_did, unsize_did]; 55,644 ( 0.00%) while !queue.is_empty() { . let obligation = queue.remove(0); . debug!("coerce_unsized resolve step: {:?}", obligation); 27,814 ( 0.00%) let bound_predicate = obligation.predicate.kind(); 139,070 ( 0.00%) let trait_pred = match bound_predicate.skip_binder() { 166,410 ( 0.00%) ty::PredicateKind::Trait(trait_pred) if traits.contains(&trait_pred.def_id()) => { 249,507 ( 0.01%) if unsize_did == trait_pred.def_id() { 690 ( 0.00%) let self_ty = trait_pred.self_ty(); 460 ( 0.00%) let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty(); 575 ( 0.00%) if let (ty::Dynamic(ref data_a, ..), ty::Dynamic(ref data_b, ..)) = . (self_ty.kind(), unsize_ty.kind()) . { . if data_a.principal_def_id() != data_b.principal_def_id() { . debug!("coerce_unsized: found trait upcasting coercion"); . has_trait_upcasting_coercion = true; . } . } 690 ( 0.00%) if let ty::Tuple(..) = unsize_ty.kind() { . debug!("coerce_unsized: found unsized tuple coercion"); . has_unsized_tuple_coercion = true; . } . } 55,446 ( 0.00%) bound_predicate.rebind(trait_pred) . } . _ => { 546 ( 0.00%) coercion.obligations.push(obligation); . continue; . } . }; 304,953 ( 0.01%) match selcx.select(&obligation.with(trait_pred)) { . // Uncertain or unimplemented. . Ok(None) => { 156 ( 0.00%) if trait_pred.def_id() == unsize_did { 72 ( 0.00%) let trait_pred = self.resolve_vars_if_possible(trait_pred); 24 ( 0.00%) let self_ty = trait_pred.skip_binder().self_ty(); 72 ( 0.00%) let unsize_ty = trait_pred.skip_binder().trait_ref.substs[1].expect_ty(); . debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred); 24 ( 0.00%) match (&self_ty.kind(), &unsize_ty.kind()) { . (ty::Infer(ty::TyVar(v)), ty::Dynamic(..)) . if self.type_var_is_sized(*v) => . { . debug!("coerce_unsized: have sized infer {:?}", v); . coercion.obligations.push(obligation); . // `$0: Unsize` where we know that `$0: Sized`, try going . // for unsizing. . } -- line 671 ---------------------------------------- -- line 679 ---------------------------------------- . } . } else { . debug!("coerce_unsized: early return - ambiguous"); . return Err(TypeError::Mismatch); . } . } . Err(traits::Unimplemented) => { . debug!("coerce_unsized: early return - can't prove obligation"); 165,528 ( 0.00%) return Err(TypeError::Mismatch); . } . . // Object safety violations or miscellaneous. . Err(err) => { . self.report_selection_error(obligation.clone(), &obligation, &err, false); . // Treat this like an obligation and follow through . // with the unsizing - the lack of a coercion should . // be silent, as it causes a type mismatch later. . } . 2,337 ( 0.00%) Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()), . } 55,200 ( 0.00%) } . 16 ( 0.00%) if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion { . feature_err( . &self.tcx.sess.parse_sess, . sym::unsized_tuple_coercion, . self.cause.span, . "unsized tuple coercion is not stable enough for use and is subject to change", . ) . .emit(); . } . 16 ( 0.00%) if has_trait_upcasting_coercion && !self.tcx().features().trait_upcasting { . feature_err( . &self.tcx.sess.parse_sess, . sym::trait_upcasting, . self.cause.span, . "trait upcasting coercion is experimental", . ) . .emit(); . } . 88 ( 0.00%) Ok(coercion) . } . . fn coerce_from_safe_fn( . &self, . a: Ty<'tcx>, . fn_ty_a: ty::PolyFnSig<'tcx>, . b: Ty<'tcx>, . to_unsafe: F, -- line 730 ---------------------------------------- -- line 819 ---------------------------------------- . . obligations.extend(o2); . Ok(InferOk { value, obligations }) . } . _ => self.unify_and(a, b, identity), . } . } . 154 ( 0.00%) fn coerce_closure_to_fn( . &self, . a: Ty<'tcx>, . closure_def_id_a: DefId, . substs_a: SubstsRef<'tcx>, . b: Ty<'tcx>, . ) -> CoerceResult<'tcx> { . //! Attempts to coerce from the type of a non-capturing closure . //! into a function pointer. . //! . . let b = self.shallow_resolve(b); . 22 ( 0.00%) match b.kind() { . // At this point we haven't done capture analysis, which means . // that the ClosureSubsts just contains an inference variable instead . // of tuple of captured types. . // . // All we care here is if any variable is being captured and not the exact paths, . // so we check `upvars_mentioned` for root variables being captured. . ty::FnPtr(fn_ty) . if self -- line 848 ---------------------------------------- -- line 864 ---------------------------------------- . self.unify_and( . pointer_ty, . b, . simple(Adjust::Pointer(PointerCast::ClosureFnPointer(unsafety))), . ) . } . _ => self.unify_and(a, b, identity), . } 88 ( 0.00%) } . . fn coerce_unsafe_ptr( . &self, . a: Ty<'tcx>, . b: Ty<'tcx>, . mutbl_b: hir::Mutability, . ) -> CoerceResult<'tcx> { . debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b); -- line 880 ---------------------------------------- -- line 906 ---------------------------------------- . } . } . . impl<'a, 'tcx> FnCtxt<'a, 'tcx> { . /// Attempt to coerce an expression to a type, and return the . /// adjusted type of the expression, if successful. . /// Adjustments are only recorded if the coercion succeeded. . /// The expressions *must not* have any pre-existing adjustments. 392,966 ( 0.01%) pub fn try_coerce( . &self, . expr: &hir::Expr<'_>, . expr_ty: Ty<'tcx>, . target: Ty<'tcx>, . allow_two_phase: AllowTwoPhase, . cause: Option>, . ) -> RelateResult<'tcx, Ty<'tcx>> { 84,207 ( 0.00%) let source = self.resolve_vars_with_obligations(expr_ty); . debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target); . . let cause = 28,069 ( 0.00%) cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable)); . let coerce = Coerce::new(self, cause, allow_two_phase); 336,743 ( 0.01%) let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?; . 112,208 ( 0.00%) let (adjustments, _) = self.register_infer_ok_obligations(ok); 280,520 ( 0.01%) self.apply_adjustments(expr, adjustments); 84,156 ( 0.00%) Ok(if expr_ty.references_error() { self.tcx.ty_error() } else { target }) 252,621 ( 0.01%) } . . /// Same as `try_coerce()`, but without side-effects. . /// . /// Returns false if the coercion creates any obligations that result in . /// errors. . pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool { . let source = self.resolve_vars_with_obligations(expr_ty); . debug!("coercion::can_with_predicates({:?} -> {:?})", source, target); -- line 941 ---------------------------------------- -- line 967 ---------------------------------------- . } . . /// Given some expressions, their known unified type and another expression, . /// tries to unify the types, potentially inserting coercions on any of the . /// provided expressions and returns their LUB (aka "common supertype"). . /// . /// This is really an internal helper. From outside the coercion . /// module, you should instantiate a `CoerceMany` instance. 130,702 ( 0.00%) fn try_find_coercion_lub( . &self, . cause: &ObligationCause<'tcx>, . exprs: &[E], . prev_ty: Ty<'tcx>, . new: &hir::Expr<'_>, . new_ty: Ty<'tcx>, . ) -> RelateResult<'tcx, Ty<'tcx>> . where . E: AsCoercionSite, . { 60,324 ( 0.00%) let prev_ty = self.resolve_vars_with_obligations(prev_ty); 30,162 ( 0.00%) let new_ty = self.resolve_vars_with_obligations(new_ty); . debug!( . "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)", . prev_ty, . new_ty, . exprs.len() . ); . . // The following check fixes #88097, where the compiler erroneously . // attempted to coerce a closure type to itself via a function pointer. 10,054 ( 0.00%) if prev_ty == new_ty { 9,971 ( 0.00%) return Ok(prev_ty); . } . . // Special-case that coercion alone cannot handle: . // Function items or non-capturing closures of differing IDs or InternalSubsts. 392 ( 0.00%) let (a_sig, b_sig) = { 392 ( 0.00%) let is_capturing_closure = |ty| { 196 ( 0.00%) if let &ty::Closure(closure_def_id, _substs) = ty { . self.tcx.upvars_mentioned(closure_def_id.expect_local()).is_some() . } else { . false . } 392 ( 0.00%) }; 588 ( 0.00%) if is_capturing_closure(prev_ty.kind()) || is_capturing_closure(new_ty.kind()) { . (None, None) . } else { 294 ( 0.00%) match (prev_ty.kind(), new_ty.kind()) { . (ty::FnDef(..), ty::FnDef(..)) => { . // Don't reify if the function types have a LUB, i.e., they . // are the same function and their parameters have a LUB. . match self . .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty)) . { . // We have a LUB of prev_ty and new_ty, just return it. . Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)), -- line 1022 ---------------------------------------- -- line 1048 ---------------------------------------- . substs_b.as_closure().sig(), . hir::Unsafety::Normal, . )), . ), . _ => (None, None), . } . } . }; 196 ( 0.00%) if let (Some(a_sig), Some(b_sig)) = (a_sig, b_sig) { . // Intrinsics are not coercible to function pointers. . if a_sig.abi() == Abi::RustIntrinsic . || a_sig.abi() == Abi::PlatformIntrinsic . || b_sig.abi() == Abi::RustIntrinsic . || b_sig.abi() == Abi::PlatformIntrinsic . { . return Err(TypeError::IntrinsicCast); . } -- line 1064 ---------------------------------------- -- line 1094 ---------------------------------------- . } . . // Configure a Coerce instance to compute the LUB. . // We don't allow two-phase borrows on any autorefs this creates since we . // probably aren't processing function arguments here and even if we were, . // they're going to get autorefed again anyway and we can apply 2-phase borrows . // at that time. . let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No); 49 ( 0.00%) coerce.use_lub = true; . . // First try to coerce the new expression to the type of the previous ones, . // but only if the new expression has no coercion already applied to it. . let mut first_error = None; 392 ( 0.00%) if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) { 28,510 ( 0.00%) let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty)); 98 ( 0.00%) match result { . Ok(ok) => { 392 ( 0.00%) let (adjustments, target) = self.register_infer_ok_obligations(ok); 392 ( 0.00%) self.apply_adjustments(new, adjustments); . debug!( . "coercion::try_find_coercion_lub: was able to coerce from previous type {:?} to new type {:?}", . prev_ty, new_ty, . ); 98 ( 0.00%) return Ok(target); . } . Err(e) => first_error = Some(e), . } . } . . // Then try to coerce the previous expressions to the type of the new one. . // This requires ensuring there are no coercions applied to *any* of the . // previous expressions, other than noop reborrows (ignoring lifetimes). -- line 1125 ---------------------------------------- -- line 1175 ---------------------------------------- . let (adjustments, target) = self.register_infer_ok_obligations(ok); . for expr in exprs { . let expr = expr.as_coercion_site(); . self.apply_adjustments(expr, adjustments.clone()); . } . Ok(target) . } . } 90,486 ( 0.00%) } . } . . /// CoerceMany encapsulates the pattern you should use when you have . /// many expressions that are all getting coerced to a common . /// type. This arises, for example, when you have a match (the result . /// of each arm is coerced to a common type). It also arises in less . /// obvious places, such as when you have many `break foo` expressions . /// that target the same loop, or the various `return` expressions in -- line 1191 ---------------------------------------- -- line 1253 ---------------------------------------- . /// expected to pass each element in the slice to `coerce(...)` in . /// order. This is used with arrays in particular to avoid . /// needlessly cloning the slice. . pub fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self { . Self::make(expected_ty, Expressions::UpFront(coercion_sites)) . } . . fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self { 756 ( 0.00%) CoerceMany { expected_ty, final_ty: None, expressions, pushed: 0 } . } . . /// Returns the "expected type" with which this coercion was . /// constructed. This represents the "downward propagated" type . /// that was given to us at the start of typing whatever construct . /// we are typing (e.g., the match expression). . /// . /// Typically, this is used as the expected type when . /// type-checking each of the alternative expressions whose types . /// we are trying to merge. . pub fn expected_ty(&self) -> Ty<'tcx> { 10 ( 0.00%) self.expected_ty . } . . /// Returns the current "merged type", representing our best-guess . /// at the LUB of the expressions we've seen so far (if any). This . /// isn't *final* until you call `self.final()`, which will return . /// the merged type. . pub fn merged_ty(&self) -> Ty<'tcx> { . self.final_ty.unwrap_or(self.expected_ty) . } . . /// Indicates that the value generated by `expression`, which is . /// of type `expression_ty`, is one of the possibilities that we . /// could coerce from. This will record `expression`, and later . /// calls to `coerce` may come back and add adjustments and things . /// if necessary. 119,388 ( 0.00%) pub fn coerce<'a>( . &mut self, . fcx: &FnCtxt<'a, 'tcx>, . cause: &ObligationCause<'tcx>, . expression: &'tcx hir::Expr<'tcx>, . expression_ty: Ty<'tcx>, . ) { 2,216 ( 0.00%) self.coerce_inner(fcx, cause, Some(expression), expression_ty, None, false) 79,592 ( 0.00%) } . . /// Indicates that one of the inputs is a "forced unit". This . /// occurs in a case like `if foo { ... };`, where the missing else . /// generates a "forced unit". Another example is a `loop { break; . /// }`, where the `break` has no argument expression. We treat . /// these cases slightly differently for error-reporting . /// purposes. Note that these tend to correspond to cases where . /// the `()` expression is implicit in the source, and hence we do -- line 1305 ---------------------------------------- -- line 1310 ---------------------------------------- . /// removing a `;`). . pub fn coerce_forced_unit<'a>( . &mut self, . fcx: &FnCtxt<'a, 'tcx>, . cause: &ObligationCause<'tcx>, . augment_error: &mut dyn FnMut(&mut DiagnosticBuilder<'_>), . label_unit_as_expected: bool, . ) { 888 ( 0.00%) self.coerce_inner( . fcx, . cause, . None, 99 ( 0.00%) fcx.tcx.mk_unit(), . Some(augment_error), . label_unit_as_expected, . ) . } . . /// The inner coercion "engine". If `expression` is `None`, this . /// is a forced-unit case, and hence `expression_ty` must be . /// `Nil`. 10,143 ( 0.00%) #[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")] . crate fn coerce_inner<'a>( . &mut self, . fcx: &FnCtxt<'a, 'tcx>, . cause: &ObligationCause<'tcx>, . expression: Option<&'tcx hir::Expr<'tcx>>, . mut expression_ty: Ty<'tcx>, . augment_error: Option<&mut dyn FnMut(&mut DiagnosticBuilder<'_>)>, . label_expression_as_expected: bool, . ) { . // Incorporate whatever type inference information we have . // until now; in principle we might also want to process . // pending obligations, but doing so should only improve . // compatibility (hopefully that is true) by helping us . // uncover never types better. 10,498 ( 0.00%) if expression_ty.is_ty_var() { . expression_ty = fcx.infcx.shallow_resolve(expression_ty); . } . . // If we see any error types, just propagate that error . // upwards. 41,728 ( 0.00%) if expression_ty.references_error() || self.merged_ty().references_error() { . self.final_ty = Some(fcx.tcx.ty_error()); . return; . } . . // Handle the actual type unification etc. 1,449 ( 0.00%) let result = if let Some(expression) = expression { 30,999 ( 0.00%) if self.pushed == 0 { . // Special-case the first expression we are coercing. . // To be honest, I'm not entirely sure why we do this. . // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why 2,511 ( 0.00%) fcx.try_coerce( . expression, . expression_ty, . self.expected_ty, . AllowTwoPhase::No, 1,116 ( 0.00%) Some(cause.clone()), . ) . } else { 20,108 ( 0.00%) match self.expressions { 104 ( 0.00%) Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub( . cause, . exprs, . self.merged_ty(), . expression, . expression_ty, . ), 60,069 ( 0.00%) Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub( . cause, 30,006 ( 0.00%) &coercion_sites[0..self.pushed], . self.merged_ty(), . expression, . expression_ty, . ), . } . } . } else { . // this is a hack for cases where we default to `()` because -- line 1389 ---------------------------------------- -- line 1394 ---------------------------------------- . // . // we wind up with a second match arm that is like `_ => . // ()`. That is the case we are considering here. We take . // a different path to get the right "expected, found" . // message and so forth (and because we know that . // `expression_ty` will be unit). . // . // Another example is `break` with no argument expression. 99 ( 0.00%) assert!(expression_ty.is_unit(), "if let hack without unit type"); 198 ( 0.00%) fcx.at(cause, fcx.param_env) . .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty()) . .map(|infer_ok| { . fcx.register_infer_ok_obligations(infer_ok); . expression_ty . }) . }; . 20,874 ( 0.00%) match result { 10,531 ( 0.00%) Ok(v) => { 10,333 ( 0.00%) self.final_ty = Some(v); . if let Some(e) = expression { 20,666 ( 0.00%) match self.expressions { . Expressions::Dynamic(ref mut buffer) => buffer.push(e), 20,320 ( 0.00%) Expressions::UpFront(coercion_sites) => { . // if the user gave us an array to validate, check that we got . // the next expression in the list, as expected 40,429 ( 0.00%) assert_eq!( 30,480 ( 0.00%) coercion_sites[self.pushed].as_coercion_site().hir_id, . e.hir_id . ); . } . } 41,505 ( 0.00%) self.pushed += 1; . } . } . Err(coercion_error) => { . let (expected, found) = if label_expression_as_expected { . // In the case where this is a "forced unit", like . // `break`, we want to call the `()` "expected" . // since it is implied by the syntax. . // (Note: not all force-units work this way.)" -- line 1434 ---------------------------------------- -- line 1707 ---------------------------------------- . if let ty::Dynamic(..) = ty.kind() { . return true; . } . } . } . false . } . 512 ( 0.00%) pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> { 1,116 ( 0.00%) if let Some(final_ty) = self.final_ty { . final_ty . } else { . // If we only had inputs that were of type `!` (or no . // inputs at all), then the final type is `!`. 86 ( 0.00%) assert_eq!(self.pushed, 0); 43 ( 0.00%) fcx.tcx.types.never . } 640 ( 0.00%) } . } . . /// Something that can be converted into an expression to which we can . /// apply a coercion. . pub trait AsCoercionSite { . fn as_coercion_site(&self) -> &hir::Expr<'_>; . } . -- line 1732 ---------------------------------------- -- line 1736 ---------------------------------------- . } . } . . impl<'a, T> AsCoercionSite for &'a T . where . T: AsCoercionSite, . { . fn as_coercion_site(&self) -> &hir::Expr<'_> { 105 ( 0.00%) (**self).as_coercion_site() . } . } . . impl AsCoercionSite for ! { . fn as_coercion_site(&self) -> &hir::Expr<'_> { . unreachable!() . } . } . . impl AsCoercionSite for hir::Arm<'_> { . fn as_coercion_site(&self) -> &hir::Expr<'_> { 212 ( 0.00%) &self.body . } . } 1,103,826 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 84 ---------------------------------------- . pub struct SessionGlobals { . symbol_interner: symbol::Interner, . span_interner: Lock, . hygiene_data: Lock, . source_map: Lock>>, . } . . impl SessionGlobals { 12 ( 0.00%) pub fn new(edition: Edition) -> SessionGlobals { 50 ( 0.00%) SessionGlobals { 2 ( 0.00%) symbol_interner: symbol::Interner::fresh(), . span_interner: Lock::new(span_encoding::SpanInterner::default()), 6 ( 0.00%) hygiene_data: Lock::new(hygiene::HygieneData::new(edition)), . source_map: Lock::new(None), . } 10 ( 0.00%) } . } . . #[inline] . pub fn create_session_globals_then(edition: Edition, f: impl FnOnce() -> R) -> R { 1 ( 0.00%) assert!( . !SESSION_GLOBALS.is_set(), . "SESSION_GLOBALS should never be overwritten! \ . Use another thread if you need another SessionGlobals" . ); 3 ( 0.00%) let session_globals = SessionGlobals::new(edition); 7 ( 0.00%) SESSION_GLOBALS.set(&session_globals, f) 1 ( 0.00%) } . . #[inline] . pub fn set_session_globals_then(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R { . assert!( . !SESSION_GLOBALS.is_set(), . "SESSION_GLOBALS should never be overwritten! \ . Use another thread if you need another SessionGlobals" . ); -- line 119 ---------------------------------------- -- line 120 ---------------------------------------- . SESSION_GLOBALS.set(session_globals, f) . } . . #[inline] . pub fn create_default_session_if_not_set_then(f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 4 ( 0.00%) create_session_if_not_set_then(edition::DEFAULT_EDITION, f) . } . . #[inline] . pub fn create_session_if_not_set_then(edition: Edition, f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 1 ( 0.00%) if !SESSION_GLOBALS.is_set() { 3 ( 0.00%) let session_globals = SessionGlobals::new(edition); 11 ( 0.00%) SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f)) 1 ( 0.00%) } else { . SESSION_GLOBALS.with(f) . } . } . . #[inline] . pub fn with_session_globals(f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 1,054,691 ( 0.02%) SESSION_GLOBALS.with(f) . } . . #[inline] . pub fn create_default_session_globals_then(f: impl FnOnce() -> R) -> R { . create_session_globals_then(edition::DEFAULT_EDITION, f) . } . . // If this ever becomes non thread-local, `decode_syntax_context` . // and `decode_expn_id` will need to be updated to handle concurrent . // deserialization. . scoped_tls::scoped_thread_local!(static SESSION_GLOBALS: SessionGlobals); . . // FIXME: We should use this enum or something like it to get rid of the . // use of magic `/rust/1.x/...` paths across the board. 21 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd)] 1,164 ( 0.00%) #[derive(Decodable)] . pub enum RealFileName { . LocalPath(PathBuf), . /// For remapped paths (namely paths into libstd that have been mapped . /// to the appropriate spot on the local host's file system, and local file . /// system paths that have been remapped with `FilePathMapping`), . Remapped { . /// `local_path` is the (host-dependent) local path to the file. This is . /// None if the file was imported from another crate -- line 173 ---------------------------------------- -- line 179 ---------------------------------------- . } . . impl Hash for RealFileName { . fn hash(&self, state: &mut H) { . // To prevent #70924 from happening again we should only hash the . // remapped (virtualized) path if that exists. This is because . // virtualized paths to sysroot crates (/rust/$hash or /rust/$version) . // remain stable even if the corresponding local_path changes 2,992 ( 0.00%) self.remapped_path_if_available().hash(state) . } . } . . // This is functionally identical to #[derive(Encodable)], with the exception of . // an added assert statement . impl Encodable for RealFileName { . fn encode(&self, encoder: &mut S) -> Result<(), S::Error> { 8 ( 0.00%) encoder.emit_enum(|encoder| match *self { . RealFileName::LocalPath(ref local_path) => { 32 ( 0.00%) encoder.emit_enum_variant("LocalPath", 0, 1, |encoder| { . encoder.emit_enum_variant_arg(true, |encoder| local_path.encode(encoder))?; . Ok(()) . }) . } . . RealFileName::Remapped { ref local_path, ref virtual_name } => encoder . .emit_enum_variant("Remapped", 1, 2, |encoder| { . // For privacy and build reproducibility, we must not embed host-dependant path in artifacts -- line 205 ---------------------------------------- -- line 224 ---------------------------------------- . p.as_ref().map(PathBuf::as_path) . } . } . } . . /// Returns the path suitable for reading from the file system on the local host, . /// if this information exists. . /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that. 4 ( 0.00%) pub fn into_local_path(self) -> Option { 4 ( 0.00%) match self { . RealFileName::LocalPath(p) => Some(p), . RealFileName::Remapped { local_path: p, virtual_name: _ } => p, . } 6 ( 0.00%) } . . /// Returns the path suitable for embedding into build artifacts. This would still . /// be a local path if it has not been remapped. A remapped path will not correspond . /// to a valid file system path: see `local_path_if_available()` for something that . /// is more likely to return paths into the local host file system. . pub fn remapped_path_if_available(&self) -> &Path { 13,146 ( 0.00%) match self { . RealFileName::LocalPath(p) . | RealFileName::Remapped { local_path: _, virtual_name: p } => &p, . } 5 ( 0.00%) } . . /// Returns the path suitable for reading from the file system on the local host, . /// if this information exists. Otherwise returns the remapped name. . /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that. . pub fn local_path_if_available(&self) -> &Path { 4 ( 0.00%) match self { . RealFileName::LocalPath(path) . | RealFileName::Remapped { local_path: None, virtual_name: path } . | RealFileName::Remapped { local_path: Some(path), virtual_name: _ } => path, . } . } . 1,192 ( 0.00%) pub fn to_string_lossy(&self, display_pref: FileNameDisplayPreference) -> Cow<'_, str> { 5,983 ( 0.00%) match display_pref { . FileNameDisplayPreference::Local => self.local_path_if_available().to_string_lossy(), . FileNameDisplayPreference::Remapped => { . self.remapped_path_if_available().to_string_lossy() . } . } 1,788 ( 0.00%) } . } . . /// Differentiates between real files and common virtual files. 6,164 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)] 7,076 ( 0.00%) #[derive(Decodable, Encodable)] . pub enum FileName { . Real(RealFileName), . /// Call to `quote!`. . QuoteExpansion(u64), . /// Command line. . Anon(u64), . /// Hack in `src/librustc_ast/parse.rs`. . // FIXME(jseyfried) -- line 281 ---------------------------------------- -- line 288 ---------------------------------------- . /// Custom sources for explicit parser calls from plugins and drivers. . Custom(String), . DocTest(PathBuf, isize), . /// Post-substitution inline assembly from LLVM. . InlineAsm(u64), . } . . impl From for FileName { 28 ( 0.00%) fn from(p: PathBuf) -> Self { 8 ( 0.00%) assert!(!p.to_string_lossy().ends_with('>')); 24 ( 0.00%) FileName::Real(RealFileName::LocalPath(p)) 28 ( 0.00%) } . } . 34 ( 0.00%) #[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)] . pub enum FileNameDisplayPreference { . Remapped, . Local, . } . . pub struct FileNameDisplay<'a> { . inner: &'a FileName, . display_pref: FileNameDisplayPreference, . } . . impl fmt::Display for FileNameDisplay<'_> { 17,504 ( 0.00%) fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { . use FileName::*; 26,256 ( 0.00%) match *self.inner { . Real(ref name) => { 26,256 ( 0.00%) write!(fmt, "{}", name.to_string_lossy(self.display_pref)) . } . QuoteExpansion(_) => write!(fmt, ""), . MacroExpansion(_) => write!(fmt, ""), . Anon(_) => write!(fmt, ""), . ProcMacroSourceCode(_) => write!(fmt, ""), . CfgSpec(_) => write!(fmt, ""), . CliCrateAttr(_) => write!(fmt, ""), . Custom(ref s) => write!(fmt, "<{}>", s), . DocTest(ref path, _) => write!(fmt, "{}", path.display()), . InlineAsm(_) => write!(fmt, ""), . } 21,880 ( 0.00%) } . } . . impl FileNameDisplay<'_> { 1,660 ( 0.00%) pub fn to_string_lossy(&self) -> Cow<'_, str> { 1,245 ( 0.00%) match self.inner { 415 ( 0.00%) FileName::Real(ref inner) => inner.to_string_lossy(self.display_pref), . _ => Cow::from(format!("{}", self)), . } 1,660 ( 0.00%) } . } . . impl FileName { . pub fn is_real(&self) -> bool { . use FileName::*; 9,844 ( 0.00%) match *self { . Real(_) => true, . Anon(_) . | MacroExpansion(_) . | ProcMacroSourceCode(_) . | CfgSpec(_) . | CliCrateAttr(_) . | Custom(_) . | QuoteExpansion(_) . | DocTest(_, _) . | InlineAsm(_) => false, . } . } . 4,749 ( 0.00%) pub fn prefer_remapped(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Remapped } 9,498 ( 0.00%) } . . // This may include transient local filesystem information. . // Must not be embedded in build outputs. 4 ( 0.00%) pub fn prefer_local(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local } 8 ( 0.00%) } . . pub fn display(&self, display_pref: FileNameDisplayPreference) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref } . } . . pub fn macro_expansion_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); -- line 375 ---------------------------------------- -- line 423 ---------------------------------------- . /// that the length of the span is equal to `span.hi - span.lo`; there may be space in the . /// [`BytePos`] range between files. . /// . /// `SpanData` is public because `Span` uses a thread-local interner and can't be . /// sent to other threads, but some pieces of performance infra run in a separate thread. . /// Using `Span` is generally preferred. . #[derive(Clone, Copy, Hash, PartialEq, Eq)] . pub struct SpanData { 11 ( 0.00%) pub lo: BytePos, 11 ( 0.00%) pub hi: BytePos, . /// Information about where the macro came from, if this piece of . /// code was created by a macro expansion. 27 ( 0.00%) pub ctxt: SyntaxContext, 9 ( 0.00%) pub parent: Option, . } . . // Order spans by position in the file. . impl Ord for SpanData { . fn cmp(&self, other: &Self) -> Ordering { . let SpanData { . lo: s_lo, . hi: s_hi, -- line 444 ---------------------------------------- -- line 485 ---------------------------------------- . } . #[inline] . pub fn with_parent(&self, parent: Option) -> Span { . Span::new(self.lo, self.hi, self.ctxt, parent) . } . /// Returns `true` if this is a dummy span with any hygienic context. . #[inline] . pub fn is_dummy(self) -> bool { 570,183 ( 0.01%) self.lo.0 == 0 && self.hi.0 == 0 . } . /// Returns `true` if `self` fully encloses `other`. . pub fn contains(self, other: Self) -> bool { 168 ( 0.00%) self.lo <= other.lo && other.hi <= self.hi . } . } . . // The interner is pointed to by a thread local value which is only set on the main thread . // with parallelization is disabled. So we don't allow `Span` to transfer between threads . // to avoid panics and other errors, even though it would be memory safe to do so. . #[cfg(not(parallel_compiler))] . impl !Send for Span {} . #[cfg(not(parallel_compiler))] . impl !Sync for Span {} . . impl PartialOrd for Span { 17,784 ( 0.00%) fn partial_cmp(&self, rhs: &Self) -> Option { 13,338 ( 0.00%) PartialOrd::partial_cmp(&self.data(), &rhs.data()) 17,784 ( 0.00%) } . } . impl Ord for Span { . fn cmp(&self, rhs: &Self) -> Ordering { . Ord::cmp(&self.data(), &rhs.data()) . } . } . . /// A collection of `Span`s. -- line 520 ---------------------------------------- -- line 532 ---------------------------------------- . } . . impl Span { . #[inline] . pub fn lo(self) -> BytePos { . self.data().lo . } . #[inline] 155,403 ( 0.00%) pub fn with_lo(self, lo: BytePos) -> Span { . self.data().with_lo(lo) 103,602 ( 0.00%) } . #[inline] 728 ( 0.00%) pub fn hi(self) -> BytePos { . self.data().hi 728 ( 0.00%) } . #[inline] 2,700 ( 0.00%) pub fn with_hi(self, hi: BytePos) -> Span { . self.data().with_hi(hi) 1,800 ( 0.00%) } . #[inline] . pub fn ctxt(self) -> SyntaxContext { . self.data_untracked().ctxt . } . #[inline] 455 ( 0.00%) pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span { . self.data_untracked().with_ctxt(ctxt) 273 ( 0.00%) } . #[inline] . pub fn parent(self) -> Option { . self.data().parent . } . #[inline] . pub fn with_parent(self, ctxt: Option) -> Span { . self.data().with_parent(ctxt) . } -- line 566 ---------------------------------------- -- line 600 ---------------------------------------- . /// Returns a new span representing an empty span at the beginning of this span. . #[inline] . pub fn shrink_to_lo(self) -> Span { . let span = self.data_untracked(); . span.with_hi(span.lo) . } . /// Returns a new span representing an empty span at the end of this span. . #[inline] 138 ( 0.00%) pub fn shrink_to_hi(self) -> Span { . let span = self.data_untracked(); . span.with_lo(span.hi) 92 ( 0.00%) } . . #[inline] . /// Returns `true` if `hi == lo`. . pub fn is_empty(self) -> bool { . let span = self.data_untracked(); . span.hi == span.lo . } . . /// Returns `self` if `self` is not the dummy span, and `other` otherwise. . pub fn substitute_dummy(self, other: Span) -> Span { . if self.is_dummy() { other } else { self } . } . . /// Returns `true` if `self` fully encloses `other`. 504 ( 0.00%) pub fn contains(self, other: Span) -> bool { . let span = self.data(); . let other = other.data(); . span.contains(other) 336 ( 0.00%) } . . /// Returns `true` if `self` touches `other`. . pub fn overlaps(self, other: Span) -> bool { . let span = self.data(); . let other = other.data(); . span.lo < other.hi && other.lo < span.hi . } . -- line 638 ---------------------------------------- -- line 650 ---------------------------------------- . pub fn trim_start(self, other: Span) -> Option { . let span = self.data(); . let other = other.data(); . if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None } . } . . /// Returns the source span -- this is either the supplied span, or the span for . /// the macro callsite that expanded to it. 10 ( 0.00%) pub fn source_callsite(self) -> Span { . let expn_data = self.ctxt().outer_expn_data(); 4 ( 0.00%) if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self } 8 ( 0.00%) } . . /// The `Span` for the tokens in the previous macro expansion from which `self` was generated, . /// if any. . pub fn parent_callsite(self) -> Option { . let expn_data = self.ctxt().outer_expn_data(); . if !expn_data.is_root() { Some(expn_data.call_site) } else { None } . } . . /// Walk down the expansion ancestors to find a span that's contained within `outer`. 230 ( 0.00%) pub fn find_ancestor_inside(mut self, outer: Span) -> Option { 115 ( 0.00%) while !outer.contains(self) { . self = self.parent_callsite()?; . } . Some(self) 253 ( 0.00%) } . . /// Edition of the crate from which this span came. 44,628 ( 0.00%) pub fn edition(self) -> edition::Edition { . self.ctxt().edition() 29,752 ( 0.00%) } . . #[inline] . pub fn rust_2015(self) -> bool { 14,421 ( 0.00%) self.edition() == edition::Edition::Edition2015 . } . . #[inline] . pub fn rust_2018(self) -> bool { 518 ( 0.00%) self.edition() >= edition::Edition::Edition2018 . } . . #[inline] . pub fn rust_2021(self) -> bool { 448 ( 0.00%) self.edition() >= edition::Edition::Edition2021 . } . . /// Returns the source callee. . /// . /// Returns `None` if the supplied span has no expansion trace, . /// else returns the `ExpnData` for the macro definition . /// corresponding to the source callsite. . pub fn source_callee(self) -> Option { -- line 703 ---------------------------------------- -- line 707 ---------------------------------------- . } . let expn_data = self.ctxt().outer_expn_data(); . if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None } . } . . /// Checks if a span is "internal" to a macro in which `#[unstable]` . /// items can be used (that is, a macro marked with . /// `#[allow_internal_unstable]`). 45 ( 0.00%) pub fn allows_unstable(self, feature: Symbol) -> bool { 9 ( 0.00%) self.ctxt() . .outer_expn_data() . .allow_internal_unstable . .map_or(false, |features| features.iter().any(|&f| f == feature)) 36 ( 0.00%) } . . /// Checks if this span arises from a compiler desugaring of kind `kind`. 83,727 ( 0.00%) pub fn is_desugaring(self, kind: DesugaringKind) -> bool { 71,766 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => k == kind, . _ => false, . } 59,805 ( 0.00%) } . . /// Returns the compiler desugaring that created this span, or `None` . /// if this span is not from a desugaring. 110 ( 0.00%) pub fn desugaring_kind(self) -> Option { 132 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => Some(k), . _ => None, . } 88 ( 0.00%) } . . /// Checks if a span is "internal" to a macro in which `unsafe` . /// can be used without triggering the `unsafe_code` lint. . // (that is, a macro marked with `#[allow_internal_unsafe]`). . pub fn allows_unsafe(self) -> bool { . self.ctxt().outer_expn_data().allow_internal_unsafe . } . -- line 745 ---------------------------------------- -- line 767 ---------------------------------------- . . /// Returns a `Span` that would enclose both `self` and `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^^^^ . /// ``` 1,037,201 ( 0.02%) pub fn to(self, end: Span) -> Span { . let span_data = self.data(); . let end_data = end.data(); . // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480). . // Return the macro span on its own to avoid weird diagnostic output. It is preferable to . // have an incomplete span than a completely nonsensical one. 188,487 ( 0.00%) if span_data.ctxt != end_data.ctxt { 90 ( 0.00%) if span_data.ctxt == SyntaxContext::root() { . return end; 77 ( 0.00%) } else if end_data.ctxt == SyntaxContext::root() { . return self; . } . // Both spans fall within a macro. . // FIXME(estebank): check if it is the *same* macro. . } . Span::new( . cmp::min(span_data.lo, end_data.lo), . cmp::max(span_data.hi, end_data.hi), . if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt }, 659,477 ( 0.01%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 848,619 ( 0.02%) } . . /// Returns a `Span` between the end of `self` to the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^ . /// ``` 132 ( 0.00%) pub fn between(self, end: Span) -> Span { . let span = self.data(); . let end = end.data(); . Span::new( . span.hi, . end.lo, . if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt }, 84 ( 0.00%) if span.parent == end.parent { span.parent } else { None }, . ) 96 ( 0.00%) } . . /// Returns a `Span` from the beginning of `self` until the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^ . /// ``` 451 ( 0.00%) pub fn until(self, end: Span) -> Span { . // Most of this function's body is copied from `to`. . // We can't just do `self.to(end.shrink_to_lo())`, . // because to also does some magic where it uses min/max so . // it can handle overlapping spans. Some advanced mis-use of . // `until` with different ctxts makes this visible. . let span_data = self.data(); . let end_data = end.data(); . // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480). . // Return the macro span on its own to avoid weird diagnostic output. It is preferable to . // have an incomplete span than a completely nonsensical one. 82 ( 0.00%) if span_data.ctxt != end_data.ctxt { . if span_data.ctxt == SyntaxContext::root() { . return end; . } else if end_data.ctxt == SyntaxContext::root() { . return self; . } . // Both spans fall within a macro. . // FIXME(estebank): check if it is the *same* macro. . } . Span::new( . span_data.lo, . end_data.lo, . if end_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt }, 287 ( 0.00%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 369 ( 0.00%) } . . pub fn from_inner(self, inner: InnerSpan) -> Span { . let span = self.data(); . Span::new( . span.lo + BytePos::from_usize(inner.start), . span.lo + BytePos::from_usize(inner.end), . span.ctxt, . span.parent, . ) . } . . /// Equivalent of `Span::def_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span { 124 ( 0.00%) self.with_ctxt_from_mark(expn_id, Transparency::Opaque) . } . . /// Equivalent of `Span::call_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_call_site_ctxt(self, expn_id: ExpnId) -> Span { 4 ( 0.00%) self.with_ctxt_from_mark(expn_id, Transparency::Transparent) . } . . /// Equivalent of `Span::mixed_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_mixed_site_ctxt(self, expn_id: ExpnId) -> Span { . self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent) . } . . /// Produces a span with the same location as `self` and context produced by a macro with the . /// given ID and transparency, assuming that macro was defined directly and not produced by . /// some other macro (which is the case for built-in and procedural macros). 768 ( 0.00%) pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { . self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency)) 448 ( 0.00%) } . . #[inline] . pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { . let span = self.data(); 360 ( 0.00%) span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency)) . } . . #[inline] . pub fn remove_mark(&mut self) -> ExpnId { . let mut span = self.data(); . let mark = span.ctxt.remove_mark(); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark -- line 897 ---------------------------------------- -- line 901 ---------------------------------------- . pub fn adjust(&mut self, expn_id: ExpnId) -> Option { . let mut span = self.data(); . let mark = span.ctxt.adjust(expn_id); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } . . #[inline] 321,642 ( 0.01%) pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option { 214,428 ( 0.00%) let mut span = self.data(); 178,658 ( 0.00%) let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id); 321,642 ( 0.01%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark 357,348 ( 0.01%) } . . #[inline] . pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option> { . let mut span = self.data(); . let mark = span.ctxt.glob_adjust(expn_id, glob_span); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } . . #[inline] . pub fn reverse_glob_adjust( . &mut self, . expn_id: ExpnId, . glob_span: Span, . ) -> Option> { 32 ( 0.00%) let mut span = self.data(); 64 ( 0.00%) let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span); 128 ( 0.00%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } . . #[inline] 120,960 ( 0.00%) pub fn normalize_to_macros_2_0(self) -> Span { . let span = self.data(); . span.with_ctxt(span.ctxt.normalize_to_macros_2_0()) 105,840 ( 0.00%) } . . #[inline] . pub fn normalize_to_macro_rules(self) -> Span { . let span = self.data(); . span.with_ctxt(span.ctxt.normalize_to_macro_rules()) . } . } . -- line 948 ---------------------------------------- -- line 958 ---------------------------------------- . . /// What label should we attach to this span (if any)? . pub label: Option, . } . . impl Default for Span { . fn default() -> Self { . DUMMY_SP 2 ( 0.00%) } . } . . impl Encodable for Span { . default fn encode(&self, s: &mut E) -> Result<(), E::Error> { . let span = self.data(); . s.emit_struct(false, |s| { . s.emit_struct_field("lo", true, |s| span.lo.encode(s))?; . s.emit_struct_field("hi", false, |s| span.hi.encode(s)) -- line 974 ---------------------------------------- -- line 990 ---------------------------------------- . /// any spans that are debug-printed during the closure's execution. . /// . /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap` . /// (see `rustc_interface::callbacks::span_debug1`). However, some parts . /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before . /// a `TyCtxt` is available. In this case, we fall back to . /// the `SourceMap` provided to this function. If that is not available, . /// we fall back to printing the raw `Span` field values. 9 ( 0.00%) pub fn with_source_map T>(source_map: Lrc, f: F) -> T { . with_session_globals(|session_globals| { 2 ( 0.00%) *session_globals.source_map.borrow_mut() = Some(source_map); . }); . struct ClearSourceMap; . impl Drop for ClearSourceMap { . fn drop(&mut self) { . with_session_globals(|session_globals| { 1 ( 0.00%) session_globals.source_map.borrow_mut().take(); . }); . } . } . . let _guard = ClearSourceMap; 4 ( 0.00%) f() 8 ( 0.00%) } . . pub fn debug_with_source_map( . span: Span, . f: &mut fmt::Formatter<'_>, . source_map: &SourceMap, . ) -> fmt::Result { . write!(f, "{} ({:?})", source_map.span_to_diagnostic_string(span), span.ctxt()) . } -- line 1021 ---------------------------------------- -- line 1048 ---------------------------------------- . . impl MultiSpan { . #[inline] . pub fn new() -> MultiSpan { . MultiSpan { primary_spans: vec![], span_labels: vec![] } . } . . pub fn from_span(primary_span: Span) -> MultiSpan { 295 ( 0.00%) MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] } . } . . pub fn from_spans(mut vec: Vec) -> MultiSpan { . vec.sort(); 10 ( 0.00%) MultiSpan { primary_spans: vec, span_labels: vec![] } . } . . pub fn push_span_label(&mut self, span: Span, label: String) { . self.span_labels.push((span, label)); . } . . /// Selects the first primary span (if any). . pub fn primary_span(&self) -> Option { . self.primary_spans.first().cloned() 19 ( 0.00%) } . . /// Returns all primary spans. . pub fn primary_spans(&self) -> &[Span] { . &self.primary_spans . } . . /// Returns `true` if any of the primary spans are displayable. . pub fn has_primary_spans(&self) -> bool { -- line 1079 ---------------------------------------- -- line 1139 ---------------------------------------- . . /// Returns `true` if any of the span labels is displayable. . pub fn has_span_labels(&self) -> bool { . self.span_labels.iter().any(|(sp, _)| !sp.is_dummy()) . } . } . . impl From for MultiSpan { 295 ( 0.00%) fn from(span: Span) -> MultiSpan { . MultiSpan::from_span(span) 295 ( 0.00%) } . } . . impl From> for MultiSpan { 10 ( 0.00%) fn from(spans: Vec) -> MultiSpan { 8 ( 0.00%) MultiSpan::from_spans(spans) 10 ( 0.00%) } . } . . /// Identifies an offset of a multi-byte character in a `SourceFile`. 33 ( 0.00%) #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub struct MultiByteChar { . /// The absolute offset of the character in the `SourceMap`. . pub pos: BytePos, . /// The number of bytes, `>= 2`. . pub bytes: u8, . } . . /// Identifies an offset of a non-narrow character in a `SourceFile`. 328 ( 0.00%) #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub enum NonNarrowChar { . /// Represents a zero-width character. . ZeroWidth(BytePos), . /// Represents a wide (full-width) character. . Wide(BytePos), . /// Represents a tab character, represented visually with a width of 4 characters. . Tab(BytePos), . } -- line 1176 ---------------------------------------- -- line 1201 ---------------------------------------- . } . } . } . . impl Add for NonNarrowChar { . type Output = Self; . . fn add(self, rhs: BytePos) -> Self { 552 ( 0.00%) match self { . NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs), . NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs), . NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs), . } . } . } . . impl Sub for NonNarrowChar { . type Output = Self; . 164 ( 0.00%) fn sub(self, rhs: BytePos) -> Self { 552 ( 0.00%) match self { . NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs), . NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs), . NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs), . } 492 ( 0.00%) } . } . . /// Identifies an offset of a character that was normalized away from `SourceFile`. . #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub struct NormalizedPos { . /// The absolute offset of the character in the `SourceMap`. . pub pos: BytePos, . /// The difference between original and normalized string at position. . pub diff: u32, . } . 12 ( 0.00%) #[derive(PartialEq, Eq, Clone, Debug)] . pub enum ExternalSource { . /// No external source has to be loaded, since the `SourceFile` represents a local crate. . Unneeded, . Foreign { . kind: ExternalSourceKind, . /// This SourceFile's byte-offset within the source_map of its original crate. . original_start_pos: BytePos, . /// The end of this SourceFile within the source_map of its original crate. -- line 1246 ---------------------------------------- -- line 1257 ---------------------------------------- . AbsentOk, . /// A failed attempt has been made to load the external source. . AbsentErr, . Unneeded, . } . . impl ExternalSource { . pub fn get_source(&self) -> Option<&Lrc> { 4 ( 0.00%) match self { . ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src), . _ => None, . } . } . } . . #[derive(Debug)] . pub struct OffsetOverflowError; . 1,180 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)] . pub enum SourceFileHashAlgorithm { . Md5, . Sha1, . Sha256, . } . . impl FromStr for SourceFileHashAlgorithm { . type Err = (); -- line 1283 ---------------------------------------- -- line 1290 ---------------------------------------- . _ => Err(()), . } . } . } . . rustc_data_structures::impl_stable_hash_via_hash!(SourceFileHashAlgorithm); . . /// The hash of the on-disk source file used for debug info. 24 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Debug)] 2,360 ( 0.00%) #[derive(HashStable_Generic, Encodable, Decodable)] . pub struct SourceFileHash { . pub kind: SourceFileHashAlgorithm, . value: [u8; 32], . } . . impl SourceFileHash { . pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash { . let mut hash = SourceFileHash { kind, value: Default::default() }; . let len = hash.hash_len(); . let value = &mut hash.value[..len]; . let data = src.as_bytes(); . match kind { . SourceFileHashAlgorithm::Md5 => { 12 ( 0.00%) value.copy_from_slice(&Md5::digest(data)); . } . SourceFileHashAlgorithm::Sha1 => { . value.copy_from_slice(&Sha1::digest(data)); . } . SourceFileHashAlgorithm::Sha256 => { . value.copy_from_slice(&Sha256::digest(data)); . } . } -- line 1321 ---------------------------------------- -- line 1324 ---------------------------------------- . . /// Check if the stored hash matches the hash of the string. . pub fn matches(&self, src: &str) -> bool { . Self::new(self.kind, src) == *self . } . . /// The bytes of the hash. . pub fn hash_bytes(&self) -> &[u8] { 156 ( 0.00%) let len = self.hash_len(); 156 ( 0.00%) &self.value[..len] 156 ( 0.00%) } . . fn hash_len(&self) -> usize { 324 ( 0.00%) match self.kind { . SourceFileHashAlgorithm::Md5 => 16, . SourceFileHashAlgorithm::Sha1 => 20, . SourceFileHashAlgorithm::Sha256 => 32, . } . } . } . . /// A single source in the [`SourceMap`]. 232 ( 0.00%) #[derive(Clone)] . pub struct SourceFile { . /// The name of the file that the source came from. Source that doesn't . /// originate from files has names between angle brackets by convention . /// (e.g., ``). . pub name: FileName, . /// The complete source code. 4 ( 0.00%) pub src: Option>, . /// The source code's hash. . pub src_hash: SourceFileHash, . /// The external source code (used for external crates, which will have a `None` . /// value as `self.src`. . pub external_src: Lock, . /// The start position of this source in the `SourceMap`. . pub start_pos: BytePos, . /// The end position of this source in the `SourceMap`. -- line 1361 ---------------------------------------- -- line 1364 ---------------------------------------- . pub lines: Vec, . /// Locations of multi-byte characters in the source code. . pub multibyte_chars: Vec, . /// Width of characters that are not narrow in the source code. . pub non_narrow_chars: Vec, . /// Locations of characters removed during normalization. . pub normalized_pos: Vec, . /// A hash of the filename, used for speeding up hashing in incremental compilation. 4 ( 0.00%) pub name_hash: u128, . /// Indicates which crate this `SourceFile` was imported from. 4 ( 0.00%) pub cnum: CrateNum, . } . . impl Encodable for SourceFile { . fn encode(&self, s: &mut S) -> Result<(), S::Error> { . s.emit_struct(false, |s| { . s.emit_struct_field("name", true, |s| self.name.encode(s))?; . s.emit_struct_field("src_hash", false, |s| self.src_hash.encode(s))?; . s.emit_struct_field("start_pos", false, |s| self.start_pos.encode(s))?; . s.emit_struct_field("end_pos", false, |s| self.end_pos.encode(s))?; . s.emit_struct_field("lines", false, |s| { . let lines = &self.lines[..]; . // Store the length. . s.emit_u32(lines.len() as u32)?; . 16 ( 0.00%) if !lines.is_empty() { . // In order to preserve some space, we exploit the fact that . // the lines list is sorted and individual lines are . // probably not that long. Because of that we can store lines . // as a difference list, using as little space as possible . // for the differences. . let max_line_length = if lines.len() == 1 { . 0 . } else { -- line 1397 ---------------------------------------- -- line 1399 ---------------------------------------- . .array_windows() . .map(|&[fst, snd]| snd - fst) . .map(|bp| bp.to_usize()) . .max() . .unwrap() . }; . . let bytes_per_diff: u8 = match max_line_length { 8 ( 0.00%) 0..=0xFF => 1, . 0x100..=0xFFFF => 2, . _ => 4, . }; . . // Encode the number of bytes used per diff. . bytes_per_diff.encode(s)?; . . // Encode the first element. . lines[0].encode(s)?; . . let diff_iter = lines.array_windows().map(|&[fst, snd]| snd - fst); . 8 ( 0.00%) match bytes_per_diff { . 1 => { . for diff in diff_iter { . (diff.0 as u8).encode(s)? . } . } . 2 => { . for diff in diff_iter { . (diff.0 as u16).encode(s)? -- line 1428 ---------------------------------------- -- line 1436 ---------------------------------------- . _ => unreachable!(), . } . } . . Ok(()) . })?; . s.emit_struct_field("multibyte_chars", false, |s| self.multibyte_chars.encode(s))?; . s.emit_struct_field("non_narrow_chars", false, |s| self.non_narrow_chars.encode(s))?; 12 ( 0.00%) s.emit_struct_field("name_hash", false, |s| self.name_hash.encode(s))?; . s.emit_struct_field("normalized_pos", false, |s| self.normalized_pos.encode(s))?; 44 ( 0.00%) s.emit_struct_field("cnum", false, |s| self.cnum.encode(s)) . }) . } . } . . impl Decodable for SourceFile { 5,310 ( 0.00%) fn decode(d: &mut D) -> SourceFile { . d.read_struct(|d| { . let name: FileName = d.read_struct_field("name", |d| Decodable::decode(d)); . let src_hash: SourceFileHash = . d.read_struct_field("src_hash", |d| Decodable::decode(d)); . let start_pos: BytePos = d.read_struct_field("start_pos", |d| Decodable::decode(d)); . let end_pos: BytePos = d.read_struct_field("end_pos", |d| Decodable::decode(d)); . let lines: Vec = d.read_struct_field("lines", |d| { . let num_lines: u32 = Decodable::decode(d); 590 ( 0.00%) let mut lines = Vec::with_capacity(num_lines as usize); . . if num_lines > 0 { . // Read the number of bytes used per diff. . let bytes_per_diff: u8 = Decodable::decode(d); . . // Read the first element. . let mut line_start: BytePos = Decodable::decode(d); . lines.push(line_start); . . for _ in 1..num_lines { 968,912 ( 0.02%) let diff = match bytes_per_diff { . 1 => d.read_u8() as u32, . 2 => d.read_u16() as u32, . 4 => d.read_u32(), . _ => unreachable!(), . }; . . line_start = line_start + BytePos(diff); . -- line 1480 ---------------------------------------- -- line 1483 ---------------------------------------- . } . . lines . }); . let multibyte_chars: Vec = . d.read_struct_field("multibyte_chars", |d| Decodable::decode(d)); . let non_narrow_chars: Vec = . d.read_struct_field("non_narrow_chars", |d| Decodable::decode(d)); 1,180 ( 0.00%) let name_hash: u128 = d.read_struct_field("name_hash", |d| Decodable::decode(d)); . let normalized_pos: Vec = . d.read_struct_field("normalized_pos", |d| Decodable::decode(d)); . let cnum: CrateNum = d.read_struct_field("cnum", |d| Decodable::decode(d)); 6,490 ( 0.00%) SourceFile { 4,720 ( 0.00%) name, . start_pos, . end_pos, . src: None, 2,360 ( 0.00%) src_hash, . // Unused - the metadata decoder will construct . // a new SourceFile, filling in `external_src` properly . external_src: Lock::new(ExternalSource::Unneeded), 2,360 ( 0.00%) lines, 2,360 ( 0.00%) multibyte_chars, 2,360 ( 0.00%) non_narrow_chars, 2,360 ( 0.00%) normalized_pos, . name_hash, . cnum, . } . }) 5,310 ( 0.00%) } . } . . impl fmt::Debug for SourceFile { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(fmt, "SourceFile({:?})", self.name) . } . } . . impl SourceFile { 44 ( 0.00%) pub fn new( . name: FileName, . mut src: String, . start_pos: BytePos, . hash_kind: SourceFileHashAlgorithm, . ) -> Self { . // Compute the file hash before any normalization. . let src_hash = SourceFileHash::new(hash_kind, &src); 12 ( 0.00%) let normalized_pos = normalize_src(&mut src, start_pos); . . let name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 8 ( 0.00%) name.hash(&mut hasher); . hasher.finish::() . }; 8 ( 0.00%) let end_pos = start_pos.to_usize() + src.len(); 12 ( 0.00%) assert!(end_pos <= u32::MAX as usize); . 48 ( 0.00%) let (lines, multibyte_chars, non_narrow_chars) = 8 ( 0.00%) analyze_source_file::analyze_source_file(&src, start_pos); . 68 ( 0.00%) SourceFile { . name, . src: Some(Lrc::new(src)), 44 ( 0.00%) src_hash, . external_src: Lock::new(ExternalSource::Unneeded), . start_pos, . end_pos: Pos::from_usize(end_pos), 16 ( 0.00%) lines, 16 ( 0.00%) multibyte_chars, 16 ( 0.00%) non_narrow_chars, 16 ( 0.00%) normalized_pos, . name_hash, . cnum: LOCAL_CRATE, . } 36 ( 0.00%) } . . /// Returns the `BytePos` of the beginning of the current line. 67,362 ( 0.00%) pub fn line_begin_pos(&self, pos: BytePos) -> BytePos { . let line_index = self.lookup_line(pos).unwrap(); 33,681 ( 0.00%) self.lines[line_index] 67,362 ( 0.00%) } . . /// Add externally loaded source. . /// If the hash of the input doesn't match or no input is supplied via None, . /// it is interpreted as an error and the corresponding enum variant is set. . /// The return value signifies whether some kind of source is present. 266 ( 0.00%) pub fn add_external_src(&self, get_src: F) -> bool . where . F: FnOnce() -> Option, . { 38 ( 0.00%) if matches!( 76 ( 0.00%) *self.external_src.borrow(), . ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. } . ) { . let src = get_src(); . let mut external_src = self.external_src.borrow_mut(); . // Check that no-one else have provided the source while we were getting it . if let ExternalSource::Foreign { . kind: src_kind @ ExternalSourceKind::AbsentOk, .. . } = &mut *external_src -- line 1582 ---------------------------------------- -- line 1592 ---------------------------------------- . *src_kind = ExternalSourceKind::AbsentErr; . } . . false . } else { . self.src.is_some() || external_src.get_source().is_some() . } . } else { 38 ( 0.00%) self.src.is_some() || self.external_src.borrow().get_source().is_some() . } 342 ( 0.00%) } . . /// Gets a line from the list of pre-computed line-beginnings. . /// The line number here is 0-based. . pub fn get_line(&self, line_number: usize) -> Option> { . fn get_until_newline(src: &str, begin: usize) -> &str { . // We can't use `lines.get(line_number+1)` because we might . // be parsing when we call this function and thus the current . // line is the last one we have line info for. -- line 1610 ---------------------------------------- -- line 1627 ---------------------------------------- . Some(Cow::Owned(String::from(get_until_newline(src, begin)))) . } else { . None . } . } . . pub fn is_real_file(&self) -> bool { . self.name.is_real() 4,922 ( 0.00%) } . . pub fn is_imported(&self) -> bool { . self.src.is_none() 94,763 ( 0.00%) } . . pub fn count_lines(&self) -> usize { . self.lines.len() . } . . /// Finds the line containing the given position. The return value is the . /// index into the `lines` array of this `SourceFile`, not the 1-based line . /// number. If the source_file is empty or the position is located before the . /// first line, `None` is returned. . pub fn lookup_line(&self, pos: BytePos) -> Option { 78,231 ( 0.00%) match self.lines.binary_search(&pos) { . Ok(idx) => Some(idx), . Err(0) => None, . Err(idx) => Some(idx - 1), . } . } . . pub fn line_bounds(&self, line_index: usize) -> Range { 34,587 ( 0.00%) if self.is_empty() { . return self.start_pos..self.end_pos; . } . 23,110 ( 0.00%) assert!(line_index < self.lines.len()); 34,353 ( 0.00%) if line_index == (self.lines.len() - 1) { 18 ( 0.00%) self.lines[line_index]..self.end_pos . } else { 22,888 ( 0.00%) self.lines[line_index]..self.lines[line_index + 1] . } . } . . /// Returns whether or not the file contains the given `SourceMap` byte . /// position. The position one past the end of the file is considered to be . /// contained by the file. This implies that files for which `is_empty` . /// returns true still contain one byte position according to this function. . #[inline] -- line 1674 ---------------------------------------- -- line 1692 ---------------------------------------- . Err(i) if i == 0 => 0, . Err(i) => self.normalized_pos[i - 1].diff, . }; . . BytePos::from_u32(pos.0 - self.start_pos.0 + diff) . } . . /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`. 1,236 ( 0.00%) pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos { . // The number of extra bytes due to multibyte chars in the `SourceFile`. . let mut total_extra_bytes = 0; . 3,708 ( 0.00%) for mbc in self.multibyte_chars.iter() { . debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos); 2,932 ( 0.00%) if mbc.pos < bpos { . // Every character is at least one byte, so we only . // count the actual extra bytes. 5,616 ( 0.00%) total_extra_bytes += mbc.bytes as u32 - 1; . // We should never see a byte position in the middle of a . // character. 4,680 ( 0.00%) assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32); . } else { . break; . } . } . 7,416 ( 0.00%) assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32()); 6,180 ( 0.00%) CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize) 2,472 ( 0.00%) } . . /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a . /// given `BytePos`. 4,326 ( 0.00%) pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) { 1,236 ( 0.00%) let chpos = self.bytepos_to_file_charpos(pos); 506 ( 0.00%) match self.lookup_line(pos) { . Some(a) => { . let line = a + 1; // Line numbers start at 1 618 ( 0.00%) let linebpos = self.lines[a]; 1,236 ( 0.00%) let linechpos = self.bytepos_to_file_charpos(linebpos); . let col = chpos - linechpos; . debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos); . debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos); . debug!("byte is on line: {}", line); 618 ( 0.00%) assert!(chpos >= linechpos); . (line, col) . } . None => (0, chpos), . } 4,944 ( 0.00%) } . . /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based) . /// column offset when displayed, for a given `BytePos`. 4,944 ( 0.00%) pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) { 1,854 ( 0.00%) let (line, col_or_chpos) = self.lookup_file_pos(pos); 1,236 ( 0.00%) if line > 0 { . let col = col_or_chpos; 618 ( 0.00%) let linebpos = self.lines[line - 1]; . let col_display = { . let start_width_idx = self . .non_narrow_chars . .binary_search_by_key(&linebpos, |x| x.pos()) . .unwrap_or_else(|x| x); . let end_width_idx = self . .non_narrow_chars . .binary_search_by_key(&pos, |x| x.pos()) . .unwrap_or_else(|x| x); 57 ( 0.00%) let special_chars = end_width_idx - start_width_idx; . let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx] . .iter() . .map(|x| x.width()) . .sum(); 3,090 ( 0.00%) col.0 - special_chars + non_narrow . }; . (line, col, col_display) . } else { . let chpos = col_or_chpos; . let col_display = { . let end_width_idx = self . .non_narrow_chars . .binary_search_by_key(&pos, |x| x.pos()) . .unwrap_or_else(|x| x); . let non_narrow: usize = . self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum(); . chpos.0 - end_width_idx + non_narrow . }; . (0, chpos, col_display) . } 4,326 ( 0.00%) } . } . . /// Normalizes the source code and records the normalizations. 40 ( 0.00%) fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec { . let mut normalized_pos = vec![]; . remove_bom(src, &mut normalized_pos); . normalize_newlines(src, &mut normalized_pos); . . // Offset all the positions by start_pos to match the final file positions. . for np in &mut normalized_pos { . np.pos.0 += start_pos.0; . } . . normalized_pos 36 ( 0.00%) } . . /// Removes UTF-8 BOM, if any. . fn remove_bom(src: &mut String, normalized_pos: &mut Vec) { 4 ( 0.00%) if src.starts_with('\u{feff}') { . src.drain(..3); . normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 }); . } . } . . /// Replaces `\r\n` with `\n` in-place in `src`. . /// . /// Returns error if there's a lone `\r` in the string. . fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec) { 4 ( 0.00%) if !src.as_bytes().contains(&b'\r') { . return; . } . . // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding. . // While we *can* call `as_mut_vec` and do surgery on the live string . // directly, let's rather steal the contents of `src`. This makes the code . // safe even if a panic occurs. . -- line 1816 ---------------------------------------- -- line 1877 ---------------------------------------- . ( . $( . $(#[$attr:meta])* . $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty); . )* . ) => { . $( . $(#[$attr])* 186,915 ( 0.00%) $vis struct $ident($inner_vis $inner_ty); . . impl Pos for $ident { . #[inline(always)] . fn from_usize(n: usize) -> $ident { 14,263 ( 0.00%) $ident(n as $inner_ty) . } . . #[inline(always)] . fn to_usize(&self) -> usize { 388,141 ( 0.01%) self.0 as usize . } . . #[inline(always)] . fn from_u32(n: u32) -> $ident { . $ident(n as $inner_ty) . } . . #[inline(always)] -- line 1903 ---------------------------------------- -- line 1906 ---------------------------------------- . } . } . . impl Add for $ident { . type Output = $ident; . . #[inline(always)] . fn add(self, rhs: $ident) -> $ident { 2,463,132 ( 0.05%) $ident(self.0 + rhs.0) . } . } . . impl Sub for $ident { . type Output = $ident; . . #[inline(always)] . fn sub(self, rhs: $ident) -> $ident { 3,460,628 ( 0.07%) $ident(self.0 - rhs.0) . } . } . )* . }; . } . . impl_pos! { . /// A byte offset. -- line 1931 ---------------------------------------- -- line 1946 ---------------------------------------- . impl Encodable for BytePos { . fn encode(&self, s: &mut S) -> Result<(), S::Error> { . s.emit_u32(self.0) . } . } . . impl Decodable for BytePos { . fn decode(d: &mut D) -> BytePos { 325,914 ( 0.01%) BytePos(d.read_u32()) . } . } . . // _____________________________________________________________________________ . // Loc, SourceFileAndLine, SourceFileAndBytePos . // . . /// A source code location used for error reporting. -- line 1962 ---------------------------------------- -- line 2079 ---------------------------------------- . /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column) . /// triple, which stays the same even if the containing `SourceFile` has moved . /// within the `SourceMap`. . /// . /// Also note that we are hashing byte offsets for the column, not unicode . /// codepoint offsets. For the purpose of the hash that's sufficient. . /// Also, hashing filenames is expensive so we avoid doing it twice when the . /// span starts and ends in the same file, which is almost always the case. 956,095 ( 0.02%) fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { . const TAG_VALID_SPAN: u8 = 0; . const TAG_INVALID_SPAN: u8 = 1; . const TAG_RELATIVE_SPAN: u8 = 2; . 138,485 ( 0.00%) if !ctx.hash_spans() { . return; . } . 817,610 ( 0.02%) let span = self.data_untracked(); 404,067 ( 0.01%) span.ctxt.hash_stable(ctx, hasher); 409,755 ( 0.01%) span.parent.hash_stable(ctx, hasher); . 273,389 ( 0.01%) if span.is_dummy() { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . 272,732 ( 0.01%) if let Some(parent) = span.parent { . let def_span = ctx.def_span(parent).data_untracked(); . if def_span.contains(span) { . // This span is enclosed in a definition: only hash the relative position. . Hash::hash(&TAG_RELATIVE_SPAN, hasher); . (span.lo - def_span.lo).to_u32().hash_stable(ctx, hasher); . (span.hi - def_span.lo).to_u32().hash_stable(ctx, hasher); . return; . } . } . . // If this is not an empty or invalid span, we want to hash the last . // position that belongs to it, as opposed to hashing the first . // position past it. 545,464 ( 0.01%) let (file, line_lo, col_lo, line_hi, col_hi) = match ctx.span_data_to_lines_and_cols(&span) . { 272,732 ( 0.01%) Some(pos) => pos, . None => { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . }; . . Hash::hash(&TAG_VALID_SPAN, hasher); . // We truncate the stable ID hash and line and column numbers. The chances -- line 2129 ---------------------------------------- -- line 2134 ---------------------------------------- . // hash only the length, for example, then two otherwise equal spans with . // different end locations will have the same hash. This can cause a problem . // during incremental compilation wherein a previous result for a query that . // depends on the end location of a span will be incorrectly reused when the . // end location of the span it depends on has changed (see issue #74890). A . // similar analysis applies if some query depends specifically on the length . // of the span, but we only hash the end location. So hash both. . 136,366 ( 0.00%) let col_lo_trunc = (col_lo.0 as u64) & 0xFF; . let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8; . let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32; . let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40; . let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc; 136,366 ( 0.00%) let len = (span.hi - span.lo).0; . Hash::hash(&col_line, hasher); . Hash::hash(&len, hasher); 1,092,680 ( 0.02%) } . } 3,804,928 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/hir/map/mod.rs -------------------------------------------------------------------------------- Ir -- line 17 ---------------------------------------- . use rustc_span::hygiene::MacroKind; . use rustc_span::source_map::Spanned; . use rustc_span::symbol::{kw, sym, Ident, Symbol}; . use rustc_span::Span; . use rustc_target::spec::abi::Abi; . use std::collections::VecDeque; . . fn fn_decl<'hir>(node: Node<'hir>) -> Option<&'hir FnDecl<'hir>> { 635 ( 0.00%) match node { . Node::Item(Item { kind: ItemKind::Fn(sig, _, _), .. }) . | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(sig, _), .. }) . | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(sig, _), .. }) => Some(&sig.decl), . Node::Expr(Expr { kind: ExprKind::Closure(_, fn_decl, ..), .. }) . | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, ..), .. }) => { . Some(fn_decl) . } . _ => None, . } . } . . pub fn fn_sig<'hir>(node: Node<'hir>) -> Option<&'hir FnSig<'hir>> { 104 ( 0.00%) match &node { . Node::Item(Item { kind: ItemKind::Fn(sig, _, _), .. }) . | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(sig, _), .. }) . | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(sig, _), .. }) => Some(sig), . _ => None, . } . } . . pub fn associated_body<'hir>(node: Node<'hir>) -> Option { 9,767 ( 0.00%) match node { . Node::Item(Item { . kind: ItemKind::Const(_, body) | ItemKind::Static(.., body) | ItemKind::Fn(.., body), . .. . }) . | Node::TraitItem(TraitItem { . kind: . TraitItemKind::Const(_, Some(body)) | TraitItemKind::Fn(_, TraitFn::Provided(body)), . .. . }) . | Node::ImplItem(ImplItem { . kind: ImplItemKind::Const(_, body) | ImplItemKind::Fn(_, body), . .. . }) 1,763 ( 0.00%) | Node::Expr(Expr { kind: ExprKind::Closure(.., body, _, _), .. }) => Some(*body), . . Node::AnonConst(constant) => Some(constant.body), . . _ => None, . } . } . . fn is_body_owner<'hir>(node: Node<'hir>, hir_id: HirId) -> bool { -- line 69 ---------------------------------------- -- line 83 ---------------------------------------- . pub struct ParentHirIterator<'hir> { . current_id: HirId, . map: Map<'hir>, . } . . impl<'hir> Iterator for ParentHirIterator<'hir> { . type Item = (HirId, Node<'hir>); . 469 ( 0.00%) fn next(&mut self) -> Option { 95 ( 0.00%) if self.current_id == CRATE_HIR_ID { . return None; . } . loop { . // There are nodes that do not have entries, so we need to skip them. . let parent_id = self.map.get_parent_node(self.current_id); . 297 ( 0.00%) if parent_id == self.current_id { . self.current_id = CRATE_HIR_ID; . return None; . } . 226 ( 0.00%) self.current_id = parent_id; 804 ( 0.00%) if let Some(node) = self.map.find(parent_id) { 268 ( 0.00%) return Some((parent_id, node)); . } . // If this `HirId` doesn't have an entry, skip it and look for its `parent_id`. . } 603 ( 0.00%) } . } . . /// An iterator that walks up the ancestor tree of a given `HirId`. . /// Constructed using `tcx.hir().parent_owner_iter(hir_id)`. . pub struct ParentOwnerIterator<'hir> { . current_id: HirId, . map: Map<'hir>, . } . . impl<'hir> Iterator for ParentOwnerIterator<'hir> { . type Item = (LocalDefId, OwnerNode<'hir>); . 6,489 ( 0.00%) fn next(&mut self) -> Option { 2,163 ( 0.00%) if self.current_id.local_id.index() != 0 { 451 ( 0.00%) self.current_id.local_id = ItemLocalId::new(0); 1,804 ( 0.00%) if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) { . return Some((self.current_id.owner, node.node)); . } . } 270 ( 0.00%) if self.current_id == CRATE_HIR_ID { 6 ( 0.00%) return None; . } . loop { . // There are nodes that do not have entries, so we need to skip them. . let parent_id = self.map.def_key(self.current_id.owner).parent; . . let parent_id = parent_id.map_or(CRATE_HIR_ID.owner, |local_def_index| { . let def_id = LocalDefId { local_def_index }; . self.map.local_def_id_to_hir_id(def_id).owner . }); 534 ( 0.00%) self.current_id = HirId::make_owner(parent_id); . . // If this `HirId` doesn't have an entry, skip it and look for its `parent_id`. 534 ( 0.00%) if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) { . return Some((self.current_id.owner, node.node)); . } . } 5,768 ( 0.00%) } . } . . impl<'hir> Map<'hir> { 224 ( 0.00%) pub fn krate(&self) -> &'hir Crate<'hir> { 32 ( 0.00%) self.tcx.hir_crate(()) 256 ( 0.00%) } . 7 ( 0.00%) pub fn root_module(&self) -> &'hir Mod<'hir> { 1 ( 0.00%) match self.tcx.hir_owner(CRATE_DEF_ID).map(|o| o.node) { . Some(OwnerNode::Crate(item)) => item, . _ => bug!(), . } 8 ( 0.00%) } . . pub fn items(&self) -> impl Iterator> + 'hir { . let krate = self.krate(); . krate.owners.iter().filter_map(|owner| match owner.as_ref()?.node() { . OwnerNode::Item(item) => Some(item), . _ => None, . }) . } -- line 169 ---------------------------------------- -- line 184 ---------------------------------------- . . #[inline] . pub fn def_path_hash(self, def_id: LocalDefId) -> DefPathHash { . // Accessing the DefPathHash is ok, it is incr. comp. stable. . self.tcx.untracked_resolutions.definitions.def_path_hash(def_id) . } . . #[inline] 14,364 ( 0.00%) pub fn local_def_id(&self, hir_id: HirId) -> LocalDefId { 3,144 ( 0.00%) self.opt_local_def_id(hir_id).unwrap_or_else(|| { . bug!( . "local_def_id: no entry for `{:?}`, which has a map of `{:?}`", . hir_id, . self.find(hir_id) . ) . }) 10,773 ( 0.00%) } . . #[inline] 8,384 ( 0.00%) pub fn opt_local_def_id(&self, hir_id: HirId) -> Option { 2,420 ( 0.00%) if hir_id.local_id == ItemLocalId::new(0) { . Some(hir_id.owner) . } else { 1,652 ( 0.00%) self.tcx . .hir_owner_nodes(hir_id.owner)? . .local_id_to_def_id . .get(&hir_id.local_id) . .copied() . } 9,432 ( 0.00%) } . . #[inline] 6 ( 0.00%) pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId { . // FIXME(#85914) is this access safe for incr. comp.? 758 ( 0.00%) self.tcx.untracked_resolutions.definitions.local_def_id_to_hir_id(def_id) 12 ( 0.00%) } . 7 ( 0.00%) pub fn iter_local_def_id(&self) -> impl Iterator + '_ { . // Create a dependency to the crate to be sure we reexcute this when the amount of . // definitions change. 1 ( 0.00%) self.tcx.ensure().hir_crate(()); . self.tcx.untracked_resolutions.definitions.iter_local_def_id() 9 ( 0.00%) } . 1,442 ( 0.00%) pub fn opt_def_kind(&self, local_def_id: LocalDefId) -> Option { . let hir_id = self.local_def_id_to_hir_id(local_def_id); 2,678 ( 0.00%) let def_kind = match self.find(hir_id)? { 316 ( 0.00%) Node::Item(item) => match item.kind { . ItemKind::Static(..) => DefKind::Static, . ItemKind::Const(..) => DefKind::Const, . ItemKind::Fn(..) => DefKind::Fn, . ItemKind::Macro(..) => DefKind::Macro(MacroKind::Bang), . ItemKind::Mod(..) => DefKind::Mod, . ItemKind::OpaqueTy(..) => DefKind::OpaqueTy, . ItemKind::TyAlias(..) => DefKind::TyAlias, . ItemKind::Enum(..) => DefKind::Enum, -- line 239 ---------------------------------------- -- line 252 ---------------------------------------- . ForeignItemKind::Static(..) => DefKind::Static, . ForeignItemKind::Type => DefKind::ForeignTy, . }, . Node::TraitItem(item) => match item.kind { . TraitItemKind::Const(..) => DefKind::AssocConst, . TraitItemKind::Fn(..) => DefKind::AssocFn, . TraitItemKind::Type(..) => DefKind::AssocTy, . }, 28 ( 0.00%) Node::ImplItem(item) => match item.kind { . ImplItemKind::Const(..) => DefKind::AssocConst, . ImplItemKind::Fn(..) => DefKind::AssocFn, . ImplItemKind::TyAlias(..) => DefKind::AssocTy, . }, . Node::Variant(_) => DefKind::Variant, . Node::Ctor(variant_data) => { . // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`? 40 ( 0.00%) assert_ne!(variant_data.ctor_hir_id(), None); . 56 ( 0.00%) let ctor_of = match self.find(self.get_parent_node(hir_id)) { . Some(Node::Item(..)) => def::CtorOf::Struct, . Some(Node::Variant(..)) => def::CtorOf::Variant, . _ => unreachable!(), . }; 16 ( 0.00%) DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data)) 32 ( 0.00%) } . Node::AnonConst(_) => { . let inline = match self.find(self.get_parent_node(hir_id)) { . Some(Node::Expr(&Expr { . kind: ExprKind::ConstBlock(ref anon_const), .. . })) if anon_const.hir_id == hir_id => true, . _ => false, . }; . if inline { DefKind::InlineConst } else { DefKind::AnonConst } . } . Node::Field(_) => DefKind::Field, 55 ( 0.00%) Node::Expr(expr) => match expr.kind { . ExprKind::Closure(.., None) => DefKind::Closure, . ExprKind::Closure(.., Some(_)) => DefKind::Generator, . _ => bug!("def_kind: unsupported node: {}", self.node_to_string(hir_id)), . }, 27 ( 0.00%) Node::GenericParam(param) => match param.kind { . GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam, . GenericParamKind::Type { .. } => DefKind::TyParam, . GenericParamKind::Const { .. } => DefKind::ConstParam, . }, . Node::Crate(_) => DefKind::Mod, . Node::Stmt(_) . | Node::PathSegment(_) . | Node::Ty(_) -- line 300 ---------------------------------------- -- line 304 ---------------------------------------- . | Node::Binding(_) . | Node::Local(_) . | Node::Param(_) . | Node::Arm(_) . | Node::Lifetime(_) . | Node::Visibility(_) . | Node::Block(_) => return None, . }; 720 ( 0.00%) Some(def_kind) 2,060 ( 0.00%) } . . pub fn def_kind(&self, local_def_id: LocalDefId) -> DefKind { . self.opt_def_kind(local_def_id) . .unwrap_or_else(|| bug!("def_kind: unsupported node: {:?}", local_def_id)) . } . 1,459,792 ( 0.03%) pub fn find_parent_node(&self, id: HirId) -> Option { 182,474 ( 0.00%) if id.local_id == ItemLocalId::from_u32(0) { . Some(self.tcx.hir_owner_parent(id.owner)) . } else { 364,166 ( 0.01%) let owner = self.tcx.hir_owner_nodes(id.owner)?; 182,083 ( 0.00%) let node = owner.nodes[id.local_id].as_ref()?; 546,249 ( 0.01%) let hir_id = HirId { owner: id.owner, local_id: node.parent }; . Some(hir_id) . } 1,459,792 ( 0.03%) } . 479 ( 0.00%) pub fn get_parent_node(&self, hir_id: HirId) -> HirId { 1,084,880 ( 0.02%) self.find_parent_node(hir_id).unwrap() 958 ( 0.00%) } . . /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found. 416,632 ( 0.01%) pub fn find(&self, id: HirId) -> Option> { 52,079 ( 0.00%) if id.local_id == ItemLocalId::from_u32(0) { . let owner = self.tcx.hir_owner(id.owner)?; 24,803 ( 0.00%) Some(owner.node.into()) . } else { 54,476 ( 0.00%) let owner = self.tcx.hir_owner_nodes(id.owner)?; 27,238 ( 0.00%) let node = owner.nodes[id.local_id].as_ref()?; 81,714 ( 0.00%) Some(node.node) . } 416,632 ( 0.01%) } . . /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found. . #[inline] . pub fn find_by_def_id(&self, id: LocalDefId) -> Option> { 29,393 ( 0.00%) self.find(self.local_def_id_to_hir_id(id)) . } . . /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found. 5,736 ( 0.00%) pub fn get(&self, id: HirId) -> Node<'hir> { 3,338 ( 0.00%) self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id)) 3,824 ( 0.00%) } . . /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found. . #[inline] . pub fn get_by_def_id(&self, id: LocalDefId) -> Node<'hir> { . self.find_by_def_id(id).unwrap_or_else(|| bug!("couldn't find {:?} in the HIR map", id)) . } . 288 ( 0.00%) pub fn get_if_local(&self, id: DefId) -> Option> { 144 ( 0.00%) id.as_local().and_then(|id| self.find(self.local_def_id_to_hir_id(id))) 288 ( 0.00%) } . . pub fn get_generics(&self, id: LocalDefId) -> Option<&'hir Generics<'hir>> { . let node = self.tcx.hir_owner(id)?; . match node.node { . OwnerNode::ImplItem(impl_item) => Some(&impl_item.generics), . OwnerNode::TraitItem(trait_item) => Some(&trait_item.generics), . OwnerNode::Item(Item { . kind: -- line 374 ---------------------------------------- -- line 381 ---------------------------------------- . | ItemKind::TraitAlias(generics, _) . | ItemKind::Impl(Impl { generics, .. }), . .. . }) => Some(generics), . _ => None, . } . } . 15,085 ( 0.00%) pub fn item(&self, id: ItemId) -> &'hir Item<'hir> { 4,310 ( 0.00%) self.tcx.hir_owner(id.def_id).unwrap().node.expect_item() 17,240 ( 0.00%) } . . pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> { . self.tcx.hir_owner(id.def_id).unwrap().node.expect_trait_item() . } . 5,551 ( 0.00%) pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> { 1,586 ( 0.00%) self.tcx.hir_owner(id.def_id).unwrap().node.expect_impl_item() 6,344 ( 0.00%) } . . pub fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> { . self.tcx.hir_owner(id.def_id).unwrap().node.expect_foreign_item() . } . 15,477 ( 0.00%) pub fn body(&self, id: BodyId) -> &'hir Body<'hir> { 4,422 ( 0.00%) self.tcx.hir_owner_nodes(id.hir_id.owner).unwrap().bodies[&id.hir_id.local_id] 17,688 ( 0.00%) } . 381 ( 0.00%) pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> { 381 ( 0.00%) if let Some(node) = self.find(hir_id) { . fn_decl(node) . } else { . bug!("no node for hir_id `{}`", hir_id) . } 254 ( 0.00%) } . 39 ( 0.00%) pub fn fn_sig_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> { 39 ( 0.00%) if let Some(node) = self.find(hir_id) { . fn_sig(node) . } else { . bug!("no node for hir_id `{}`", hir_id) . } 39 ( 0.00%) } . . pub fn enclosing_body_owner(&self, hir_id: HirId) -> HirId { . for (parent, _) in self.parent_iter(hir_id) { . if let Some(body) = self.maybe_body_owned_by(parent) { . return self.body_owner(body); . } . } . . bug!("no `enclosing_body_owner` for hir_id `{}`", hir_id); . } . . /// Returns the `HirId` that corresponds to the definition of . /// which this is the body of, i.e., a `fn`, `const` or `static` . /// item (possibly associated), a closure, or a `hir::AnonConst`. 10,472 ( 0.00%) pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> HirId { . let parent = self.get_parent_node(hir_id); 7,854 ( 0.00%) assert!(self.find(parent).map_or(false, |n| is_body_owner(n, hir_id))); . parent 10,472 ( 0.00%) } . 3,300 ( 0.00%) pub fn body_owner_def_id(&self, id: BodyId) -> LocalDefId { 5,240 ( 0.00%) self.local_def_id(self.body_owner(id)) 3,300 ( 0.00%) } . . /// Given a `HirId`, returns the `BodyId` associated with it, . /// if the node is a body owner, otherwise returns `None`. 437 ( 0.00%) pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option { 1,443 ( 0.00%) self.find(hir_id).map(associated_body).flatten() 1,311 ( 0.00%) } . . /// Given a body owner's id, returns the `BodyId` associated with it. 1,188 ( 0.00%) pub fn body_owned_by(&self, id: HirId) -> BodyId { . self.maybe_body_owned_by(id).unwrap_or_else(|| { . span_bug!( . self.span(id), . "body_owned_by: {} has no associated body", . self.node_to_string(id) . ); . }) 924 ( 0.00%) } . 42 ( 0.00%) pub fn body_param_names(&self, id: BodyId) -> impl Iterator + 'hir { 378 ( 0.00%) self.body(id).params.iter().map(|arg| match arg.pat.kind { 126 ( 0.00%) PatKind::Binding(_, _, ident, _) => ident, . _ => Ident::empty(), . }) 126 ( 0.00%) } . . /// Returns the `BodyOwnerKind` of this `LocalDefId`. . /// . /// Panics if `LocalDefId` does not have an associated body. 2,343 ( 0.00%) pub fn body_owner_kind(&self, id: HirId) -> BodyOwnerKind { 6,005 ( 0.00%) match self.get(id) { . Node::Item(&Item { kind: ItemKind::Const(..), .. }) . | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. }) . | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. }) . | Node::AnonConst(_) => BodyOwnerKind::Const, . Node::Ctor(..) . | Node::Item(&Item { kind: ItemKind::Fn(..), .. }) . | Node::TraitItem(&TraitItem { kind: TraitItemKind::Fn(..), .. }) . | Node::ImplItem(&ImplItem { kind: ImplItemKind::Fn(..), .. }) => BodyOwnerKind::Fn, 132 ( 0.00%) Node::Item(&Item { kind: ItemKind::Static(_, m, _), .. }) => BodyOwnerKind::Static(m), . Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => BodyOwnerKind::Closure, . node => bug!("{:#?} is not a body node", node), . } 2,343 ( 0.00%) } . . /// Returns the `ConstContext` of the body associated with this `LocalDefId`. . /// . /// Panics if `LocalDefId` does not have an associated body. . /// . /// This should only be used for determining the context of a body, a return . /// value of `Some` does not always suggest that the owner of the body is `const`, . /// just that it has to be checked as if it were. 3,168 ( 0.00%) pub fn body_const_context(&self, did: LocalDefId) -> Option { . let hir_id = self.local_def_id_to_hir_id(did); 4,752 ( 0.00%) let ccx = match self.body_owner_kind(hir_id) { . BodyOwnerKind::Const => ConstContext::Const, 198 ( 0.00%) BodyOwnerKind::Static(mt) => ConstContext::Static(mt), . 252 ( 0.00%) BodyOwnerKind::Fn if self.tcx.is_constructor(did.to_def_id()) => return None, 252 ( 0.00%) BodyOwnerKind::Fn if self.tcx.is_const_fn_raw(did.to_def_id()) => ConstContext::ConstFn, . BodyOwnerKind::Fn 504 ( 0.00%) if self.tcx.has_attr(did.to_def_id(), sym::default_method_body_is_const) => . { . ConstContext::ConstFn . } . BodyOwnerKind::Fn | BodyOwnerKind::Closure => return None, . }; . . Some(ccx) 3,564 ( 0.00%) } . . /// Returns an iterator of the `DefId`s for all body-owners in this . /// crate. If you would prefer to iterate over the bodies . /// themselves, you can do `self.hir().krate().body_ids.iter()`. 21 ( 0.00%) pub fn body_owners(self) -> impl Iterator + 'hir { 3 ( 0.00%) self.krate() . .owners . .iter_enumerated() . .flat_map(move |(owner, owner_info)| { 618 ( 0.00%) let bodies = &owner_info.as_ref()?.nodes.bodies; . Some(bodies.iter().map(move |&(local_id, _)| { 11 ( 0.00%) let hir_id = HirId { owner, local_id }; . let body_id = BodyId { hir_id }; 627 ( 0.00%) self.body_owner_def_id(body_id) . })) . }) . .flatten() 15 ( 0.00%) } . 10 ( 0.00%) pub fn par_body_owners(self, f: F) { . use rustc_data_structures::sync::{par_iter, ParallelIterator}; . #[cfg(parallel_compiler)] . use rustc_rayon::iter::IndexedParallelIterator; . 3 ( 0.00%) par_iter(&self.krate().owners.raw).enumerate().for_each(|(owner, owner_info)| { . let owner = LocalDefId::new(owner); 1,236 ( 0.00%) if let Some(owner_info) = owner_info { . par_iter(owner_info.nodes.bodies.range(..)).for_each(|(local_id, _)| { . let hir_id = HirId { owner, local_id: *local_id }; . let body_id = BodyId { hir_id }; 594 ( 0.00%) f(self.body_owner_def_id(body_id)) . }) . } . }); 8 ( 0.00%) } . . pub fn ty_param_owner(&self, id: HirId) -> LocalDefId { . match self.get(id) { . Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => { . id.expect_owner() . } . Node::GenericParam(_) => self.get_parent_item(id), . _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id)), -- line 558 ---------------------------------------- -- line 564 ---------------------------------------- . Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => { . kw::SelfUpper . } . Node::GenericParam(param) => param.name.ident().name, . _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)), . } . } . 765 ( 0.00%) pub fn trait_impls(&self, trait_did: DefId) -> &'hir [LocalDefId] { 85 ( 0.00%) self.tcx.all_local_trait_impls(()).get(&trait_did).map_or(&[], |xs| &xs[..]) 765 ( 0.00%) } . . /// Gets the attributes on the crate. This is preferable to . /// invoking `krate.attrs` because it registers a tighter . /// dep-graph access. . pub fn krate_attrs(&self) -> &'hir [ast::Attribute] { 74 ( 0.00%) self.attrs(CRATE_HIR_ID) . } . 119 ( 0.00%) pub fn get_module(&self, module: LocalDefId) -> (&'hir Mod<'hir>, Span, HirId) { . let hir_id = HirId::make_owner(module); 85 ( 0.00%) match self.tcx.hir_owner(module).map(|o| o.node) { 12 ( 0.00%) Some(OwnerNode::Item(&Item { span, kind: ItemKind::Mod(ref m), .. })) => { . (m, span, hir_id) . } 33 ( 0.00%) Some(OwnerNode::Crate(item)) => (item, item.inner, hir_id), . node => panic!("not a module: {:?}", node), . } 153 ( 0.00%) } . . /// Walks the contents of a crate. See also `Crate::visit_all_items`. 11 ( 0.00%) pub fn walk_toplevel_module(self, visitor: &mut impl Visitor<'hir>) { 30 ( 0.00%) let (top_mod, span, hir_id) = self.get_module(CRATE_DEF_ID); . visitor.visit_mod(top_mod, span, hir_id); 8 ( 0.00%) } . . /// Walks the attributes in a crate. 20 ( 0.00%) pub fn walk_attributes(self, visitor: &mut impl Visitor<'hir>) { 2 ( 0.00%) let krate = self.krate(); . for (owner, info) in krate.owners.iter_enumerated() { 824 ( 0.00%) if let Some(info) = info { . for (local_id, attrs) in info.attrs.map.iter() { . let id = HirId { owner, local_id: *local_id }; . for a in *attrs { 625 ( 0.00%) visitor.visit_attribute(id, a) . } . } . } . } 16 ( 0.00%) } . . /// Visits all items in the crate in some deterministic (but . /// unspecified) order. If you just need to process every item, . /// but don't care about nesting, this method is the best choice. . /// . /// If you do care about nesting -- usually because your algorithm . /// follows lexical scoping rules -- then you want a different . /// approach. You should override `visit_nested_item` in your . /// visitor and then call `intravisit::walk_crate` instead. 152 ( 0.00%) pub fn visit_all_item_likes(&self, visitor: &mut V) . where . V: itemlikevisit::ItemLikeVisitor<'hir>, . { 22 ( 0.00%) let krate = self.krate(); 82 ( 0.00%) for owner in krate.owners.iter().filter_map(Option::as_ref) { 3,564 ( 0.00%) match owner.node() { 4,029 ( 0.00%) OwnerNode::Item(item) => visitor.visit_item(item), . OwnerNode::ForeignItem(item) => visitor.visit_foreign_item(item), 84 ( 0.00%) OwnerNode::ImplItem(item) => visitor.visit_impl_item(item), . OwnerNode::TraitItem(item) => visitor.visit_trait_item(item), . OwnerNode::Crate(_) => {} . } . } 152 ( 0.00%) } . . /// A parallel version of `visit_all_item_likes`. . pub fn par_visit_all_item_likes(&self, visitor: &V) . where . V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send, . { 1 ( 0.00%) let krate = self.krate(); 2 ( 0.00%) par_for_each_in(&krate.owners.raw, |owner| match owner.as_ref().map(OwnerInfo::node) { 79 ( 0.00%) Some(OwnerNode::Item(item)) => visitor.visit_item(item), . Some(OwnerNode::ForeignItem(item)) => visitor.visit_foreign_item(item), 28 ( 0.00%) Some(OwnerNode::ImplItem(item)) => visitor.visit_impl_item(item), . Some(OwnerNode::TraitItem(item)) => visitor.visit_trait_item(item), . Some(OwnerNode::Crate(_)) | None => {} . }) . } . 258 ( 0.00%) pub fn visit_item_likes_in_module(&self, module: LocalDefId, visitor: &mut V) . where . V: ItemLikeVisitor<'hir>, . { 33 ( 0.00%) let module = self.tcx.hir_module_items(module); . 36 ( 0.00%) for id in module.items.iter() { 3,555 ( 0.00%) visitor.visit_item(self.item(*id)); . } . 36 ( 0.00%) for id in module.trait_items.iter() { . visitor.visit_trait_item(self.trait_item(*id)); . } . 36 ( 0.00%) for id in module.impl_items.iter() { 1,092 ( 0.00%) visitor.visit_impl_item(self.impl_item(*id)); . } . 36 ( 0.00%) for id in module.foreign_items.iter() { . visitor.visit_foreign_item(self.foreign_item(*id)); . } 264 ( 0.00%) } . 46 ( 0.00%) pub fn for_each_module(&self, f: impl Fn(LocalDefId)) { . let mut queue = VecDeque::new(); . queue.push_back(CRATE_DEF_ID); . 24 ( 0.00%) while let Some(id) = queue.pop_front() { . f(id); 9 ( 0.00%) let items = self.tcx.hir_module_items(id); 96 ( 0.00%) queue.extend(items.submodules.iter().copied()) . } 40 ( 0.00%) } . . #[cfg(not(parallel_compiler))] . #[inline] . pub fn par_for_each_module(&self, f: impl Fn(LocalDefId)) { 4 ( 0.00%) self.for_each_module(f) . } . . #[cfg(parallel_compiler)] . pub fn par_for_each_module(&self, f: impl Fn(LocalDefId) + Sync) { . use rustc_data_structures::sync::{par_iter, ParallelIterator}; . par_iter_submodules(self.tcx, CRATE_DEF_ID, &f); . . fn par_iter_submodules(tcx: TyCtxt<'_>, module: LocalDefId, f: &F) -- line 699 ---------------------------------------- -- line 703 ---------------------------------------- . (*f)(module); . let items = tcx.hir_module_items(module); . par_iter(&items.submodules[..]).for_each(|&sm| par_iter_submodules(tcx, sm, f)); . } . } . . /// Returns an iterator for the nodes in the ancestor tree of the `current_id` . /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`. 67 ( 0.00%) pub fn parent_iter(self, current_id: HirId) -> ParentHirIterator<'hir> { . ParentHirIterator { current_id, map: self } 284 ( 0.00%) } . . /// Returns an iterator for the nodes in the ancestor tree of the `current_id` . /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`. . pub fn parent_owner_iter(self, current_id: HirId) -> ParentOwnerIterator<'hir> { . ParentOwnerIterator { current_id, map: self } 2,142 ( 0.00%) } . . /// Checks if the node is left-hand side of an assignment. . pub fn is_lhs(&self, id: HirId) -> bool { . match self.find(self.get_parent_node(id)) { . Some(Node::Expr(expr)) => match expr.kind { . ExprKind::Assign(lhs, _rhs, _span) => lhs.hir_id == id, . _ => false, . }, -- line 727 ---------------------------------------- -- line 752 ---------------------------------------- . /// ``` . /// fn foo(x: usize) -> bool { . /// loop { . /// true // If `get_return_block` gets passed the `id` corresponding . /// } // to this, it will return `None`. . /// false . /// } . /// ``` 36 ( 0.00%) pub fn get_return_block(&self, id: HirId) -> Option { 4 ( 0.00%) let mut iter = self.parent_iter(id).peekable(); . let mut ignore_tail = false; 16 ( 0.00%) if let Some(node) = self.find(id) { 16 ( 0.00%) if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = node { . // When dealing with `return` statements, we don't care about climbing only tail . // expressions. . ignore_tail = true; . } . } 48 ( 0.00%) while let Some((hir_id, node)) = iter.next() { 196 ( 0.00%) if let (Some((_, next_node)), false) = (iter.peek(), ignore_tail) { 3 ( 0.00%) match next_node { . Node::Block(Block { expr: None, .. }) => return None, . // The current node is not the tail expression of its parent. 3 ( 0.00%) Node::Block(Block { expr: Some(e), .. }) if hir_id != e.hir_id => return None, . _ => {} . } . } 210 ( 0.00%) match node { . Node::Item(_) . | Node::ForeignItem(_) . | Node::TraitItem(_) . | Node::Expr(Expr { kind: ExprKind::Closure(..), .. }) . | Node::ImplItem(_) => return Some(hir_id), . // Ignore `return`s on the first iteration . Node::Expr(Expr { kind: ExprKind::Loop(..) | ExprKind::Ret(..), .. }) . | Node::Local(_) => { . return None; . } . _ => {} . } . } . None 40 ( 0.00%) } . . /// Retrieves the `HirId` for `id`'s parent item, or `id` itself if no . /// parent item is in this map. The "parent item" is the closest parent node . /// in the HIR which is recorded by the map and is an item, either an item . /// in a module, trait, or impl. 637 ( 0.00%) pub fn get_parent_item(&self, hir_id: HirId) -> LocalDefId { 5,773 ( 0.00%) if let Some((def_id, _node)) = self.parent_owner_iter(hir_id).next() { . def_id . } else { . CRATE_DEF_ID . } 1,274 ( 0.00%) } . . /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no . /// module parent is in this map. . pub(super) fn get_module_parent_node(&self, hir_id: HirId) -> LocalDefId { 582 ( 0.00%) for (def_id, node) in self.parent_owner_iter(hir_id) { 298 ( 0.00%) if let OwnerNode::Item(&Item { kind: ItemKind::Mod(_), .. }) = node { . return def_id; . } . } . CRATE_DEF_ID . } . . /// When on an if expression, a match arm tail expression or a match arm, give back . /// the enclosing `if` or `match` expression. -- line 820 ---------------------------------------- -- line 885 ---------------------------------------- . } . } . bug!( . "expected foreign mod or inlined parent, found {}", . self.node_to_string(HirId::make_owner(parent)) . ) . } . 2,331 ( 0.00%) pub fn expect_item(&self, id: LocalDefId) -> &'hir Item<'hir> { 999 ( 0.00%) match self.tcx.hir_owner(id) { . Some(Owner { node: OwnerNode::Item(item), .. }) => item, . _ => bug!("expected item, found {}", self.node_to_string(HirId::make_owner(id))), . } 2,664 ( 0.00%) } . 392 ( 0.00%) pub fn expect_impl_item(&self, id: LocalDefId) -> &'hir ImplItem<'hir> { 168 ( 0.00%) match self.tcx.hir_owner(id) { . Some(Owner { node: OwnerNode::ImplItem(item), .. }) => item, . _ => bug!("expected impl item, found {}", self.node_to_string(HirId::make_owner(id))), . } 448 ( 0.00%) } . . pub fn expect_trait_item(&self, id: LocalDefId) -> &'hir TraitItem<'hir> { . match self.tcx.hir_owner(id) { . Some(Owner { node: OwnerNode::TraitItem(item), .. }) => item, . _ => bug!("expected trait item, found {}", self.node_to_string(HirId::make_owner(id))), . } . } . -- line 913 ---------------------------------------- -- line 929 ---------------------------------------- . . pub fn expect_expr(&self, id: HirId) -> &'hir Expr<'hir> { . match self.find(id) { . Some(Node::Expr(expr)) => expr, . _ => bug!("expected expr, found {}", self.node_to_string(id)), . } . } . 432 ( 0.00%) pub fn opt_name(&self, id: HirId) -> Option { 164 ( 0.00%) Some(match self.get(id) { . Node::Item(i) => i.ident.name, . Node::ForeignItem(fi) => fi.ident.name, . Node::ImplItem(ii) => ii.ident.name, . Node::TraitItem(ti) => ti.ident.name, . Node::Variant(v) => v.ident.name, . Node::Field(f) => f.ident.name, . Node::Lifetime(lt) => lt.name.ident().name, 114 ( 0.00%) Node::GenericParam(param) => param.name.ident().name, 20 ( 0.00%) Node::Binding(&Pat { kind: PatKind::Binding(_, _, l, _), .. }) => l.name, . Node::Ctor(..) => self.name(HirId::make_owner(self.get_parent_item(id))), . _ => return None, . }) 240 ( 0.00%) } . 344 ( 0.00%) pub fn name(&self, id: HirId) -> Symbol { 154 ( 0.00%) match self.opt_name(id) { . Some(name) => name, . None => bug!("no name for {}", self.node_to_string(id)), . } 258 ( 0.00%) } . . /// Given a node ID, gets a list of attributes associated with the AST . /// corresponding to the node-ID. 2,689,267 ( 0.05%) pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] { 384,181 ( 0.01%) self.tcx.hir_attrs(id.owner).get(id.local_id) 3,073,448 ( 0.06%) } . . /// Gets the span of the definition of the specified HIR node. . /// This is used by `tcx.get_span` 732 ( 0.00%) pub fn span(&self, hir_id: HirId) -> Span { 68,648 ( 0.00%) self.opt_span(hir_id) . .unwrap_or_else(|| bug!("hir::map::Map::span: id not in map: {:?}", hir_id)) 732 ( 0.00%) } . 122,752 ( 0.00%) pub fn opt_span(&self, hir_id: HirId) -> Option { 122,752 ( 0.00%) let span = match self.find(hir_id)? { . Node::Param(param) => param.span, 334 ( 0.00%) Node::Item(item) => match &item.kind { . ItemKind::Fn(sig, _, _) => sig.span, 206 ( 0.00%) _ => item.span, . }, . Node::ForeignItem(foreign_item) => foreign_item.span, . Node::TraitItem(trait_item) => match &trait_item.kind { . TraitItemKind::Fn(sig, _) => sig.span, . _ => trait_item.span, . }, 212 ( 0.00%) Node::ImplItem(impl_item) => match &impl_item.kind { 208 ( 0.00%) ImplItemKind::Fn(sig, _) => sig.span, 4 ( 0.00%) _ => impl_item.span, . }, 16 ( 0.00%) Node::Variant(variant) => variant.span, 72 ( 0.00%) Node::Field(field) => field.span, . Node::AnonConst(constant) => self.body(constant.body).value.span, . Node::Expr(expr) => expr.span, . Node::Stmt(stmt) => stmt.span, . Node::PathSegment(seg) => seg.ident.span, . Node::Ty(ty) => ty.span, . Node::TraitRef(tr) => tr.path.span, . Node::Binding(pat) => pat.span, . Node::Pat(pat) => pat.span, . Node::Arm(arm) => arm.span, . Node::Block(block) => block.span, 98 ( 0.00%) Node::Ctor(..) => match self.find(self.get_parent_node(hir_id))? { . Node::Item(item) => item.span, . Node::Variant(variant) => variant.span, . _ => unreachable!(), . }, . Node::Lifetime(lifetime) => lifetime.span, . Node::GenericParam(param) => param.span, . Node::Visibility(&Spanned { . node: VisibilityKind::Restricted { ref path, .. }, . .. . }) => path.span, . Node::Infer(i) => i.span, . Node::Visibility(v) => bug!("unexpected Visibility {:?}", v), . Node::Local(local) => local.span, 4 ( 0.00%) Node::Crate(item) => item.inner, . }; . Some(span) 175,360 ( 0.00%) } . . /// Like `hir.span()`, but includes the body of function items . /// (instead of just the function header) . pub fn span_with_body(&self, hir_id: HirId) -> Span { . match self.find(hir_id) { . Some(Node::TraitItem(item)) => item.span, . Some(Node::ImplItem(impl_item)) => impl_item.span, . Some(Node::Item(item)) => item.span, . Some(_) => self.span(hir_id), . _ => bug!("hir::map::Map::span_with_body: id not in map: {:?}", hir_id), . } . } . 44 ( 0.00%) pub fn span_if_local(&self, id: DefId) -> Option { 366 ( 0.00%) id.as_local().and_then(|id| self.opt_span(self.local_def_id_to_hir_id(id))) 66 ( 0.00%) } . . pub fn res_span(&self, res: Res) -> Option { . match res { . Res::Err => None, . Res::Local(id) => Some(self.span(id)), . res => self.span_if_local(res.opt_def_id()?), . } . } -- line 1042 ---------------------------------------- -- line 1062 ---------------------------------------- . } . . impl<'hir> intravisit::Map<'hir> for Map<'hir> { . fn find(&self, hir_id: HirId) -> Option> { . self.find(hir_id) . } . . fn body(&self, id: BodyId) -> &'hir Body<'hir> { 1,274 ( 0.00%) self.body(id) . } . . fn item(&self, id: ItemId) -> &'hir Item<'hir> { 1,025 ( 0.00%) self.item(id) . } . . fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> { . self.trait_item(id) . } . . fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> { 392 ( 0.00%) self.impl_item(id) . } . . fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> { . self.foreign_item(id) . } . } . 7 ( 0.00%) pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh { . debug_assert_eq!(crate_num, LOCAL_CRATE); . let krate = tcx.hir_crate(()); 3 ( 0.00%) let hir_body_hash = krate.hir_hash; . . let upstream_crates = upstream_crates(tcx); . . // We hash the final, remapped names of all local source files so we . // don't have to include the path prefix remapping commandline args. . // If we included the full mapping in the SVH, we could only have . // reproducible builds by compiling from the same directory. So we just . // hash the result of the mapping instead of the mapping itself. 2 ( 0.00%) let mut source_file_names: Vec<_> = tcx . .sess . .source_map() . .files() . .iter() . .filter(|source_file| source_file.cnum == LOCAL_CRATE) 11 ( 0.00%) .map(|source_file| source_file.name_hash) . .collect(); . . source_file_names.sort_unstable(); . . let mut hcx = tcx.create_stable_hashing_context(); . let mut stable_hasher = StableHasher::new(); . hir_body_hash.hash_stable(&mut hcx, &mut stable_hasher); . upstream_crates.hash_stable(&mut hcx, &mut stable_hasher); . source_file_names.hash_stable(&mut hcx, &mut stable_hasher); 3 ( 0.00%) if tcx.sess.opts.debugging_opts.incremental_relative_spans { . let definitions = &tcx.untracked_resolutions.definitions; . let mut owner_spans: Vec<_> = krate . .owners . .iter_enumerated() . .filter_map(|(def_id, info)| { . let _ = info.as_ref()?; . let def_path_hash = definitions.def_path_hash(def_id); . let span = definitions.def_span(def_id); . debug_assert_eq!(span.parent(), None); . Some((def_path_hash, span)) . }) . .collect(); . owner_spans.sort_unstable_by_key(|bn| bn.0); . owner_spans.hash_stable(&mut hcx, &mut stable_hasher); . } 3 ( 0.00%) tcx.sess.opts.dep_tracking_hash(true).hash_stable(&mut hcx, &mut stable_hasher); 2 ( 0.00%) tcx.sess.local_stable_crate_id().hash_stable(&mut hcx, &mut stable_hasher); . . let crate_hash: Fingerprint = stable_hasher.finish(); 1 ( 0.00%) Svh::new(crate_hash.to_smaller_hash()) 9 ( 0.00%) } . . fn upstream_crates(tcx: TyCtxt<'_>) -> Vec<(StableCrateId, Svh)> { . let mut upstream_crates: Vec<_> = tcx . .crates(()) . .iter() . .map(|&cnum| { 120 ( 0.00%) let stable_crate_id = tcx.resolutions(()).cstore.stable_crate_id(cnum); 24 ( 0.00%) let hash = tcx.crate_hash(cnum); . (stable_crate_id, hash) . }) . .collect(); . upstream_crates.sort_unstable_by_key(|&(stable_crate_id, _)| stable_crate_id); . upstream_crates . } . . fn hir_id_to_string(map: &Map<'_>, id: HirId) -> String { -- line 1155 ---------------------------------------- -- line 1238 ---------------------------------------- . Some(Node::Lifetime(_)) => node_str("lifetime"), . Some(Node::GenericParam(ref param)) => format!("generic_param {:?}{}", param, id_str), . Some(Node::Visibility(ref vis)) => format!("visibility {:?}{}", vis, id_str), . Some(Node::Crate(..)) => String::from("root_crate"), . None => format!("unknown node{}", id_str), . } . } . 27 ( 0.00%) pub(super) fn hir_module_items(tcx: TyCtxt<'_>, module_id: LocalDefId) -> ModuleItems { 18 ( 0.00%) let mut collector = ModuleCollector { . tcx, . submodules: Vec::default(), . items: Vec::default(), . trait_items: Vec::default(), . impl_items: Vec::default(), . foreign_items: Vec::default(), . }; . 15 ( 0.00%) let (hir_mod, span, hir_id) = tcx.hir().get_module(module_id); . collector.visit_mod(hir_mod, span, hir_id); . 48 ( 0.00%) let ModuleCollector { submodules, items, trait_items, impl_items, foreign_items, .. } = . collector; 33 ( 0.00%) return ModuleItems { 12 ( 0.00%) submodules: submodules.into_boxed_slice(), 12 ( 0.00%) items: items.into_boxed_slice(), 12 ( 0.00%) trait_items: trait_items.into_boxed_slice(), 12 ( 0.00%) impl_items: impl_items.into_boxed_slice(), 12 ( 0.00%) foreign_items: foreign_items.into_boxed_slice(), . }; . . struct ModuleCollector<'tcx> { . tcx: TyCtxt<'tcx>, . submodules: Vec, . items: Vec, . trait_items: Vec, . impl_items: Vec, . foreign_items: Vec, . } . . impl<'hir> Visitor<'hir> for ModuleCollector<'hir> { . type NestedFilter = nested_filter::All; . . fn nested_visit_map(&mut self) -> Self::Map { 170 ( 0.00%) self.tcx.hir() . } . 395 ( 0.00%) fn visit_item(&mut self, item: &'hir Item<'hir>) { 237 ( 0.00%) self.items.push(item.item_id()); 158 ( 0.00%) if let ItemKind::Mod(..) = item.kind { . // If this declares another module, do not recurse inside it. 2 ( 0.00%) self.submodules.push(item.def_id); . } else { 462 ( 0.00%) intravisit::walk_item(self, item) . } 8 ( 0.00%) } . . fn visit_trait_item(&mut self, item: &'hir TraitItem<'hir>) { . self.trait_items.push(item.trait_item_id()); . intravisit::walk_trait_item(self, item) . } . . fn visit_impl_item(&mut self, item: &'hir ImplItem<'hir>) { 84 ( 0.00%) self.impl_items.push(item.impl_item_id()); 84 ( 0.00%) intravisit::walk_impl_item(self, item) . } . . fn visit_foreign_item(&mut self, item: &'hir ForeignItem<'hir>) { . self.foreign_items.push(item.foreign_item_id()); . intravisit::walk_foreign_item(self, item) . } . } 24 ( 0.00%) } 511,279 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs -------------------------------------------------------------------------------- Ir -- line 57 ---------------------------------------- . /// # Examples . /// . /// Basic usage: . /// . /// ``` . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 38,896 ( 0.00%) pub fn from_str_radix(src: &str, radix: u32) -> Result { 19,448 ( 0.00%) from_str_radix(src, radix) 58,344 ( 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 { 76,410 ( 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 { 424,163 ( 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,179,440 ( 0.02%) 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 { 16,061,356 ( 0.33%) intrinsics::rotate_left(self, n as $SelfT) . } . . /// Shifts the bits to the right by a specified amount, `n`, . /// wrapping the truncated bits to the beginning of the resulting . /// integer. . /// . /// Please note this isn't the same operation as the `>>` shifting operator! . /// -- line 220 ---------------------------------------- -- line 430 ---------------------------------------- . #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] . pub const fn checked_add(self, rhs: Self) -> Option { 4 ( 0.00%) let (a, b) = self.overflowing_add(rhs); . if unlikely!(b) {None} else {Some(a)} . } . . /// Unchecked integer addition. Computes `self + rhs`, assuming overflow . /// cannot occur. . /// . /// # Safety . /// -- line 446 ---------------------------------------- -- line 456 ---------------------------------------- . )] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] . #[inline(always)] . pub const unsafe fn unchecked_add(self, rhs: Self) -> Self { . // SAFETY: the caller must uphold the safety contract for . // `unchecked_add`. 1,468,100 ( 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`. 94,590 ( 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 2,248 ( 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 { 287,815 ( 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 { 704,653 ( 0.01%) intrinsics::saturating_sub(self, rhs) . } . . /// Saturating integer multiplication. Computes `self * rhs`, . /// saturating at the numeric bounds instead of overflowing. . /// . /// # Examples . /// . /// Basic usage: -- line 1100 ---------------------------------------- -- line 1175 ---------------------------------------- . #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_add(self, rhs: Self) -> Self { 9,725,678 ( 0.20%) 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 { 2,240,875 ( 0.05%) 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 { 11,130,363 ( 0.23%) intrinsics::wrapping_mul(self, rhs) . } . . /// Wrapping (modular) division. Computes `self / rhs`. . /// Wrapped division on unsigned types is just normal division. . /// There's no way wrapping could ever happen. . /// This function exists, so that all operations . /// are accounted for in the wrapping operations. . /// -- line 1256 ---------------------------------------- -- line 1397 ---------------------------------------- . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_shl(self, rhs: u32) -> Self { . // SAFETY: the masking by the bitsize of the type ensures that we do not shift . // out of bounds . unsafe { 9 ( 0.00%) intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT) . } . } . . /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, . /// where `mask` removes any high-order bits of `rhs` that . /// would cause the shift to exceed the bitwidth of the type. . /// . /// Note that this is *not* the same as a rotate-right; the -- line 1413 ---------------------------------------- -- line 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)] 14 ( 0.00%) pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) { 3,599,545 ( 0.07%) let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) 28 ( 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)] 8 ( 0.00%) pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) { 216,825 ( 0.00%) let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) 16 ( 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)] 8 ( 0.00%) pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) { 2,097,613 ( 0.04%) let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) 4 ( 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 1701 ---------------------------------------- . /// ``` . #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")] . /// ``` . #[inline(always)] . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] 2 ( 0.00%) pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) { 8 ( 0.00%) (self / rhs, false) 6 ( 0.00%) } . . /// Calculates the quotient of Euclidean division `self.div_euclid(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`. . /// Since, for the positive integers, all common -- line 1719 ---------------------------------------- -- line 1838 ---------------------------------------- . #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) { 3 ( 0.00%) (self.wrapping_shl(rhs), (rhs > ($BITS - 1))) . } . . /// Shifts self right by `rhs` bits. . /// . /// Returns a tuple of the shifted version of self along with a boolean . /// indicating whether the shift value was larger than or equal to the . /// number of bits. If the shift value is too large, then value is . /// masked (N-1) where N is the number of bits, and this value is then -- line 1854 ---------------------------------------- -- line 2132 ---------------------------------------- . #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")] . #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")] . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")] . #[inline(always)] . pub const fn is_power_of_two(self) -> bool { 174 ( 0.00%) self.count_ones() == 1 . } . . // Returns one less than next power of two. . // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8) . // . // 8u8.one_less_than_next_power_of_two() == 7 . // 6u8.one_less_than_next_power_of_two() == 7 . // . // This method cannot overflow, as in the `next_power_of_two` . // overflow cases it instead ends up returning the maximum value . // of the type, and can return 0 for 0. . #[inline] . #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")] . const fn one_less_than_next_power_of_two(self) -> Self { 8,260 ( 0.00%) if self <= 1 { return 0; } . 9,440 ( 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. 28,081 ( 0.00%) let z = unsafe { intrinsics::ctlz_nonzero(p) }; 9,575 ( 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 { 10,570 ( 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 ---------------------------------------- 105,079 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/layout.rs -------------------------------------------------------------------------------- Ir -- line 23 ---------------------------------------- . use std::iter; . use std::num::NonZeroUsize; . use std::ops::Bound; . . use rand::{seq::SliceRandom, SeedableRng}; . use rand_xoshiro::Xoshiro128StarStar; . . pub fn provide(providers: &mut ty::query::Providers) { 6 ( 0.00%) *providers = . ty::query::Providers { layout_of, fn_abi_of_fn_ptr, fn_abi_of_instance, ..*providers }; . } . . pub trait IntegerExt { . fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>, signed: bool) -> Ty<'tcx>; . fn from_attr(cx: &C, ity: attr::IntType) -> Integer; . fn from_int_ty(cx: &C, ity: ty::IntTy) -> Integer; . fn from_uint_ty(cx: &C, uty: ty::UintTy) -> Integer; -- line 39 ---------------------------------------- -- line 44 ---------------------------------------- . min: i128, . max: i128, . ) -> (Integer, bool); . } . . impl IntegerExt for Integer { . #[inline] . fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>, signed: bool) -> Ty<'tcx> { 405,419 ( 0.01%) match (*self, signed) { . (I8, false) => tcx.types.u8, . (I16, false) => tcx.types.u16, . (I32, false) => tcx.types.u32, . (I64, false) => tcx.types.u64, . (I128, false) => tcx.types.u128, . (I8, true) => tcx.types.i8, . (I16, true) => tcx.types.i16, . (I32, true) => tcx.types.i32, . (I64, true) => tcx.types.i64, . (I128, true) => tcx.types.i128, . } . } . . /// Gets the Integer type from an attr::IntType. 364 ( 0.00%) fn from_attr(cx: &C, ity: attr::IntType) -> Integer { . let dl = cx.data_layout(); . 910 ( 0.00%) match ity { . attr::SignedInt(ast::IntTy::I8) | attr::UnsignedInt(ast::UintTy::U8) => I8, . attr::SignedInt(ast::IntTy::I16) | attr::UnsignedInt(ast::UintTy::U16) => I16, . attr::SignedInt(ast::IntTy::I32) | attr::UnsignedInt(ast::UintTy::U32) => I32, . attr::SignedInt(ast::IntTy::I64) | attr::UnsignedInt(ast::UintTy::U64) => I64, . attr::SignedInt(ast::IntTy::I128) | attr::UnsignedInt(ast::UintTy::U128) => I128, . attr::SignedInt(ast::IntTy::Isize) | attr::UnsignedInt(ast::UintTy::Usize) => { 174 ( 0.00%) dl.ptr_sized_integer() . } . } 364 ( 0.00%) } . . fn from_int_ty(cx: &C, ity: ty::IntTy) -> Integer { . match ity { . ty::IntTy::I8 => I8, . ty::IntTy::I16 => I16, . ty::IntTy::I32 => I32, . ty::IntTy::I64 => I64, . ty::IntTy::I128 => I128, 1,785 ( 0.00%) ty::IntTy::Isize => cx.data_layout().ptr_sized_integer(), . } . } . fn from_uint_ty(cx: &C, ity: ty::UintTy) -> Integer { 360 ( 0.00%) match ity { . ty::UintTy::U8 => I8, . ty::UintTy::U16 => I16, . ty::UintTy::U32 => I32, . ty::UintTy::U64 => I64, . ty::UintTy::U128 => I128, 3 ( 0.00%) ty::UintTy::Usize => cx.data_layout().ptr_sized_integer(), . } . } . . /// Finds the appropriate Integer type and signedness for the given . /// signed discriminant range and `#[repr]` attribute. . /// N.B.: `u128` values above `i128::MAX` will be treated as signed, but . /// that shouldn't affect anything, other than maybe debuginfo. 273 ( 0.00%) fn repr_discr<'tcx>( . tcx: TyCtxt<'tcx>, . ty: Ty<'tcx>, . repr: &ReprOptions, . min: i128, . max: i128, . ) -> (Integer, bool) { . // Theoretically, negative values could be larger in unsigned representation . // than the unsigned representation of the signed minimum. However, if there . // are any negative values, the only valid unsigned representation is u128 . // which can fit all i128 values, so the result remains unaffected. . let unsigned_fit = Integer::fit_unsigned(cmp::max(min as u128, max as u128)); . let signed_fit = cmp::max(Integer::fit_signed(min), Integer::fit_signed(max)); . 309 ( 0.00%) if let Some(ity) = repr.int { . let discr = Integer::from_attr(&tcx, ity); 12 ( 0.00%) let fit = if ity.is_signed() { signed_fit } else { unsigned_fit }; 4 ( 0.00%) if discr < fit { . bug!( . "Integer::repr_discr: `#[repr]` hint too small for \ . discriminant range of enum `{}", . ty . ) . } . return (discr, ity.is_signed()); . } . 174 ( 0.00%) let at_least = if repr.c() { . // This is usually I32, however it can be different on some platforms, . // notably hexagon and arm-none/thumb-none . tcx.data_layout().c_enum_min_size . } else { . // repr(Rust) enums try to be as small as possible . I8 . }; . . // If there are no negative values, we can use the unsigned fit. 783 ( 0.00%) if min >= 0 { . (cmp::max(unsigned_fit, at_least), false) . } else { . (cmp::max(signed_fit, at_least), true) . } 538 ( 0.00%) } . } . . pub trait PrimitiveExt { . fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx>; . fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx>; . } . . impl PrimitiveExt for Primitive { . #[inline] . fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 342,372 ( 0.01%) match *self { 2,096 ( 0.00%) Int(i, signed) => i.to_ty(tcx, signed), . F32 => tcx.types.f32, . F64 => tcx.types.f64, . Pointer => tcx.mk_mut_ptr(tcx.mk_unit()), . } . } . . /// Return an *integer* type matching this primitive. . /// Useful in particular when dealing with enum discriminants. . #[inline] . fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 193,591 ( 0.00%) match *self { 96,744 ( 0.00%) Int(i, signed) => i.to_ty(tcx, signed), . Pointer => tcx.types.usize, . F32 | F64 => bug!("floats do not have an int type"), . } . } . } . . /// The first half of a fat pointer. . /// -- line 181 ---------------------------------------- -- line 191 ---------------------------------------- . . /// The maximum supported number of lanes in a SIMD vector. . /// . /// This value is selected based on backend support: . /// * LLVM does not appear to have a vector width limit. . /// * Cranelift stores the base-2 log of the lane count in a 4 bit integer. . pub const MAX_SIMD_LANES: u64 = 1 << 0xF; . 90 ( 0.00%) #[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)] . pub enum LayoutError<'tcx> { . Unknown(Ty<'tcx>), . SizeOverflow(Ty<'tcx>), . NormalizationFailure(Ty<'tcx>, NormalizationError<'tcx>), . } . . impl<'tcx> fmt::Display for LayoutError<'tcx> { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { -- line 207 ---------------------------------------- -- line 215 ---------------------------------------- . "unable to determine layout for `{}` because `{}` cannot be normalized", . t, . e.get_type_for_failure() . ), . } . } . } . 31,264 ( 0.00%) #[instrument(skip(tcx, query), level = "debug")] . fn layout_of<'tcx>( . tcx: TyCtxt<'tcx>, . query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>, . ) -> Result, LayoutError<'tcx>> { . ty::tls::with_related_context(tcx, move |icx| { 1,954 ( 0.00%) let (param_env, ty) = query.into_parts(); . debug!(?ty); . 7,816 ( 0.00%) if !tcx.recursion_limit().value_within_limit(icx.layout_depth) { . tcx.sess.fatal(&format!("overflow representing the type `{}`", ty)); . } . . // Update the ImplicitCtxt to increase the layout_depth 17,586 ( 0.00%) let icx = ty::tls::ImplicitCtxt { layout_depth: icx.layout_depth + 1, ..icx.clone() }; . . ty::tls::enter_context(&icx, |_| { 5,862 ( 0.00%) let param_env = param_env.with_reveal_all_normalized(tcx); . let unnormalized_ty = ty; . . // FIXME: We might want to have two different versions of `layout_of`: . // One that can be called after typecheck has completed and can use . // `normalize_erasing_regions` here and another one that can be called . // before typecheck has completed and uses `try_normalize_erasing_regions`. . let ty = match tcx.try_normalize_erasing_regions(param_env, ty) { . Ok(t) => t, . Err(normalization_error) => { . return Err(LayoutError::NormalizationFailure(ty, normalization_error)); . } . }; . 1,954 ( 0.00%) if ty != unnormalized_ty { . // Ensure this layout is also cached for the normalized type. . return tcx.layout_of(param_env.and(ty)); . } . 7,700 ( 0.00%) let cx = LayoutCx { tcx, param_env }; . 5,775 ( 0.00%) let layout = cx.layout_of_uncached(ty)?; . let layout = TyAndLayout { ty, layout }; . . cx.record_layout_for_printing(layout); . . // Type-level uninhabitedness should always imply ABI uninhabitedness. 1,922 ( 0.00%) if tcx.conservative_is_privately_uninhabited(param_env.and(ty)) { 3 ( 0.00%) assert!(layout.abi.is_uninhabited()); . } . 5,766 ( 0.00%) Ok(layout) . }) . }) . } . . pub struct LayoutCx<'tcx, C> { . pub tcx: C, . pub param_env: ty::ParamEnv<'tcx>, . } -- line 279 ---------------------------------------- -- line 291 ---------------------------------------- . // Invert a bijective mapping, i.e. `invert(map)[y] = x` if `map[x] = y`. . // This is used to go between `memory_index` (source field order to memory order) . // and `inverse_memory_index` (memory order to source field order). . // See also `FieldsShape::Arbitrary::memory_index` for more details. . // FIXME(eddyb) build a better abstraction for permutations, if possible. . fn invert_mapping(map: &[u32]) -> Vec { . let mut inverse = vec![0; map.len()]; . for i in 0..map.len() { 2,624 ( 0.00%) inverse[map[i] as usize] = i as u32; . } . inverse . } . . impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> { 1,359 ( 0.00%) fn scalar_pair(&self, a: Scalar, b: Scalar) -> Layout { . let dl = self.data_layout(); 1,057 ( 0.00%) let b_align = b.value.align(dl); 1,208 ( 0.00%) let align = a.value.align(dl).max(b_align).max(dl.aggregate_align); . let b_offset = a.value.size(dl).align_to(b_align.abi); . let size = (b_offset + b.value.size(dl)).align_to(align.abi); . . // HACK(nox): We iter on `b` and then `a` because `max_by_key` . // returns the last maximum. 1,812 ( 0.00%) let largest_niche = Niche::from_scalar(dl, b_offset, b) . .into_iter() 1,510 ( 0.00%) .chain(Niche::from_scalar(dl, Size::ZERO, a)) . .max_by_key(|niche| niche.available(dl)); . 2,869 ( 0.00%) Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, . fields: FieldsShape::Arbitrary { 302 ( 0.00%) offsets: vec![Size::ZERO, b_offset], 302 ( 0.00%) memory_index: vec![0, 1], . }, 1,963 ( 0.00%) abi: Abi::ScalarPair(a, b), 1,510 ( 0.00%) largest_niche, . align, . size, . } 1,208 ( 0.00%) } . 20,664 ( 0.00%) fn univariant_uninterned( . &self, . ty: Ty<'tcx>, . fields: &[TyAndLayout<'_>], . repr: &ReprOptions, . kind: StructKind, . ) -> Result> { . let dl = self.data_layout(); 6,888 ( 0.00%) let pack = repr.pack; 1,722 ( 0.00%) if pack.is_some() && repr.align.is_some() { . self.tcx.sess.delay_span_bug(DUMMY_SP, "struct cannot be packed and aligned"); . return Err(LayoutError::Unknown(ty)); . } . 6,888 ( 0.00%) let mut align = if pack.is_some() { dl.i8_align } else { dl.aggregate_align }; . . let mut inverse_memory_index: Vec = (0..fields.len() as u32).collect(); . . let optimize = !repr.inhibit_struct_field_reordering_opt(); 1,698 ( 0.00%) if optimize { . let end = 11,732 ( 0.00%) if let StructKind::MaybeUnsized = kind { fields.len() - 1 } else { fields.len() }; . let optimizing = &mut inverse_memory_index[..end]; 1,676 ( 0.00%) let field_align = |f: &TyAndLayout<'_>| { 1,857 ( 0.00%) if let Some(pack) = pack { f.align.abi.min(pack) } else { f.align.abi } . }; . . // If `-Z randomize-layout` was enabled for the type definition we can shuffle . // the field ordering to try and catch some code making assumptions about layouts . // we don't guarantee . if repr.can_randomize_type_layout() { . // `ReprOptions.layout_seed` is a deterministic seed that we can use to . // randomize field ordering with . let mut rng = Xoshiro128StarStar::seed_from_u64(repr.field_shuffle_seed); . . // Shuffle the ordering of the fields . optimizing.shuffle(&mut rng); . . // Otherwise we just leave things alone and actually optimize the type's fields . } else { 3,352 ( 0.00%) match kind { . StructKind::AlwaysSized | StructKind::MaybeUnsized => { 7,290 ( 0.00%) optimizing.sort_by_key(|&x| { . // Place ZSTs first to avoid "interesting offsets", . // especially with only one or two non-ZST fields. 1,617 ( 0.00%) let f = &fields[x as usize]; 290 ( 0.00%) (!f.is_zst(), cmp::Reverse(field_align(f))) . }); . } . . StructKind::Prefixed(..) => { . // Sort in ascending alignment so that the layout stays optimal . // regardless of the prefix 1,097 ( 0.00%) optimizing.sort_by_key(|&x| field_align(&fields[x as usize])); . } . } . . // FIXME(Kixiron): We can always shuffle fields within a given alignment class . // regardless of the status of `-Z randomize-layout` . } . } . -- line 393 ---------------------------------------- -- line 399 ---------------------------------------- . // produce `memory_index` (see `invert_mapping`). . . let mut sized = true; . let mut offsets = vec![Size::ZERO; fields.len()]; . let mut offset = Size::ZERO; . let mut largest_niche = None; . let mut largest_niche_available = 0; . 5,166 ( 0.00%) if let StructKind::Prefixed(prefix_size, prefix_align) = kind { . let prefix_align = 1,785 ( 0.00%) if let Some(pack) = pack { prefix_align.min(pack) } else { prefix_align }; . align = align.max(AbiAndPrefAlign::new(prefix_align)); . offset = prefix_size.align_to(prefix_align); . } . 681 ( 0.00%) for &i in &inverse_memory_index { 8,816 ( 0.00%) let field = fields[i as usize]; 1,362 ( 0.00%) if !sized { . self.tcx.sess.delay_span_bug( . DUMMY_SP, . &format!( . "univariant: field #{} of `{}` comes after unsized field", . offsets.len(), . ty . ), . ); . } . 3,405 ( 0.00%) if field.is_unsized() { . sized = false; . } . . // Invariant: offset < dl.obj_size_bound() <= 1<<61 1,362 ( 0.00%) let field_align = if let Some(pack) = pack { . field.align.min(AbiAndPrefAlign::new(pack)) . } else { 2,043 ( 0.00%) field.align . }; . offset = offset.align_to(field_align.abi); . align = align.max(field_align); . . debug!("univariant offset: {:?} field: {:#?}", offset, field); 1,362 ( 0.00%) offsets[i as usize] = offset; . 681 ( 0.00%) if !repr.hide_niche() { 6,645 ( 0.00%) if let Some(mut niche) = field.largest_niche { . let available = niche.available(dl); 1,416 ( 0.00%) if available > largest_niche_available { . largest_niche_available = available; . niche.offset += offset; 4,448 ( 0.00%) largest_niche = Some(niche); . } . } . } . 681 ( 0.00%) offset = offset.checked_add(field.size, dl).ok_or(LayoutError::SizeOverflow(ty))?; . } . 3,874 ( 0.00%) if let Some(repr_align) = repr.align { . align = align.max(AbiAndPrefAlign::new(repr_align)); . } . . debug!("univariant min_size: {:?}", offset); . let min_size = offset; . . // As stated above, inverse_memory_index holds field indices by increasing offset. . // This makes it an already-sorted view of the offsets vec. . // To invert it, consider: . // If field 5 has offset 0, offsets[0] is 5, and memory_index[5] should be 0. . // Field 5 would be the first element, so memory_index is i: . // Note: if we didn't optimize, it's already right. . . let memory_index = 3,766 ( 0.00%) if optimize { invert_mapping(&inverse_memory_index) } else { inverse_memory_index }; . . let size = min_size.align_to(align.abi); 3,444 ( 0.00%) let mut abi = Abi::Aggregate { sized }; . . // Unpack newtype ABIs and find scalar pairs. 6,888 ( 0.00%) if sized && size.bytes() > 0 { . // All other fields must be ZSTs. . let mut non_zst_fields = fields.iter().enumerate().filter(|&(_, f)| !f.is_zst()); . 486 ( 0.00%) match (non_zst_fields.next(), non_zst_fields.next(), non_zst_fields.next()) { . // We have exactly one non-ZST field. . (Some((i, field)), None, None) => { . // Field fills the struct and it has a scalar or scalar pair ABI. 1,268 ( 0.00%) if offsets[i].bytes() == 0 && align.abi == field.align.abi && size == field.size . { 832 ( 0.00%) match field.abi { . // For plain scalars, or vectors of them, we can't unpack . // newtypes for `#[repr(C)]`, as that affects C ABIs. 170 ( 0.00%) Abi::Scalar(_) | Abi::Vector { .. } if optimize => { . abi = field.abi; . } . // But scalar pairs are Rust-specific and get . // treated as aggregates by C ABIs anyway. . Abi::ScalarPair(..) => { . abi = field.abi; . } . _ => {} -- line 499 ---------------------------------------- -- line 503 ---------------------------------------- . . // Two non-ZST fields, and they're both scalars. . ( . Some((i, &TyAndLayout { layout: &Layout { abi: Abi::Scalar(a), .. }, .. })), . Some((j, &TyAndLayout { layout: &Layout { abi: Abi::Scalar(b), .. }, .. })), . None, . ) => { . // Order by the memory placement, not source order. 612 ( 0.00%) let ((i, a), (j, b)) = 476 ( 0.00%) if offsets[i] < offsets[j] { ((i, a), (j, b)) } else { ((j, b), (i, a)) }; 748 ( 0.00%) let pair = self.scalar_pair(a, b); 136 ( 0.00%) let pair_offsets = match pair.fields { 136 ( 0.00%) FieldsShape::Arbitrary { ref offsets, ref memory_index } => { 68 ( 0.00%) assert_eq!(memory_index, &[0, 1]); . offsets . } . _ => bug!(), . }; 612 ( 0.00%) if offsets[i] == pair_offsets[0] 68 ( 0.00%) && offsets[j] == pair_offsets[1] . && align == pair.align . && size == pair.size . { . // We can use `ScalarPair` only when it matches our . // already computed layout (including `#[repr(C)]`). 952 ( 0.00%) abi = pair.abi; . } 68 ( 0.00%) } . . _ => {} . } . } . 681 ( 0.00%) if fields.iter().any(|f| f.abi.is_uninhabited()) { . abi = Abi::Uninhabited; . } . 55,104 ( 0.00%) Ok(Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, 17,220 ( 0.00%) fields: FieldsShape::Arbitrary { offsets, memory_index }, . abi, 18,942 ( 0.00%) largest_niche, . align, . size, . }) 17,220 ( 0.00%) } . 19,250 ( 0.00%) fn layout_of_uncached(&self, ty: Ty<'tcx>) -> Result<&'tcx Layout, LayoutError<'tcx>> { 3,850 ( 0.00%) let tcx = self.tcx; 1,925 ( 0.00%) let param_env = self.param_env; . let dl = self.data_layout(); 2,137 ( 0.00%) let scalar_unit = |value: Primitive| { 28 ( 0.00%) let size = value.size(dl); 990 ( 0.00%) assert!(size.bits() <= 128); 676 ( 0.00%) Scalar { value, valid_range: WrappingRange { start: 0, end: size.unsigned_int_max() } } 212 ( 0.00%) }; . let scalar = |value: Primitive| tcx.intern_layout(Layout::scalar(self, scalar_unit(value))); . . let univariant = |fields: &[TyAndLayout<'_>], repr: &ReprOptions, kind| { 25,470 ( 0.00%) Ok(tcx.intern_layout(self.univariant_uninterned(ty, fields, repr, kind)?)) . }; . debug_assert!(!ty.has_infer_types_or_consts()); . 14,400 ( 0.00%) Ok(match *ty.kind() { . // Basic scalars. . ty::Bool => tcx.intern_layout(Layout::scalar( . self, 12 ( 0.00%) Scalar { value: Int(I8, false), valid_range: WrappingRange { start: 0, end: 1 } }, . )), . ty::Char => tcx.intern_layout(Layout::scalar( . self, 12 ( 0.00%) Scalar { . value: Int(I32, false), . valid_range: WrappingRange { start: 0, end: 0x10FFFF }, . }, . )), 30 ( 0.00%) ty::Int(ity) => scalar(Int(Integer::from_int_ty(dl, ity), true)), 55 ( 0.00%) ty::Uint(ity) => scalar(Int(Integer::from_uint_ty(dl, ity), false)), . ty::Float(fty) => scalar(match fty { . ty::FloatTy::F32 => F32, . ty::FloatTy::F64 => F64, . }), . ty::FnPtr(_) => { . let mut ptr = scalar_unit(Pointer); . ptr.valid_range = ptr.valid_range.with_start(1); 24 ( 0.00%) tcx.intern_layout(Layout::scalar(self, ptr)) . } . . // The never type. 3 ( 0.00%) ty::Never => tcx.intern_layout(Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, . fields: FieldsShape::Primitive, . abi: Abi::Uninhabited, . largest_niche: None, 1 ( 0.00%) align: dl.i8_align, . size: Size::ZERO, . }), . . // Potentially-wide pointers. 473 ( 0.00%) ty::Ref(_, pointee, _) | ty::RawPtr(ty::TypeAndMut { ty: pointee, .. }) => { . let mut data_ptr = scalar_unit(Pointer); . if !ty.is_unsafe_ptr() { . data_ptr.valid_range = data_ptr.valid_range.with_start(1); . } . . let pointee = tcx.normalize_erasing_regions(param_env, pointee); 2,944 ( 0.00%) if pointee.is_sized(tcx.at(DUMMY_SP), param_env) { 5,440 ( 0.00%) return Ok(tcx.intern_layout(Layout::scalar(self, data_ptr))); . } . 192 ( 0.00%) let unsized_part = tcx.struct_tail_erasing_lifetimes(pointee, param_env); 192 ( 0.00%) let metadata = match unsized_part.kind() { . ty::Foreign(..) => { 16 ( 0.00%) return Ok(tcx.intern_layout(Layout::scalar(self, data_ptr))); . } 288 ( 0.00%) ty::Slice(_) | ty::Str => scalar_unit(Int(dl.ptr_sized_integer(), false)), . ty::Dynamic(..) => { 22 ( 0.00%) let mut vtable = scalar_unit(Pointer); 22 ( 0.00%) vtable.valid_range = vtable.valid_range.with_start(1); 88 ( 0.00%) vtable . } . _ => return Err(LayoutError::Unknown(unsized_part)), . }; . . // Effectively a (ptr, meta) tuple. 987 ( 0.00%) tcx.intern_layout(self.scalar_pair(data_ptr, metadata)) . } . . // Arrays and slices. 72 ( 0.00%) ty::Array(element, mut count) => { 24 ( 0.00%) if count.has_projections() { . count = tcx.normalize_erasing_regions(param_env, count); . if count.has_projections() { . return Err(LayoutError::Unknown(ty)); . } . } . 96 ( 0.00%) let count = count.try_eval_usize(tcx, param_env).ok_or(LayoutError::Unknown(ty))?; 120 ( 0.00%) let element = self.layout_of(element)?; . let size = 120 ( 0.00%) element.size.checked_mul(count, dl).ok_or(LayoutError::SizeOverflow(ty))?; . . let abi = 180 ( 0.00%) if count != 0 && tcx.conservative_is_privately_uninhabited(param_env.and(ty)) { . Abi::Uninhabited . } else { . Abi::Aggregate { sized: true } . }; . 242 ( 0.00%) let largest_niche = if count != 0 { element.largest_niche } else { None }; . 528 ( 0.00%) tcx.intern_layout(Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, 24 ( 0.00%) fields: FieldsShape::Array { stride: element.size, count }, . abi, . largest_niche, 24 ( 0.00%) align: element.align, . size, . }) . } 26 ( 0.00%) ty::Slice(element) => { 39 ( 0.00%) let element = self.layout_of(element)?; 143 ( 0.00%) tcx.intern_layout(Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, 13 ( 0.00%) fields: FieldsShape::Array { stride: element.size, count: 0 }, . abi: Abi::Aggregate { sized: false }, . largest_niche: None, 13 ( 0.00%) align: element.align, . size: Size::ZERO, . }) . } 12 ( 0.00%) ty::Str => tcx.intern_layout(Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, . fields: FieldsShape::Array { stride: Size::from_bytes(1), count: 0 }, . abi: Abi::Aggregate { sized: false }, . largest_niche: None, 2 ( 0.00%) align: dl.i8_align, . size: Size::ZERO, . }), . . // Odd unit types. 2,168 ( 0.00%) ty::FnDef(..) => univariant(&[], &ReprOptions::default(), StructKind::AlwaysSized)?, . ty::Dynamic(..) | ty::Foreign(..) => { 65 ( 0.00%) let mut unit = self.univariant_uninterned( . ty, . &[], 10 ( 0.00%) &ReprOptions::default(), . StructKind::AlwaysSized, . )?; 10 ( 0.00%) match unit.abi { 5 ( 0.00%) Abi::Aggregate { ref mut sized } => *sized = false, . _ => bug!(), . } 35 ( 0.00%) tcx.intern_layout(unit) . } . . ty::Generator(def_id, substs, _) => self.generator_layout(ty, def_id, substs)?, . . ty::Closure(_, ref substs) => { 66 ( 0.00%) let tys = substs.as_closure().upvar_tys(); 66 ( 0.00%) univariant( 276 ( 0.00%) &tys.map(|ty| self.layout_of(ty)).collect::, _>>()?, 132 ( 0.00%) &ReprOptions::default(), . StructKind::AlwaysSized, . )? . } . 66 ( 0.00%) ty::Tuple(tys) => { . let kind = 198 ( 0.00%) if tys.len() == 0 { StructKind::AlwaysSized } else { StructKind::MaybeUnsized }; . 66 ( 0.00%) univariant( 132 ( 0.00%) &tys.iter() . .map(|k| self.layout_of(k.expect_ty())) . .collect::, _>>()?, 132 ( 0.00%) &ReprOptions::default(), . kind, . )? . } . . // SIMD vector types. 540 ( 0.00%) ty::Adt(def, substs) if def.repr.simd() => { 1 ( 0.00%) if !def.is_struct() { . // Should have yielded E0517 by now. . tcx.sess.delay_span_bug( . DUMMY_SP, . "#[repr(simd)] was applied to an ADT that is not a struct", . ); . return Err(LayoutError::Unknown(ty)); . } . -- line 733 ---------------------------------------- -- line 736 ---------------------------------------- . // * #[repr(simd)] struct S(T, T, T, T); . // * #[repr(simd)] struct S { x: T, y: T, z: T, w: T } . // * #[repr(simd)] struct S([T; 4]) . // . // where T is a primitive scalar (integer/float/pointer). . . // SIMD vectors with zero fields are not supported. . // (should be caught by typeck) 3 ( 0.00%) if def.non_enum_variant().fields.is_empty() { . tcx.sess.fatal(&format!("monomorphising SIMD type `{}` of zero length", ty)); . } . . // Type of the first ADT field: 7 ( 0.00%) let f0_ty = def.non_enum_variant().fields[0].ty(tcx, substs); . . // Heterogeneous SIMD vectors are not supported: . // (should be caught by typeck) 7 ( 0.00%) for fi in &def.non_enum_variant().fields { 24 ( 0.00%) if fi.ty(tcx, substs) != f0_ty { . tcx.sess.fatal(&format!("monomorphising heterogeneous SIMD type `{}`", ty)); . } . } . . // The element type and number of elements of the SIMD vector . // are obtained from: . // . // * the element type and length of the single array field, if . // the first field is of array type, or . // . // * the homogenous field type and the number of fields. 5 ( 0.00%) let (e_ty, e_len, is_array) = if let ty::Array(e_ty, _) = f0_ty.kind() { . // First ADT field is an array: . . // SIMD vectors with multiple array fields are not supported: . // (should be caught by typeck) . if def.non_enum_variant().fields.len() != 1 { . tcx.sess.fatal(&format!( . "monomorphising SIMD type `{}` with more than one array field", . ty -- line 774 ---------------------------------------- -- line 781 ---------------------------------------- . .. . }) = self.layout_of(f0_ty) else { . return Err(LayoutError::Unknown(ty)); . }; . . (*e_ty, *count, true) . } else { . // First ADT field is not an array: 4 ( 0.00%) (f0_ty, def.non_enum_variant().fields.len() as _, false) . }; . . // SIMD vectors of zero length are not supported. . // Additionally, lengths are capped at 2^16 as a fixed maximum backends must . // support. . // . // Can't be caught in typeck if the array length is generic. 2 ( 0.00%) if e_len == 0 { . tcx.sess.fatal(&format!("monomorphising SIMD type `{}` of zero length", ty)); 2 ( 0.00%) } else if e_len > MAX_SIMD_LANES { . tcx.sess.fatal(&format!( . "monomorphising SIMD type `{}` of length greater than {}", . ty, MAX_SIMD_LANES, . )); . } . . // Compute the ABI of the element type: 5 ( 0.00%) let e_ly = self.layout_of(e_ty)?; 8 ( 0.00%) let Abi::Scalar(e_abi) = e_ly.abi else { . // This error isn't caught in typeck, e.g., if . // the element type of the vector is generic. . tcx.sess.fatal(&format!( . "monomorphising SIMD type `{}` with a non-primitive-scalar \ . (integer/float/pointer) element type `{}`", . ty, e_ty . )) . }; . . // Compute the size and alignment of the vector: 5 ( 0.00%) let size = e_ly.size.checked_mul(e_len, dl).ok_or(LayoutError::SizeOverflow(ty))?; 4 ( 0.00%) let align = dl.vector_align(size); 5 ( 0.00%) let size = size.align_to(align.abi); . . // Compute the placement of the vector fields: 1 ( 0.00%) let fields = if is_array { . FieldsShape::Arbitrary { offsets: vec![Size::ZERO], memory_index: vec![0] } . } else { 3 ( 0.00%) FieldsShape::Array { stride: e_ly.size, count: e_len } . }; . 23 ( 0.00%) tcx.intern_layout(Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, . fields, 6 ( 0.00%) abi: Abi::Vector { element: e_abi, count: e_len }, 6 ( 0.00%) largest_niche: e_ly.largest_niche, . size, . align, . }) . } . . // ADTs. 538 ( 0.00%) ty::Adt(def, substs) => { . // Cache the field layouts. 534 ( 0.00%) let variants = def . .variants . .iter() . .map(|v| { . v.fields . .iter() 3,739 ( 0.00%) .map(|field| self.layout_of(field.ty(tcx, substs))) . .collect::, _>>() . }) . .collect::, _>>()?; . 267 ( 0.00%) if def.is_union() { 84 ( 0.00%) if def.repr.pack.is_some() && def.repr.align.is_some() { . self.tcx.sess.delay_span_bug( . tcx.def_span(def.did), . "union cannot be packed and aligned", . ); . return Err(LayoutError::Unknown(ty)); . } . . let mut align = 28 ( 0.00%) if def.repr.pack.is_some() { dl.i8_align } else { dl.aggregate_align }; . 42 ( 0.00%) if let Some(repr_align) = def.repr.align { . align = align.max(AbiAndPrefAlign::new(repr_align)); . } . . let optimize = !def.repr.inhibit_union_abi_opt(); . let mut size = Size::ZERO; 14 ( 0.00%) let mut abi = Abi::Aggregate { sized: true }; . let index = VariantIdx::new(0); . for field in &variants[index] { 188 ( 0.00%) assert!(!field.is_unsized()); . align = align.max(field.align); . . // If all non-ZST fields have the same ABI, forward this ABI 43 ( 0.00%) if optimize && !field.is_zst() { . // Normalize scalar_unit to the maximal valid range 40 ( 0.00%) let field_abi = match field.abi { 28 ( 0.00%) Abi::Scalar(x) => Abi::Scalar(scalar_unit(x.value)), 8 ( 0.00%) Abi::ScalarPair(x, y) => { 100 ( 0.00%) Abi::ScalarPair(scalar_unit(x.value), scalar_unit(y.value)) . } 1 ( 0.00%) Abi::Vector { element: x, count } => { 15 ( 0.00%) Abi::Vector { element: scalar_unit(x.value), count } . } . Abi::Uninhabited | Abi::Aggregate { .. } => { 2 ( 0.00%) Abi::Aggregate { sized: true } . } . }; . 8 ( 0.00%) if size == Size::ZERO { . // first non ZST: initialize 'abi' 96 ( 0.00%) abi = field_abi; . } else if abi != field_abi { . // different fields have different ABI: reset to Aggregate . abi = Abi::Aggregate { sized: true }; . } . } . 42 ( 0.00%) size = cmp::max(size, field.size); . } . 84 ( 0.00%) if let Some(pack) = def.repr.pack { . align = align.min(AbiAndPrefAlign::new(pack)); . } . 602 ( 0.00%) return Ok(tcx.intern_layout(Layout { 14 ( 0.00%) variants: Variants::Single { index }, 28 ( 0.00%) fields: FieldsShape::Union( 14 ( 0.00%) NonZeroUsize::new(variants[index].len()) . .ok_or(LayoutError::Unknown(ty))?, . ), . abi, . largest_niche: None, . align, 28 ( 0.00%) size: size.align_to(align.abi), . })); . } . . // A variant is absent if it's uninhabited and only has ZST fields. . // Present uninhabited variants only require space for their fields, . // but *not* an encoding of the discriminant (e.g., a tag value). . // See issue #49298 for more details on the need to leave space . // for non-ZST uninhabited data (mostly partial initialization). . let absent = |fields: &[TyAndLayout<'_>]| { 571 ( 0.00%) let uninhabited = fields.iter().any(|f| f.abi.is_uninhabited()); . let is_zst = fields.iter().all(|f| f.is_zst()); 217 ( 0.00%) uninhabited && is_zst 217 ( 0.00%) }; . let (present_first, present_second) = { . let mut present_variants = variants . .iter_enumerated() 1,408 ( 0.00%) .filter_map(|(i, v)| if absent(v) { None } else { Some(i) }); . (present_variants.next(), present_variants.next()) . }; 506 ( 0.00%) let present_first = match present_first { . Some(present_first) => present_first, . // Uninhabited because it has no variants, or only absent ones. 2 ( 0.00%) None if def.is_enum() => { 12 ( 0.00%) return Ok(tcx.layout_of(param_env.and(tcx.types.never))?.layout); . } . // If it's a struct, still compute a layout so that we can still compute the . // field offsets. . None => VariantIdx::new(0), . }; . 251 ( 0.00%) let is_struct = !def.is_enum() || . // Only one variant is present. 101 ( 0.00%) (present_second.is_none() && . // Representation optimizations are allowed. . !def.repr.inhibit_enum_layout_opt()); 40 ( 0.00%) if is_struct { . // Struct, or univariant enum equivalent to a struct. . // (Typechecking will reject discriminant-sizing attrs.) . . let v = present_first; 150 ( 0.00%) let kind = if def.is_enum() || variants[v].is_empty() { . StructKind::AlwaysSized . } else { 384 ( 0.00%) let param_env = tcx.param_env(def.did); 128 ( 0.00%) let last_field = def.variants[v].fields.last().unwrap(); . let always_sized = 768 ( 0.00%) tcx.type_of(last_field.did).is_sized(tcx.at(DUMMY_SP), param_env); 256 ( 0.00%) if !always_sized { . StructKind::MaybeUnsized . } else { . StructKind::AlwaysSized . } . }; . 2,080 ( 0.00%) let mut st = self.univariant_uninterned(ty, &variants[v], &def.repr, kind)?; 800 ( 0.00%) st.variants = Variants::Single { index: v }; 1,120 ( 0.00%) let (start, end) = self.tcx.layout_scalar_valid_range(def.did); 640 ( 0.00%) match st.abi { . Abi::Scalar(ref mut scalar) | Abi::ScalarPair(ref mut scalar, _) => { . // the asserts ensure that we are not using the . // `#[rustc_layout_scalar_valid_range(n)]` . // attribute to widen the range of anything as that would probably . // result in UB somewhere . // FIXME(eddyb) the asserts are probably not needed, . // as larger validity ranges would result in missed . // optimizations, *not* wrongly assuming the inner . // value is valid. e.g. unions enlarge validity ranges, . // because the values may be uninitialized. 240 ( 0.00%) if let Bound::Included(start) = start { . // FIXME(eddyb) this might be incorrect - it doesn't . // account for wrap-around (end < start) ranges. 72 ( 0.00%) assert!(scalar.valid_range.start <= start); 36 ( 0.00%) scalar.valid_range.start = start; . } 160 ( 0.00%) if let Bound::Included(end) = end { . // FIXME(eddyb) this might be incorrect - it doesn't . // account for wrap-around (end < start) ranges. . assert!(scalar.valid_range.end >= end); . scalar.valid_range.end = end; . } . . // Update `largest_niche` if we have introduced a larger niche. 240 ( 0.00%) let niche = if def.repr.hide_niche() { . None . } else { 800 ( 0.00%) Niche::from_scalar(dl, Size::ZERO, *scalar) . }; 386 ( 0.00%) if let Some(niche) = niche { 102 ( 0.00%) match st.largest_niche { 238 ( 0.00%) Some(largest_niche) => { . // Replace the existing niche even if they're equal, . // because this one is at a lower offset. 170 ( 0.00%) if largest_niche.available(dl) <= niche.available(dl) { 238 ( 0.00%) st.largest_niche = Some(niche); . } . } 119 ( 0.00%) None => st.largest_niche = Some(niche), . } . } . } . _ => assert!( 240 ( 0.00%) start == Bound::Unbounded && end == Bound::Unbounded, . "nonscalar layout for layout_scalar_valid_range type {:?}: {:#?}", . def, . st, . ), . } . 1,440 ( 0.00%) return Ok(tcx.intern_layout(st)); . } . . // At this point, we have handled all unions and . // structs. (We have also handled univariant enums . // that allow representation optimization.) . assert!(def.is_enum()); . . // The current code for niche-filling relies on variant indices . // instead of actual discriminants, so dataful enums with . // explicit discriminants (RFC #2363) would misbehave. . let no_explicit_discriminants = def . .variants . .iter_enumerated() . .all(|(i, v)| v.discr == ty::VariantDiscr::Relative(i.as_u32())); . 182 ( 0.00%) let mut niche_filling_layout = None; . . // Niche-filling enum optimization. 182 ( 0.00%) if !def.repr.inhibit_enum_layout_opt() && no_explicit_discriminants { . let mut dataful_variant = None; . let mut niche_variants = VariantIdx::MAX..=VariantIdx::new(0); . . // Find one non-ZST variant. 2,135 ( 0.00%) 'variants: for (v, fields) in variants.iter_enumerated() { 651 ( 0.00%) if absent(fields) { . continue 'variants; . } 434 ( 0.00%) for f in fields { 114 ( 0.00%) if !f.is_zst() { . if dataful_variant.is_none() { . dataful_variant = Some(v); . continue 'variants; . } else { . dataful_variant = None; . break 'variants; . } . } . } 548 ( 0.00%) niche_variants = *niche_variants.start().min(&v)..=v; . } . 222 ( 0.00%) if niche_variants.start() > niche_variants.end() { . dataful_variant = None; . } . . if let Some(i) = dataful_variant { 290 ( 0.00%) let count = (niche_variants.end().as_u32() . - niche_variants.start().as_u32() . + 1) as u128; . . // Find the field with the largest niche 58 ( 0.00%) let niche_candidate = variants[i] . .iter() . .enumerate() 118 ( 0.00%) .filter_map(|(j, field)| Some((j, field.largest_niche?))) . .max_by_key(|(_, niche)| niche.available(dl)); . 675 ( 0.00%) if let Some((field_index, niche, (niche_start, niche_scalar))) = 1,012 ( 0.00%) niche_candidate.and_then(|(field_index, niche)| { 602 ( 0.00%) Some((field_index, niche, niche.reserve(self, count)?)) . }) . { 129 ( 0.00%) let mut align = dl.aggregate_align; 86 ( 0.00%) let st = variants . .iter_enumerated() . .map(|(j, v)| { 1,462 ( 0.00%) let mut st = self.univariant_uninterned( . ty, . v, . &def.repr, . StructKind::AlwaysSized, . )?; 258 ( 0.00%) st.variants = Variants::Single { index: j }; . 172 ( 0.00%) align = align.max(st.align); . 516 ( 0.00%) Ok(st) . }) . .collect::, _>>()?; . 344 ( 0.00%) let offset = st[i].fields.offset(field_index) + niche.offset; 86 ( 0.00%) let size = st[i].size; . . let abi = if st.iter().all(|v| v.abi.is_uninhabited()) { . Abi::Uninhabited . } else { 191 ( 0.00%) match st[i].abi { 160 ( 0.00%) Abi::Scalar(_) => Abi::Scalar(niche_scalar), . Abi::ScalarPair(first, second) => { . // We need to use scalar_unit to reset the . // valid range to the maximal one for that . // primitive, because only the niche is . // guaranteed to be initialised, not the . // other primitive. 24 ( 0.00%) if offset.bytes() == 0 { 153 ( 0.00%) Abi::ScalarPair(niche_scalar, scalar_unit(second.value)) . } else { 54 ( 0.00%) Abi::ScalarPair(scalar_unit(first.value), niche_scalar) . } . } . _ => Abi::Aggregate { sized: true }, . } . }; . 473 ( 0.00%) let largest_niche = Niche::from_scalar(dl, offset, niche_scalar); . 2,666 ( 0.00%) niche_filling_layout = Some(Layout { 258 ( 0.00%) variants: Variants::Multiple { . tag: niche_scalar, . tag_encoding: TagEncoding::Niche { . dataful_variant: i, . niche_variants, . niche_start, . }, . tag_field: 0, . variants: st, . }, . fields: FieldsShape::Arbitrary { 215 ( 0.00%) offsets: vec![offset], 215 ( 0.00%) memory_index: vec![0], . }, . abi, . largest_niche, . size, 86 ( 0.00%) align, . }); . } . } . } . 455 ( 0.00%) let (mut min, mut max) = (i128::MAX, i128::MIN); 255 ( 0.00%) let discr_type = def.repr.discr_type(); 273 ( 0.00%) let bits = Integer::from_attr(self, discr_type).size().bits(); 1,256 ( 0.00%) for (i, discr) in def.discriminants(tcx) { 127 ( 0.00%) if variants[i].iter().any(|f| f.abi.is_uninhabited()) { . continue; . } . let mut x = discr.val as i128; 255 ( 0.00%) if discr_type.is_signed() { . // sign extend the raw representation to be an i128 4,541 ( 0.00%) x = (x << (128 - bits)) >> (128 - bits); . } 1,020 ( 0.00%) if x < min { 364 ( 0.00%) min = x; . } 1,020 ( 0.00%) if x > max { 765 ( 0.00%) max = x; . } . } . // We might have no inhabited variants, so pretend there's at least one. 91 ( 0.00%) if (min, max) == (i128::MAX, i128::MIN) { . min = 0; . max = 0; . } 455 ( 0.00%) assert!(min <= max, "discriminant range is {}...{}", min, max); 819 ( 0.00%) let (min_ity, signed) = Integer::repr_discr(tcx, ty, &def.repr, min, max); . 182 ( 0.00%) let mut align = dl.aggregate_align; 91 ( 0.00%) let mut size = Size::ZERO; . . // We're interested in the smallest alignment, so start large. 182 ( 0.00%) let mut start_align = Align::from_bytes(256).unwrap(); 455 ( 0.00%) assert_eq!(Integer::for_align(dl, start_align), None); . . // repr(C) on an enum tells us to make a (tag, union) layout, . // so we need to grow the prefix alignment to be at least . // the alignment of the union. (This value is used both for . // determining the alignment of the overall enum, and the . // determining the alignment of the payload after the tag.) 1,183 ( 0.00%) let mut prefix_align = min_ity.align(dl).abi; 95 ( 0.00%) if def.repr.c() { . for fields in &variants { . for field in fields { . prefix_align = prefix_align.max(field.align.abi); . } . } . } . . // Create the set of structs that represent each variant. 182 ( 0.00%) let mut layout_variants = variants . .iter_enumerated() . .map(|(i, field_layouts)| { 4,845 ( 0.00%) let mut st = self.univariant_uninterned( 255 ( 0.00%) ty, . &field_layouts, 510 ( 0.00%) &def.repr, 1,020 ( 0.00%) StructKind::Prefixed(min_ity.size(), prefix_align), . )?; 765 ( 0.00%) st.variants = Variants::Single { index: i }; . // Find the first field we can't move later . // to make room for a larger discriminant. . for field in 3,569 ( 0.00%) st.fields.index_by_increasing_offset().map(|j| field_layouts[j]) . { 187 ( 0.00%) if !field.is_zst() || field.align.abi.bytes() != 1 { 172 ( 0.00%) start_align = start_align.min(field.align.abi); . break; . } . } 1,020 ( 0.00%) size = cmp::max(size, st.size); 765 ( 0.00%) align = align.max(st.align); 1,530 ( 0.00%) Ok(st) . }) . .collect::, _>>()?; . . // Align the maximum variant size to the largest alignment. 455 ( 0.00%) size = size.align_to(align.abi); . 364 ( 0.00%) if size.bytes() >= dl.obj_size_bound() { . return Err(LayoutError::SizeOverflow(ty)); . } . 364 ( 0.00%) let typeck_ity = Integer::from_attr(dl, def.repr.discr_type()); 273 ( 0.00%) if typeck_ity < min_ity { . // It is a bug if Layout decided on a greater discriminant size than typeck for . // some reason at this point (based on values discriminant can take on). Mostly . // because this discriminant will be loaded, and then stored into variable of . // type calculated by typeck. Consider such case (a bug): typeck decided on . // byte-sized discriminant, but layout thinks we need a 16-bit to store all . // discriminant values. That would be a bug, because then, in codegen, in order . // to store this 16-bit discriminant into 8-bit sized temporary some of the . // space necessary to represent would have to be discarded (or layout is wrong -- line 1250 ---------------------------------------- -- line 1263 ---------------------------------------- . // as the alignment of the first field of each variant. . // We increase the size of the discriminant to avoid LLVM copying . // padding when it doesn't need to. This normally causes unaligned . // load/stores and excessive memcpy/memset operations. By using a . // bigger integer size, LLVM can be sure about its contents and . // won't be so conservative. . . // Use the initial field alignment 271 ( 0.00%) let mut ity = if def.repr.c() || def.repr.int.is_some() { . min_ity . } else { 255 ( 0.00%) Integer::for_align(dl, start_align).unwrap_or(min_ity) . }; . . // If the alignment is not larger than the chosen discriminant size, . // don't use the alignment as the final size. 85 ( 0.00%) if ity <= min_ity { . ity = min_ity; . } else { . // Patch up the variants' first few fields. 128 ( 0.00%) let old_ity_size = min_ity.size(); . let new_ity_size = ity.size(); . for variant in &mut layout_variants { 260 ( 0.00%) match variant.fields { . FieldsShape::Arbitrary { ref mut offsets, .. } => { . for i in offsets { 286 ( 0.00%) if *i <= old_ity_size { 22 ( 0.00%) assert_eq!(*i, old_ity_size); 22 ( 0.00%) *i = new_ity_size; . } . } . // We might be making the struct larger. 130 ( 0.00%) if variant.size <= old_ity_size { 112 ( 0.00%) variant.size = new_ity_size; . } . } . _ => bug!(), . } . } . } . 91 ( 0.00%) let tag_mask = ity.size().unsigned_int_max(); . let tag = Scalar { . value: Int(ity, signed), . valid_range: WrappingRange { 455 ( 0.00%) start: (min as u128 & tag_mask), 364 ( 0.00%) end: (max as u128 & tag_mask), . }, . }; . let mut abi = Abi::Aggregate { sized: true }; 546 ( 0.00%) if tag.value.size(dl) == size { . abi = Abi::Scalar(tag); . } else { . // Try to use a ScalarPair for all tagged enums. . let mut common_prim = None; . for (field_layouts, layout_variant) in iter::zip(&variants, &layout_variants) { 268 ( 0.00%) let offsets = match layout_variant.fields { . FieldsShape::Arbitrary { ref offsets, .. } => offsets, . _ => bug!(), . }; . let mut fields = . iter::zip(field_layouts, offsets).filter(|p| !p.0.is_zst()); 1,340 ( 0.00%) let (field, offset) = match (fields.next(), fields.next()) { . (None, None) => continue, . (Some(pair), None) => pair, . _ => { . common_prim = None; . break; . } . }; 231 ( 0.00%) let prim = match field.abi { 84 ( 0.00%) Abi::Scalar(scalar) => scalar.value, . _ => { . common_prim = None; . break; . } . }; 84 ( 0.00%) if let Some(pair) = common_prim { . // This is pretty conservative. We could go fancier . // by conflating things like i32 and u32, or even . // realising that (u8, u8) could just cohabit with . // u16 or even u32. 36 ( 0.00%) if pair != (prim, offset) { . common_prim = None; . break; . } . } else { . common_prim = Some((prim, offset)); . } . } 72 ( 0.00%) if let Some((prim, offset)) = common_prim { 612 ( 0.00%) let pair = self.scalar_pair(tag, scalar_unit(prim)); 72 ( 0.00%) let pair_offsets = match pair.fields { 72 ( 0.00%) FieldsShape::Arbitrary { ref offsets, ref memory_index } => { 36 ( 0.00%) assert_eq!(memory_index, &[0, 1]); . offsets . } . _ => bug!(), . }; 216 ( 0.00%) if pair_offsets[0] == Size::ZERO 72 ( 0.00%) && pair_offsets[1] == *offset 36 ( 0.00%) && align == pair.align 36 ( 0.00%) && size == pair.size . { . // We can use `ScalarPair` only when it matches our . // already computed layout (including `#[repr(C)]`). 972 ( 0.00%) abi = pair.abi; . } 36 ( 0.00%) } . } . . if layout_variants.iter().all(|v| v.abi.is_uninhabited()) { . abi = Abi::Uninhabited; . } . 1,456 ( 0.00%) let largest_niche = Niche::from_scalar(dl, Size::ZERO, tag); . . let tagged_layout = Layout { . variants: Variants::Multiple { . tag, . tag_encoding: TagEncoding::Direct, . tag_field: 0, . variants: layout_variants, . }, . fields: FieldsShape::Arbitrary { 455 ( 0.00%) offsets: vec![Size::ZERO], 364 ( 0.00%) memory_index: vec![0], . }, . largest_niche, . abi, 182 ( 0.00%) align, 91 ( 0.00%) size, . }; . 316 ( 0.00%) let best_layout = match (tagged_layout, niche_filling_layout) { . (tagged_layout, Some(niche_filling_layout)) => { . // Pick the smaller layout; otherwise, . // pick the layout with the larger niche; otherwise, . // pick tagged as it has simpler codegen. 2,967 ( 0.00%) cmp::min_by_key(tagged_layout, niche_filling_layout, |layout| { 258 ( 0.00%) let niche_size = layout.largest_niche.map_or(0, |n| n.available(dl)); 43 ( 0.00%) (layout.size, cmp::Reverse(niche_size)) . }) . } 2,928 ( 0.00%) (tagged_layout, None) => tagged_layout, . }; . 819 ( 0.00%) tcx.intern_layout(best_layout) 534 ( 0.00%) } . . // Types with no meaningful known layout. . ty::Projection(_) | ty::Opaque(..) => { . // NOTE(eddyb) `layout_of` query should've normalized these away, . // if that was possible, so there's no reason to try again here. . return Err(LayoutError::Unknown(ty)); . } . -- line 1419 ---------------------------------------- -- line 1420 ---------------------------------------- . ty::Placeholder(..) | ty::GeneratorWitness(..) | ty::Infer(_) => { . bug!("Layout::compute: unexpected type `{}`", ty) . } . . ty::Bound(..) | ty::Param(_) | ty::Error(_) => { . return Err(LayoutError::Unknown(ty)); . } . }) 15,400 ( 0.00%) } . } . . /// Overlap eligibility and variant assignment for each GeneratorSavedLocal. . #[derive(Clone, Debug, PartialEq)] . enum SavedLocalEligibility { . Unassigned, . Assigned(VariantIdx), . // FIXME: Use newtype_index so we aren't wasting bytes -- line 1436 ---------------------------------------- -- line 1755 ---------------------------------------- . } . . /// This is invoked by the `layout_of` query to record the final . /// layout of each type. . #[inline(always)] . fn record_layout_for_printing(&self, layout: TyAndLayout<'tcx>) { . // If we are running with `-Zprint-type-sizes`, maybe record layouts . // for dumping later. 9,610 ( 0.00%) if self.tcx.sess.opts.debugging_opts.print_type_sizes { . self.record_layout_for_printing_outlined(layout) . } . } . . fn record_layout_for_printing_outlined(&self, layout: TyAndLayout<'tcx>) { . // Ignore layouts that are done with non-empty environments or . // non-monomorphic layouts, as the user only wants to see the stuff . // resulting from the final codegen session. -- line 1771 ---------------------------------------- -- line 2041 ---------------------------------------- . . pub trait HasParamEnv<'tcx> { . fn param_env(&self) -> ty::ParamEnv<'tcx>; . } . . impl<'tcx> HasDataLayout for TyCtxt<'tcx> { . #[inline] . fn data_layout(&self) -> &TargetDataLayout { 614,066 ( 0.01%) &self.data_layout . } . } . . impl<'tcx> HasTargetSpec for TyCtxt<'tcx> { . fn target_spec(&self) -> &Target { 6 ( 0.00%) &self.sess.target . } . } . . impl<'tcx> HasTyCtxt<'tcx> for TyCtxt<'tcx> { . #[inline] . fn tcx(&self) -> TyCtxt<'tcx> { . *self . } -- line 2063 ---------------------------------------- -- line 2080 ---------------------------------------- . #[inline] . fn tcx(&self) -> TyCtxt<'tcx> { . **self . } . } . . impl<'tcx, C> HasParamEnv<'tcx> for LayoutCx<'tcx, C> { . fn param_env(&self) -> ty::ParamEnv<'tcx> { 5,791 ( 0.00%) self.param_env . } . } . . impl<'tcx, T: HasDataLayout> HasDataLayout for LayoutCx<'tcx, T> { . fn data_layout(&self) -> &TargetDataLayout { . self.tcx.data_layout() . } . } -- line 2096 ---------------------------------------- -- line 2098 ---------------------------------------- . impl<'tcx, T: HasTargetSpec> HasTargetSpec for LayoutCx<'tcx, T> { . fn target_spec(&self) -> &Target { . self.tcx.target_spec() . } . } . . impl<'tcx, T: HasTyCtxt<'tcx>> HasTyCtxt<'tcx> for LayoutCx<'tcx, T> { . fn tcx(&self) -> TyCtxt<'tcx> { 9,176 ( 0.00%) self.tcx.tcx() . } . } . . pub trait MaybeResult { . type Error; . . fn from(x: Result) -> Self; . fn to_result(self) -> Result; -- line 2114 ---------------------------------------- -- line 2124 ---------------------------------------- . Ok(self) . } . } . . impl MaybeResult for Result { . type Error = E; . . fn from(x: Result) -> Self { 237,226 ( 0.00%) x . } . fn to_result(self) -> Result { . self . } . } . . pub type TyAndLayout<'tcx> = rustc_target::abi::TyAndLayout<'tcx, Ty<'tcx>>; . -- line 2140 ---------------------------------------- -- line 2167 ---------------------------------------- . ) -> >>::Error; . } . . /// Blanket extension trait for contexts that can compute layouts of types. . pub trait LayoutOf<'tcx>: LayoutOfHelpers<'tcx> { . /// Computes the layout of a type. Note that this implicitly . /// executes in "reveal all" mode, and will normalize the input type. . #[inline] 741,841 ( 0.02%) fn layout_of(&self, ty: Ty<'tcx>) -> Self::LayoutOfResult { 61,945 ( 0.00%) self.spanned_layout_of(ty, DUMMY_SP) 740,672 ( 0.02%) } . . /// Computes the layout of a type, at `span`. Note that this implicitly . /// executes in "reveal all" mode, and will normalize the input type. . // FIXME(eddyb) avoid passing information like this, and instead add more . // `TyCtxt::at`-like APIs to be able to do e.g. `cx.at(span).layout_of(ty)`. . #[inline] 383,760 ( 0.01%) fn spanned_layout_of(&self, ty: Ty<'tcx>, span: Span) -> Self::LayoutOfResult { 29,520 ( 0.00%) let span = if !span.is_dummy() { span } else { self.layout_tcx_at_span() }; 39,151 ( 0.00%) let tcx = self.tcx().at(span); . . MaybeResult::from( . tcx.layout_of(self.param_env().and(ty)) . .map_err(|err| self.handle_layout_err(err, span, ty)), . ) 236,160 ( 0.00%) } . } . . impl<'tcx, C: LayoutOfHelpers<'tcx>> LayoutOf<'tcx> for C {} . . impl<'tcx> LayoutOfHelpers<'tcx> for LayoutCx<'tcx, TyCtxt<'tcx>> { . type LayoutOfResult = Result, LayoutError<'tcx>>; . . #[inline] -- line 2200 ---------------------------------------- -- line 2216 ---------------------------------------- . err . } . } . . impl<'tcx, C> TyAbiInterface<'tcx, C> for Ty<'tcx> . where . C: HasTyCtxt<'tcx> + HasParamEnv<'tcx>, . { 391,550 ( 0.01%) fn ty_and_layout_for_variant( . this: TyAndLayout<'tcx>, . cx: &C, . variant_index: VariantIdx, . ) -> TyAndLayout<'tcx> { 78,386 ( 0.00%) let layout = match this.variants { . Variants::Single { index } . // If all variants but one are uninhabited, the variant layout is the enum layout. 20 ( 0.00%) if index == variant_index && . // Don't confuse variants of uninhabited enums with the enum itself. . // For more details see https://github.com/rust-lang/rust/issues/69763. . this.fields != FieldsShape::Primitive => . { . this.layout . } . . Variants::Single { index } => { -- line 2240 ---------------------------------------- -- line 2263 ---------------------------------------- . align: tcx.data_layout.i8_align, . size: Size::ZERO, . }) . } . . Variants::Multiple { ref variants, .. } => &variants[variant_index], . }; . 313,544 ( 0.01%) assert_eq!(layout.variants, Variants::Single { index: variant_index }); . . TyAndLayout { ty: this.ty, layout } 391,550 ( 0.01%) } . 2,799,915 ( 0.06%) fn ty_and_layout_field(this: TyAndLayout<'tcx>, cx: &C, i: usize) -> TyAndLayout<'tcx> { . enum TyMaybeWithLayout<'tcx> { . Ty(Ty<'tcx>), . TyAndLayout(TyAndLayout<'tcx>), . } . 2,306,131 ( 0.05%) fn field_ty_or_layout<'tcx>( . this: TyAndLayout<'tcx>, . cx: &(impl HasTyCtxt<'tcx> + HasParamEnv<'tcx>), . i: usize, . ) -> TyMaybeWithLayout<'tcx> { . let tcx = cx.tcx(); . let tag_layout = |tag: Scalar| -> TyAndLayout<'tcx> { 911,521 ( 0.02%) let layout = Layout::scalar(cx, tag); 741,065 ( 0.02%) TyAndLayout { layout: tcx.intern_layout(layout), ty: tag.value.to_ty(tcx) } . }; . 562,053 ( 0.01%) match *this.ty.kind() { . ty::Bool . | ty::Char . | ty::Int(_) . | ty::Uint(_) . | ty::Float(_) . | ty::FnPtr(_) . | ty::Never . | ty::FnDef(..) . | ty::GeneratorWitness(..) . | ty::Foreign(..) . | ty::Dynamic(..) => bug!("TyAndLayout::field({:?}): not applicable", this), . . // Potentially-fat pointers. . ty::Ref(_, pointee, _) | ty::RawPtr(ty::TypeAndMut { ty: pointee, .. }) => { 5,586 ( 0.00%) assert!(i < this.fields.count()); . . // Reuse the fat `*T` type as its own thin pointer data field. . // This provides information about, e.g., DST struct pointees . // (which may have no non-DST form), and will work as long . // as the `Abi` or `FieldsShape` is checked by users. 5,586 ( 0.00%) if i == 0 { . let nil = tcx.mk_unit(); 1,417 ( 0.00%) let unit_ptr_ty = if this.ty.is_unsafe_ptr() { . tcx.mk_mut_ptr(nil) . } else { 1,184 ( 0.00%) tcx.mk_mut_ref(tcx.lifetimes.re_static, nil) . }; . . // NOTE(eddyb) using an empty `ParamEnv`, and `unwrap`-ing . // the `Result` should always work because the type is . // always either `*mut ()` or `&'static mut ()`. 4,277 ( 0.00%) return TyMaybeWithLayout::TyAndLayout(TyAndLayout { . ty: this.ty, . ..tcx.layout_of(ty::ParamEnv::reveal_all().and(unit_ptr_ty)).unwrap() . }); . } . 9,860 ( 0.00%) match tcx.struct_tail_erasing_lifetimes(pointee, cx.param_env()).kind() { 2,524 ( 0.00%) ty::Slice(_) | ty::Str => TyMaybeWithLayout::Ty(tcx.types.usize), . ty::Dynamic(_, _) => { . TyMaybeWithLayout::Ty(tcx.mk_imm_ref( 114 ( 0.00%) tcx.lifetimes.re_static, 368 ( 0.00%) tcx.mk_array(tcx.types.usize, 3), . )) . /* FIXME: use actual fn pointers . Warning: naively computing the number of entries in the . vtable by counting the methods on the trait + methods on . all parent traits does not work, because some methods can . be not object safe and thus excluded from the vtable. . Increase this counter if you tried to implement this but . failed to do it without duplicating a lot of code from -- line 2344 ---------------------------------------- -- line 2350 ---------------------------------------- . */ . } . _ => bug!("TyAndLayout::field({:?}): not applicable", this), . } . } . . // Arrays and slices. . ty::Array(element, _) | ty::Slice(element) => TyMaybeWithLayout::Ty(element), 550 ( 0.00%) ty::Str => TyMaybeWithLayout::Ty(tcx.types.u8), . . // Tuples, generators and closures. . ty::Closure(_, ref substs) => field_ty_or_layout( 879 ( 0.00%) TyAndLayout { ty: substs.as_closure().tupled_upvars_ty(), ..this }, . cx, . i, . ), . . ty::Generator(def_id, ref substs, _) => match this.variants { . Variants::Single { index } => TyMaybeWithLayout::Ty( . substs . .as_generator() -- line 2370 ---------------------------------------- -- line 2377 ---------------------------------------- . Variants::Multiple { tag, tag_field, .. } => { . if i == tag_field { . return TyMaybeWithLayout::TyAndLayout(tag_layout(tag)); . } . TyMaybeWithLayout::Ty(substs.as_generator().prefix_tys().nth(i).unwrap()) . } . }, . 72,342 ( 0.00%) ty::Tuple(tys) => TyMaybeWithLayout::Ty(tys[i].expect_ty()), . . // ADTs. 99,421 ( 0.00%) ty::Adt(def, substs) => { 312,852 ( 0.01%) match this.variants { 99,421 ( 0.00%) Variants::Single { index } => { 397,684 ( 0.01%) TyMaybeWithLayout::Ty(def.variants[index].fields[i].ty(tcx, substs)) . } . . // Discriminant field for enums (where applicable). . Variants::Multiple { tag, .. } => { 114,010 ( 0.00%) assert_eq!(i, 0); 1,677 ( 0.00%) return TyMaybeWithLayout::TyAndLayout(tag_layout(tag)); . } . } . } . . ty::Projection(_) . | ty::Bound(..) . | ty::Placeholder(..) . | ty::Opaque(..) . | ty::Param(_) . | ty::Infer(_) . | ty::Error(_) => bug!("TyAndLayout::field: unexpected type `{}`", this.ty), . } 1,681,659 ( 0.03%) } . 747,404 ( 0.02%) match field_ty_or_layout(this, cx, i) { 256,858 ( 0.01%) TyMaybeWithLayout::Ty(field_ty) => { 7,291 ( 0.00%) cx.tcx().layout_of(cx.param_env().and(field_ty)).unwrap_or_else(|e| { . bug!( . "failed to get layout for `{}`: {},\n\ . despite it being a field (#{}) of an existing layout: {:#?}", . field_ty, . e, . i, . this . ) . }) . } 175,266 ( 0.00%) TyMaybeWithLayout::TyAndLayout(field_layout) => field_layout, . } 1,493,288 ( 0.03%) } . 36,870 ( 0.00%) fn ty_and_layout_pointee_info_at( . this: TyAndLayout<'tcx>, . cx: &C, . offset: Size, . ) -> Option { 1,138 ( 0.00%) let tcx = cx.tcx(); . let param_env = cx.param_env(); . . let addr_space_of_ty = |ty: Ty<'tcx>| { 2,071 ( 0.00%) if ty.is_fn() { cx.data_layout().instruction_address_space } else { AddressSpace::DATA } . }; . 18,894 ( 0.00%) let pointee_info = match *this.ty.kind() { 2,851 ( 0.00%) ty::RawPtr(mt) if offset.bytes() == 0 => { . tcx.layout_of(param_env.and(mt.ty)).ok().map(|layout| PointeeInfo { 933 ( 0.00%) size: layout.size, 933 ( 0.00%) align: layout.align.abi, . safe: None, 933 ( 0.00%) address_space: addr_space_of_ty(mt.ty), 4,665 ( 0.00%) }) . } 2,952 ( 0.00%) ty::FnPtr(fn_sig) if offset.bytes() == 0 => { . tcx.layout_of(param_env.and(tcx.mk_fn_ptr(fn_sig))).ok().map(|layout| PointeeInfo { 16 ( 0.00%) size: layout.size, . align: layout.align.abi, . safe: None, 8 ( 0.00%) address_space: cx.data_layout().instruction_address_space, 24 ( 0.00%) }) . } 3,403 ( 0.00%) ty::Ref(_, ty, mt) if offset.bytes() == 0 => { 1,129 ( 0.00%) let address_space = addr_space_of_ty(ty); 2,258 ( 0.00%) let kind = if tcx.sess.opts.optimize == OptLevel::No { . // Use conservative pointer kind if not optimizing. This saves us the . // Freeze/Unpin queries, and can save time in the codegen backend (noalias . // attributes in LLVM have compile-time cost even in unoptimized builds). . PointerKind::Shared . } else { . match mt { . hir::Mutability::Not => { . if ty.is_freeze(tcx.at(DUMMY_SP), cx.param_env()) { -- line 2468 ---------------------------------------- -- line 2481 ---------------------------------------- . } else { . PointerKind::Shared . } . } . } . }; . . tcx.layout_of(param_env.and(ty)).ok().map(|layout| PointeeInfo { 1,129 ( 0.00%) size: layout.size, . align: layout.align.abi, . safe: Some(kind), . address_space, 7,903 ( 0.00%) }) . } . . _ => { 3,274 ( 0.00%) let mut data_variant = match this.variants { . // Within the discriminant field, only the niche itself is . // always initialized, so we only check for a pointer at its . // offset. . // . // If the niche is a pointer, it's either valid (according . // to its type), or null (which the niche field's scalar . // validity range encodes). This allows using . // `dereferenceable_or_null` for e.g., `Option<&T>`, and . // this will continue to work as long as we don't start . // using more niches than just null (e.g., the first page of . // the address space, or unaligned pointers). . Variants::Multiple { 123 ( 0.00%) tag_encoding: TagEncoding::Niche { dataful_variant, .. }, . tag_field, . .. 538 ( 0.00%) } if this.fields.offset(tag_field) == offset => { . Some(this.for_variant(cx, dataful_variant)) . } . _ => Some(this), . }; . 246 ( 0.00%) if let Some(variant) = data_variant { . // We're not interested in any unions. 4,506 ( 0.00%) if let FieldsShape::Union(_) = variant.fields { . data_variant = None; . } . } . . let mut result = None; . . if let Some(variant) = data_variant { . let ptr_end = offset + Pointer.size(cx); . for i in 0..variant.fields.count() { . let field_start = variant.fields.offset(i); 12,222 ( 0.00%) if field_start <= offset { . let field = variant.field(cx, i); . result = field.to_result().ok().and_then(|field| { 3,458 ( 0.00%) if ptr_end <= field_start + field.size { . // We found the right field, look inside it. . let field_info = 5,948 ( 0.00%) field.pointee_info_at(cx, offset - field_start); . field_info . } else { . None . } . }); 1,487 ( 0.00%) if result.is_some() { . break; . } . } . } . } . . // FIXME(eddyb) This should be for `ptr::Unique`, not `Box`. . if let Some(ref mut pointee) = result { 2,958 ( 0.00%) if let ty::Adt(def, _) = this.ty.kind() { 9,336 ( 0.00%) if def.is_box() && offset.bytes() == 0 { . pointee.safe = Some(PointerKind::UniqueOwned); . } . } . } . . result . } . }; -- line 2562 ---------------------------------------- -- line 2564 ---------------------------------------- . debug!( . "pointee_info_at (offset={:?}, type kind: {:?}) => {:?}", . offset, . this.ty.kind(), . pointee_info . ); . . pointee_info 57,152 ( 0.00%) } . } . . impl<'tcx> ty::Instance<'tcx> { . // NOTE(eddyb) this is private to avoid using it from outside of . // `fn_abi_of_instance` - any other uses are either too high-level . // for `Instance` (e.g. typeck would use `Ty::fn_sig` instead), . // or should go through `FnAbi` instead, to avoid losing any . // adjustments `fn_abi_of_instance` might be performing. 12,386 ( 0.00%) fn fn_sig_for_fn_abi( . &self, . tcx: TyCtxt<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> ty::PolyFnSig<'tcx> { 6,756 ( 0.00%) let ty = self.ty(tcx, param_env); 3,494 ( 0.00%) match *ty.kind() { . ty::FnDef(..) => { . // HACK(davidtwco,eddyb): This is a workaround for polymorphization considering . // parameters unused if they show up in the signature, but not in the `mir::Body` . // (i.e. due to being inside a projection that got normalized, see . // `src/test/ui/polymorphization/normalized_sig_types.rs`), and codegen not keeping . // track of a polymorphization `ParamEnv` to allow normalizing later. 2,136 ( 0.00%) let mut sig = match *ty.kind() { 7,476 ( 0.00%) ty::FnDef(def_id, substs) => tcx . .normalize_erasing_regions(tcx.param_env(def_id), tcx.fn_sig(def_id)) . .subst(tcx, substs), . _ => unreachable!(), . }; . 2,136 ( 0.00%) if let ty::InstanceDef::VtableShim(..) = self.def { . // Modify `fn(self, ...)` to `fn(self: *mut Self, ...)`. . sig = sig.map_bound(|mut sig| { . let mut inputs_and_output = sig.inputs_and_output.to_vec(); . inputs_and_output[0] = tcx.mk_mut_ptr(inputs_and_output[0]); . sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output); . sig . }); . } 8,544 ( 0.00%) sig . } 232 ( 0.00%) ty::Closure(def_id, substs) => { 116 ( 0.00%) let sig = substs.as_closure().sig(); . . let bound_vars = tcx.mk_bound_variable_kinds( . sig.bound_vars() . .iter() . .chain(iter::once(ty::BoundVariableKind::Region(ty::BrEnv))), . ); . let br = ty::BoundRegion { 116 ( 0.00%) var: ty::BoundVar::from_usize(bound_vars.len() - 1), . kind: ty::BoundRegionKind::BrEnv, . }; . let env_region = ty::ReLateBound(ty::INNERMOST, br); 522 ( 0.00%) let env_ty = tcx.closure_env_ty(def_id, substs, env_region).unwrap(); . 58 ( 0.00%) let sig = sig.skip_binder(); . ty::Binder::bind_with_vars( . tcx.mk_fn_sig( . iter::once(env_ty).chain(sig.inputs().iter().cloned()), . sig.output(), 116 ( 0.00%) sig.c_variadic, 348 ( 0.00%) sig.unsafety, . sig.abi, . ), . bound_vars, . ) . } . ty::Generator(_, substs, _) => { . let sig = substs.as_generator().poly_sig(); . -- line 2641 ---------------------------------------- -- line 2669 ---------------------------------------- . hir::Unsafety::Normal, . rustc_target::spec::abi::Abi::Rust, . ), . bound_vars, . ) . } . _ => bug!("unexpected type {:?} in Instance::fn_sig", ty), . } 10,134 ( 0.00%) } . } . . /// Calculates whether a function's ABI can unwind or not. . /// . /// This takes two primary parameters: . /// . /// * `codegen_fn_attr_flags` - these are flags calculated as part of the . /// codegen attrs for a defined function. For function pointers this set of -- line 2685 ---------------------------------------- -- line 2725 ---------------------------------------- . /// might (from a foreign exception or similar). . #[inline] . pub fn fn_can_unwind<'tcx>( . tcx: TyCtxt<'tcx>, . codegen_fn_attr_flags: CodegenFnAttrFlags, . abi: SpecAbi, . ) -> bool { . // Special attribute for functions which can't unwind. 1,506 ( 0.00%) if codegen_fn_attr_flags.contains(CodegenFnAttrFlags::NEVER_UNWIND) { . return false; . } . . // Otherwise if this isn't special then unwinding is generally determined by . // the ABI of the itself. ABIs like `C` have variants which also . // specifically allow unwinding (`C-unwind`), but not all platform-specific . // ABIs have such an option. Otherwise the only other thing here is Rust . // itself, and those ABIs are determined by the panic strategy configured -- line 2741 ---------------------------------------- -- line 2767 ---------------------------------------- . // to `panic=abort`). . // . // Eventually the check against `c_unwind` here will ideally get removed and . // this'll be a little cleaner as it'll be a straightforward check of the . // ABI. . // . // [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/2945-c-unwind-abi.md . use SpecAbi::*; 1,508 ( 0.00%) match abi { . C { unwind } | Stdcall { unwind } | System { unwind } | Thiscall { unwind } => { 6 ( 0.00%) unwind 12 ( 0.00%) || (!tcx.features().c_unwind && tcx.sess.panic_strategy() == PanicStrategy::Unwind) . } . Cdecl . | Fastcall . | Vectorcall . | Aapcs . | Win64 . | SysV64 . | PtxKernel -- line 2786 ---------------------------------------- -- line 2797 ---------------------------------------- . | Unadjusted => false, . Rust | RustCall => tcx.sess.panic_strategy() == PanicStrategy::Unwind, . } . } . . #[inline] . pub fn conv_from_spec_abi(tcx: TyCtxt<'_>, abi: SpecAbi) -> Conv { . use rustc_target::spec::abi::Abi::*; 11,290 ( 0.00%) match tcx.sess.target.adjust_abi(abi) { . RustIntrinsic | PlatformIntrinsic | Rust | RustCall => Conv::Rust, . . // It's the ABI's job to select this, not ours. . System { .. } => bug!("system abi should be selected elsewhere"), . EfiApi => bug!("eficall abi should be selected elsewhere"), . . Stdcall { .. } => Conv::X86Stdcall, . Fastcall => Conv::X86Fastcall, -- line 2813 ---------------------------------------- -- line 2901 ---------------------------------------- . /// instead, where the instance is an `InstanceDef::Virtual`. . #[inline] . fn fn_abi_of_fn_ptr( . &self, . sig: ty::PolyFnSig<'tcx>, . extra_args: &'tcx ty::List>, . ) -> Self::FnAbiOfResult { . // FIXME(eddyb) get a better `span` here. 18 ( 0.00%) let span = self.layout_tcx_at_span(); 18 ( 0.00%) let tcx = self.tcx().at(span); . . MaybeResult::from(tcx.fn_abi_of_fn_ptr(self.param_env().and((sig, extra_args))).map_err( . |err| self.handle_fn_abi_err(err, span, FnAbiRequest::OfFnPtr { sig, extra_args }), . )) . } . . /// Compute a `FnAbi` suitable for declaring/defining an `fn` instance, and for . /// direct calls to an `fn`. . /// . /// NB: that includes virtual calls, which are represented by "direct calls" . /// to an `InstanceDef::Virtual` instance (of `::fn`). . #[inline] 20,664 ( 0.00%) fn fn_abi_of_instance( . &self, . instance: ty::Instance<'tcx>, . extra_args: &'tcx ty::List>, . ) -> Self::FnAbiOfResult { . // FIXME(eddyb) get a better `span` here. 7,942 ( 0.00%) let span = self.layout_tcx_at_span(); 13,694 ( 0.00%) let tcx = self.tcx().at(span); . . MaybeResult::from( 32,246 ( 0.00%) tcx.fn_abi_of_instance(self.param_env().and((instance, extra_args))).map_err(|err| { . // HACK(eddyb) at least for definitions of/calls to `Instance`s, . // we can get some kind of span even if one wasn't provided. . // However, we don't do this early in order to avoid calling . // `def_span` unconditionally (which may have a perf penalty). . let span = if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) }; . self.handle_fn_abi_err(err, span, FnAbiRequest::OfInstance { instance, extra_args }) . }), . ) 20,664 ( 0.00%) } . } . . impl<'tcx, C: FnAbiOfHelpers<'tcx>> FnAbiOf<'tcx> for C {} . 9 ( 0.00%) fn fn_abi_of_fn_ptr<'tcx>( . tcx: TyCtxt<'tcx>, . query: ty::ParamEnvAnd<'tcx, (ty::PolyFnSig<'tcx>, &'tcx ty::List>)>, . ) -> Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, FnAbiError<'tcx>> { 6 ( 0.00%) let (param_env, (sig, extra_args)) = query.into_parts(); . 21 ( 0.00%) LayoutCx { tcx, param_env }.fn_abi_new_uncached( 12 ( 0.00%) sig, . extra_args, . None, . CodegenFnAttrFlags::empty(), . false, . ) 12 ( 0.00%) } . 10,134 ( 0.00%) fn fn_abi_of_instance<'tcx>( . tcx: TyCtxt<'tcx>, . query: ty::ParamEnvAnd<'tcx, (ty::Instance<'tcx>, &'tcx ty::List>)>, . ) -> Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, FnAbiError<'tcx>> { 9,008 ( 0.00%) let (param_env, (instance, extra_args)) = query.into_parts(); . 4,504 ( 0.00%) let sig = instance.fn_sig_for_fn_abi(tcx, param_env); . 5,630 ( 0.00%) let caller_location = if instance.def.requires_caller_location(tcx) { 234 ( 0.00%) Some(tcx.caller_location_ty()) . } else { . None . }; . 1,126 ( 0.00%) let attrs = tcx.codegen_fn_attrs(instance.def_id()).flags; . 9,008 ( 0.00%) LayoutCx { tcx, param_env }.fn_abi_new_uncached( 4,504 ( 0.00%) sig, . extra_args, . caller_location, . attrs, 5,630 ( 0.00%) matches!(instance.def, ty::InstanceDef::Virtual(..)), . ) 10,134 ( 0.00%) } . . impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> { . // FIXME(eddyb) perhaps group the signature/type-containing (or all of them?) . // arguments of this method, into a separate `struct`. 14,677 ( 0.00%) fn fn_abi_new_uncached( . &self, . sig: ty::PolyFnSig<'tcx>, . extra_args: &[Ty<'tcx>], . caller_location: Option>, . codegen_fn_attr_flags: CodegenFnAttrFlags, . // FIXME(eddyb) replace this with something typed, like an `enum`. . force_thin_self_ptr: bool, . ) -> Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, FnAbiError<'tcx>> { . debug!("fn_abi_new_uncached({:?}, {:?})", sig, extra_args); . 16,935 ( 0.00%) let sig = self.tcx.normalize_erasing_late_bound_regions(self.param_env, sig); . . let conv = conv_from_spec_abi(self.tcx(), sig.abi); . . let mut inputs = sig.inputs(); . let extra_args = if sig.abi == RustCall { 276 ( 0.00%) assert!(!sig.c_variadic && extra_args.is_empty()); . 69 ( 0.00%) if let Some(input) = sig.inputs().last() { 276 ( 0.00%) if let ty::Tuple(tupled_arguments) = input.kind() { . inputs = &sig.inputs()[0..sig.inputs().len() - 1]; 69 ( 0.00%) tupled_arguments.iter().map(|k| k.expect_ty()).collect() . } else { . bug!( . "argument to function with \"rust-call\" ABI \ . is not a tuple" . ); . } . } else { . bug!( . "argument to function with \"rust-call\" ABI \ . is not a tuple" . ); . } . } else { 4,240 ( 0.00%) assert!(sig.c_variadic || extra_args.is_empty()); . extra_args.to_vec() . }; . 1,267 ( 0.00%) let target = &self.tcx.sess.target; 3,387 ( 0.00%) let target_env_gnu_like = matches!(&target.env[..], "gnu" | "musl" | "uclibc"); 3,387 ( 0.00%) let win_x64_gnu = target.os == "windows" && target.arch == "x86_64" && target.env == "gnu"; . let linux_s390x_gnu_like = 4,516 ( 0.00%) target.os == "linux" && target.arch == "s390x" && target_env_gnu_like; . let linux_sparc64_gnu_like = 4,516 ( 0.00%) target.os == "linux" && target.arch == "sparc64" && target_env_gnu_like; . let linux_powerpc_gnu_like = 6,774 ( 0.00%) target.os == "linux" && target.arch == "powerpc" && target_env_gnu_like; . use SpecAbi::*; 4,516 ( 0.00%) let rust_abi = matches!(sig.abi, RustIntrinsic | PlatformIntrinsic | Rust | RustCall); . . // Handle safe Rust thin and fat pointers. 1,129 ( 0.00%) let adjust_for_rust_scalar = |attrs: &mut ArgAttributes, . scalar: Scalar, . layout: TyAndLayout<'tcx>, . offset: Size, . is_return: bool| { . // Booleans are always an i1 that needs to be zero-extended. 187 ( 0.00%) if scalar.is_bool() { 390 ( 0.00%) attrs.ext(ArgExtension::Zext); . return; . } . . // Only pointer types handled below. 1,642 ( 0.00%) if scalar.value != Pointer { . return; . } . 1,642 ( 0.00%) if !scalar.valid_range.contains(0) { 2,194 ( 0.00%) attrs.set(ArgAttribute::NonNull); . } . 13,438 ( 0.00%) if let Some(pointee) = layout.pointee_info_at(self, offset) { . if let Some(kind) = pointee.safe { 2,916 ( 0.00%) attrs.pointee_align = Some(pointee.align); . . // `Box` (`UniqueBorrowed`) are not necessarily dereferenceable . // for the entire duration of the function as they can be deallocated . // at any time. Set their valid size to 0. 4,860 ( 0.00%) attrs.pointee_size = match kind { . PointerKind::UniqueOwned => Size::ZERO, . _ => pointee.size, . }; . . // `Box` pointer parameters never alias because ownership is transferred . // `&mut` pointer parameters never alias other parameters, . // or mutable global data . // -- line 3078 ---------------------------------------- -- line 3080 ---------------------------------------- . // and can be marked as both `readonly` and `noalias`, as . // LLVM's definition of `noalias` is based solely on memory . // dependencies rather than pointer equality . // . // Due to past miscompiles in LLVM, we apply a separate NoAliasMutRef attribute . // for UniqueBorrowed arguments, so that the codegen backend can decide whether . // or not to actually emit the attribute. It can also be controlled with the . // `-Zmutable-noalias` debugging option. 4,860 ( 0.00%) let no_alias = match kind { . PointerKind::Shared | PointerKind::UniqueBorrowed => false, . PointerKind::UniqueOwned => true, . PointerKind::Frozen => !is_return, . }; . if no_alias { 14 ( 0.00%) attrs.set(ArgAttribute::NoAlias); . } . 2,916 ( 0.00%) if kind == PointerKind::Frozen && !is_return { . attrs.set(ArgAttribute::ReadOnly); . } . 2,916 ( 0.00%) if kind == PointerKind::UniqueBorrowed && !is_return { . attrs.set(ArgAttribute::NoAliasMutRef); . } . } . } . }; . 16,935 ( 0.00%) let arg_of = |ty: Ty<'tcx>, arg_idx: Option| -> Result<_, FnAbiError<'tcx>> { 4,713 ( 0.00%) let is_return = arg_idx.is_none(); . 6,308 ( 0.00%) let layout = self.layout_of(ty)?; 5,378 ( 0.00%) let layout = if force_thin_self_ptr && arg_idx == Some(0) { . // Don't pass the vtable, it's not an argument of the virtual fn. . // Instead, pass just the data pointer, but give it the type `*const/mut dyn Trait` . // or `&/&mut dyn Trait` because this is special-cased elsewhere in codegen 6 ( 0.00%) make_thin_self_ptr(self, layout) . } else { . layout . }; . 54,759 ( 0.00%) let mut arg = ArgAbi::new(self, layout, |layout, scalar, offset| { 9,162 ( 0.00%) let mut attrs = ArgAttributes::new(); 15,270 ( 0.00%) adjust_for_rust_scalar(&mut attrs, scalar, *layout, offset, is_return); . attrs 30,540 ( 0.00%) }); . 541 ( 0.00%) if arg.layout.is_zst() { . // For some forsaken reason, x86_64-pc-windows-gnu . // doesn't ignore zero-sized struct arguments. . // The same is true for {s390x,sparc64,powerpc}-unknown-linux-{gnu,musl,uclibc}. 986 ( 0.00%) if is_return 128 ( 0.00%) || rust_abi . || (!win_x64_gnu . && !linux_s390x_gnu_like . && !linux_sparc64_gnu_like . && !linux_powerpc_gnu_like) . { 365 ( 0.00%) arg.mode = PassMode::Ignore; . } . } . 53,773 ( 0.00%) Ok(arg) . }; . 46,289 ( 0.00%) let mut fn_abi = FnAbi { . ret: arg_of(sig.output(), None)?, 2,258 ( 0.00%) args: inputs . .iter() . .cloned() . .chain(extra_args) . .chain(caller_location) . .enumerate() 1,792 ( 0.00%) .map(|(i, ty)| arg_of(ty, Some(i))) . .collect::>()?, . c_variadic: sig.c_variadic, . fixed_count: inputs.len(), . conv, . can_unwind: fn_can_unwind(self.tcx(), codegen_fn_attr_flags, sig.abi), . }; . self.fn_abi_adjust_for_abi(&mut fn_abi, sig.abi)?; . debug!("fn_abi_new_uncached = {:?}", fn_abi); 4,516 ( 0.00%) Ok(self.tcx.arena.alloc(fn_abi)) 9,032 ( 0.00%) } . . fn fn_abi_adjust_for_abi( . &self, . fn_abi: &mut FnAbi<'tcx, Ty<'tcx>>, . abi: SpecAbi, . ) -> Result<(), FnAbiError<'tcx>> { . if abi == SpecAbi::Unadjusted { . return Ok(()); . } . . if abi == SpecAbi::Rust . || abi == SpecAbi::RustCall . || abi == SpecAbi::RustIntrinsic . || abi == SpecAbi::PlatformIntrinsic . { 16,136 ( 0.00%) let fixup = |arg: &mut ArgAbi<'tcx, Ty<'tcx>>| { 2,908 ( 0.00%) if arg.is_ignore() { . return; . } . 15,262 ( 0.00%) match arg.layout.abi { . Abi::Aggregate { .. } => {} . . // This is a fun case! The gist of what this is doing is . // that we want callers and callees to always agree on the . // ABI of how they pass SIMD arguments. If we were to *not* . // make these arguments indirect then they'd be immediates . // in LLVM, which means that they'd used whatever the . // appropriate ABI is for the callee and the caller. That -- line 3192 ---------------------------------------- -- line 3199 ---------------------------------------- . // which should get them all to agree on ABI regardless of . // target feature sets. Some more information about this . // issue can be found in #44367. . // . // Note that the platform intrinsic ABI is exempt here as . // that's how we connect up to LLVM and it's unstable . // anyway, we control all calls to it in libstd. . Abi::Vector { .. } 2 ( 0.00%) if abi != SpecAbi::PlatformIntrinsic 6 ( 0.00%) && self.tcx.sess.target.simd_types_indirect => . { . arg.make_indirect(); . return; . } . . _ => return, . } . . // Pass and return structures up to 2 pointers in size by value, matching `ScalarPair`. . // LLVM will usually pass these in 2 registers, which is more efficient than by-ref. 176 ( 0.00%) let max_by_val_size = Pointer.size(self) * 2; . let size = arg.layout.size; . 704 ( 0.00%) if arg.layout.is_unsized() || size > max_by_val_size { . arg.make_indirect(); . } else { . // We want to pass small aggregates as immediates, but using . // a LLVM aggregate type for this leads to bad optimizations, . // so we pick an appropriately sized integer type instead. . arg.cast_to(Reg { kind: RegKind::Integer, size }); . } 13,770 ( 0.00%) }; 1,126 ( 0.00%) fixup(&mut fn_abi.ret); . for arg in &mut fn_abi.args { 8,499 ( 0.00%) fixup(arg); . } . } else { 18 ( 0.00%) fn_abi.adjust_for_foreign_abi(self, abi)?; . } . . Ok(()) . } . } . 12 ( 0.00%) fn make_thin_self_ptr<'tcx>( . cx: &(impl HasTyCtxt<'tcx> + HasParamEnv<'tcx>), . layout: TyAndLayout<'tcx>, . ) -> TyAndLayout<'tcx> { . let tcx = cx.tcx(); 1 ( 0.00%) let fat_pointer_ty = if layout.is_unsized() { . // unsized `self` is passed as a pointer to `self` . // FIXME (mikeyhew) change this to use &own if it is ever added to the language . tcx.mk_mut_ptr(layout.ty) . } else { 2 ( 0.00%) match layout.abi { . Abi::ScalarPair(..) => (), . _ => bug!("receiver type has unsupported layout: {:?}", layout), . } . . // In the case of Rc, we need to explicitly pass a *mut RcBox . // with a Scalar (not ScalarPair) ABI. This is a hack that is understood . // elsewhere in the compiler as a method on a `dyn Trait`. . // To get the type `*mut RcBox`, we just keep unwrapping newtypes until we . // get a built-in pointer type 2 ( 0.00%) let mut fat_pointer_layout = layout; 3 ( 0.00%) 'descend_newtypes: while !fat_pointer_layout.ty.is_unsafe_ptr() . && !fat_pointer_layout.ty.is_region_ptr() . { . for i in 0..fat_pointer_layout.fields.count() { . let field_layout = fat_pointer_layout.field(cx, i); . . if !field_layout.is_zst() { . fat_pointer_layout = field_layout; . continue 'descend_newtypes; -- line 3272 ---------------------------------------- -- line 3286 ---------------------------------------- . . TyAndLayout { . ty: fat_pointer_ty, . . // NOTE(eddyb) using an empty `ParamEnv`, and `unwrap`-ing the `Result` . // should always work because the type is always `*mut ()`. . ..tcx.layout_of(ty::ParamEnv::reveal_all().and(unit_ptr_ty)).unwrap() . } 9 ( 0.00%) } 756,607 ( 0.02%) -------------------------------------------------------------------------------- The following files chosen for auto-annotation could not be found: -------------------------------------------------------------------------------- ./elf/dl-lookup.c ./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 -------------------------------------------------------------------------------- 562,955,151 (11.41%) events annotated