Skip to content

Commit

Permalink
clean up potential_query_instability with FxIndexMap and UnordMap
Browse files Browse the repository at this point in the history
  • Loading branch information
chenyukang committed Feb 11, 2024
1 parent 9aa232e commit 99853c7
Show file tree
Hide file tree
Showing 14 changed files with 51 additions and 56 deletions.
7 changes: 1 addition & 6 deletions compiler/rustc_borrowck/src/region_infer/values.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::fx::FxIndexSet;
use rustc_index::bit_set::SparseBitMatrix;
use rustc_index::interval::IntervalSet;
Expand Down Expand Up @@ -42,7 +41,7 @@ pub(crate) struct LivenessValues {

/// Which regions are live. This is exclusive with the fine-grained tracking in `points`, and
/// currently only used for validating promoteds (which don't care about more precise tracking).
live_regions: Option<FxHashSet<RegionVid>>,
live_regions: Option<FxIndexSet<RegionVid>>,

/// For each region: the points where it is live.
///
Expand Down Expand Up @@ -104,10 +103,6 @@ impl LivenessValues {
self.points.as_ref().expect("use with_specific_points").rows()
}

/// Iterate through each region that has a value in this set.
// We are passing query instability implications to the caller.
#[rustc_lint_query_instability]
#[allow(rustc::potential_query_instability)]
pub(crate) fn live_regions_unordered(&self) -> impl Iterator<Item = RegionVid> + '_ {
self.live_regions.as_ref().unwrap().iter().copied()
}
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_borrowck/src/type_check/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -599,7 +599,6 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
//
// add_location doesn't care about ordering so not a problem for the live regions to be
// unordered.
#[allow(rustc::potential_query_instability)]
for region in liveness_constraints.live_regions_unordered() {
self.cx
.borrowck_context
Expand Down
5 changes: 2 additions & 3 deletions compiler/rustc_borrowck/src/universal_regions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
#![allow(rustc::diagnostic_outside_of_impl)]
#![allow(rustc::untranslatable_diagnostic)]

use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::fx::FxIndexMap;
use rustc_errors::Diagnostic;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::lang_items::LangItem;
Expand Down Expand Up @@ -180,7 +180,7 @@ struct UniversalRegionIndices<'tcx> {
/// basically equivalent to an `GenericArgs`, except that it also
/// contains an entry for `ReStatic` -- it might be nice to just
/// use an args, and then handle `ReStatic` another way.
indices: FxHashMap<ty::Region<'tcx>, RegionVid>,
indices: FxIndexMap<ty::Region<'tcx>, RegionVid>,

/// The vid assigned to `'static`. Used only for diagnostics.
pub fr_static: RegionVid,
Expand Down Expand Up @@ -327,7 +327,6 @@ impl<'tcx> UniversalRegions<'tcx> {
/// Gets an iterator over all the early-bound regions that have names.
/// Iteration order may be unstable, so this should only be used when
/// iteration order doesn't affect anything
#[allow(rustc::potential_query_instability)]
pub fn named_universal_regions<'s>(
&'s self,
) -> impl Iterator<Item = (ty::Region<'tcx>, ty::RegionVid)> + 's {
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_codegen_llvm/src/back/lto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use rustc_codegen_ssa::traits::*;
use rustc_codegen_ssa::{looks_like_rust_object_file, ModuleCodegen, ModuleKind};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::memmap::Mmap;
use rustc_data_structures::unord::UnordMap;
use rustc_errors::{DiagCtxt, FatalError};
use rustc_hir::def_id::LOCAL_CRATE;
use rustc_middle::bug;
Expand Down Expand Up @@ -787,7 +788,7 @@ pub unsafe fn optimize_thin_module(
#[derive(Debug, Default)]
pub struct ThinLTOKeysMap {
// key = llvm name of importing module, value = LLVM cache key
keys: FxHashMap<String, String>,
keys: UnordMap<String, String>,
}

impl ThinLTOKeysMap {
Expand All @@ -797,16 +798,15 @@ impl ThinLTOKeysMap {
let mut writer = io::BufWriter::new(file);
// The entries are loaded back into a hash map in `load_from_file()`, so
// the order in which we write them to file here does not matter.
#[allow(rustc::potential_query_instability)]
for (module, key) in &self.keys {
for (module, key) in self.keys.items().into_sorted_stable_ord() {
writeln!(writer, "{module} {key}")?;
}
Ok(())
}

fn load_from_file(path: &Path) -> io::Result<Self> {
use std::io::BufRead;
let mut keys = FxHashMap::default();
let mut keys = UnordMap::default();
let file = File::open(path)?;
for line in io::BufReader::new(file).lines() {
let line = line?;
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,6 @@ fn codegenned_and_inlined_items(tcx: TyCtxt<'_>) -> DefIdSet {
let mut result = items.clone();

for cgu in cgus {
#[allow(rustc::potential_query_instability)]
for item in cgu.items().keys() {
if let mir::mono::MonoItem::Fn(ref instance) = item {
let did = instance.def_id();
Expand Down
10 changes: 4 additions & 6 deletions compiler/rustc_codegen_ssa/src/assert_module_sources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
use crate::errors;
use rustc_ast as ast;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::unord::UnordMap;
use rustc_data_structures::unord::UnordSet;
use rustc_errors::{DiagnosticArgValue, IntoDiagnosticArg};
use rustc_hir::def_id::LOCAL_CRATE;
Expand Down Expand Up @@ -218,8 +218,8 @@ pub enum ComparisonKind {
}

struct TrackerData {
actual_reuse: FxHashMap<String, CguReuse>,
expected_reuse: FxHashMap<String, (String, Span, CguReuse, ComparisonKind)>,
actual_reuse: UnordMap<String, CguReuse>,
expected_reuse: UnordMap<String, (String, Span, CguReuse, ComparisonKind)>,
}

pub struct CguReuseTracker {
Expand Down Expand Up @@ -267,9 +267,7 @@ impl CguReuseTracker {

fn check_expected_reuse(&self, sess: &Session) {
if let Some(ref data) = self.data {
#[allow(rustc::potential_query_instability)]
let mut keys = data.expected_reuse.keys().collect::<Vec<_>>();
keys.sort_unstable();
let keys = data.expected_reuse.keys().into_sorted_stable_ord();
for cgu_name in keys {
let &(ref cgu_user_name, ref error_span, expected_reuse, comparison_kind) =
data.expected_reuse.get(cgu_name).unwrap();
Expand Down
9 changes: 5 additions & 4 deletions compiler/rustc_codegen_ssa/src/back/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -682,13 +682,14 @@ fn link_dwarf_object<'a>(
}

// Input rlibs contain .o/.dwo files from dependencies.
#[allow(rustc::potential_query_instability)]
let input_rlibs = cg_results
.crate_info
.used_crate_source
.values()
.filter_map(|csource| csource.rlib.as_ref())
.map(|(path, _)| path);
.items()
.filter_map(|(_, csource)| csource.rlib.as_ref())
.map(|(path, _)| path)
.into_sorted_stable_ord();

for input_rlib in input_rlibs {
debug!(?input_rlib);
package.add_input_object(input_rlib)?;
Expand Down
11 changes: 5 additions & 6 deletions compiler/rustc_codegen_ssa/src/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use rustc_attr as attr;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};
use rustc_data_structures::sync::par_map;
use rustc_data_structures::unord::UnordMap;
use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LOCAL_CRATE};
use rustc_hir::lang_items::LangItem;
Expand Down Expand Up @@ -851,6 +852,8 @@ impl CrateInfo {
// `compiler_builtins` are always placed last to ensure that they're linked correctly.
used_crates.extend(compiler_builtins);

let crates = tcx.crates(());
let n_crates = crates.len();
let mut info = CrateInfo {
target_cpu,
crate_types,
Expand All @@ -862,19 +865,15 @@ impl CrateInfo {
is_no_builtins: Default::default(),
native_libraries: Default::default(),
used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
crate_name: Default::default(),
crate_name: UnordMap::with_capacity(n_crates),
used_crates,
used_crate_source: Default::default(),
used_crate_source: UnordMap::with_capacity(n_crates),
dependency_formats: tcx.dependency_formats(()).clone(),
windows_subsystem,
natvis_debugger_visualizers: Default::default(),
};
let crates = tcx.crates(());

let n_crates = crates.len();
info.native_libraries.reserve(n_crates);
info.crate_name.reserve(n_crates);
info.used_crate_source.reserve(n_crates);

for &cnum in crates.iter() {
info.native_libraries
Expand Down
7 changes: 4 additions & 3 deletions compiler/rustc_codegen_ssa/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ extern crate rustc_middle;
use rustc_ast as ast;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::sync::Lrc;
use rustc_data_structures::unord::UnordMap;
use rustc_hir::def_id::CrateNum;
use rustc_middle::dep_graph::WorkProduct;
use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
Expand Down Expand Up @@ -152,16 +153,16 @@ impl From<&cstore::NativeLib> for NativeLib {
pub struct CrateInfo {
pub target_cpu: String,
pub crate_types: Vec<CrateType>,
pub exported_symbols: FxHashMap<CrateType, Vec<String>>,
pub exported_symbols: UnordMap<CrateType, Vec<String>>,
pub linked_symbols: FxHashMap<CrateType, Vec<(String, SymbolExportKind)>>,
pub local_crate_name: Symbol,
pub compiler_builtins: Option<CrateNum>,
pub profiler_runtime: Option<CrateNum>,
pub is_no_builtins: FxHashSet<CrateNum>,
pub native_libraries: FxHashMap<CrateNum, Vec<NativeLib>>,
pub crate_name: FxHashMap<CrateNum, Symbol>,
pub crate_name: UnordMap<CrateNum, Symbol>,
pub used_libraries: Vec<NativeLib>,
pub used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
pub used_crate_source: UnordMap<CrateNum, Lrc<CrateSource>>,
pub used_crates: Vec<CrateNum>,
pub dependency_formats: Lrc<Dependencies>,
pub windows_subsystem: Option<String>,
Expand Down
5 changes: 5 additions & 0 deletions compiler/rustc_data_structures/src/unord.rs
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,11 @@ impl<K: Eq + Hash, V> UnordMap<K, V> {
UnordItems(self.inner.into_iter())
}

#[inline]
pub fn keys(&self) -> UnordItems<&K, impl Iterator<Item = &K>> {
UnordItems(self.inner.keys())
}

/// Returns the entries of this map in stable sort order (as defined by `ToStableHashKey`).
///
/// The `cache_sort_key` parameter controls if [slice::sort_by_cached_key] or
Expand Down
12 changes: 5 additions & 7 deletions compiler/rustc_hir_typeck/src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use crate::{
use rustc_ast as ast;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_data_structures::unord::UnordMap;
use rustc_errors::{
codes::*, pluralize, struct_span_code_err, AddToDiagnostic, Applicability, Diagnostic,
DiagnosticBuilder, ErrCode, ErrorGuaranteed, StashKey,
Expand Down Expand Up @@ -1716,7 +1717,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.fields
.iter_enumerated()
.map(|(i, field)| (field.ident(tcx).normalize_to_macros_2_0(), (i, field)))
.collect::<FxHashMap<_, _>>();
.collect::<UnordMap<_, _>>();

let mut seen_fields = FxHashMap::default();

Expand Down Expand Up @@ -1960,18 +1961,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&self,
adt_ty: Ty<'tcx>,
span: Span,
remaining_fields: FxHashMap<Ident, (FieldIdx, &ty::FieldDef)>,
remaining_fields: UnordMap<Ident, (FieldIdx, &ty::FieldDef)>,
variant: &'tcx ty::VariantDef,
ast_fields: &'tcx [hir::ExprField<'tcx>],
args: GenericArgsRef<'tcx>,
) {
let len = remaining_fields.len();

#[allow(rustc::potential_query_instability)]
let mut displayable_field_names: Vec<&str> =
remaining_fields.keys().map(|ident| ident.as_str()).collect();
// sorting &str primitives here, sort_unstable is ok
displayable_field_names.sort_unstable();
let displayable_field_names: Vec<&str> =
remaining_fields.items().map(|(ident, _)| ident.as_str()).into_sorted_stable_ord();

let mut truncated_fields_error = String::new();
let remaining_fields_names = match &displayable_field_names[..] {
Expand Down
20 changes: 10 additions & 10 deletions compiler/rustc_lint/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@ use self::TargetLint::*;

use crate::levels::LintLevelsBuilder;
use crate::passes::{EarlyLintPassObject, LateLintPassObject};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::fx::FxIndexMap;
use rustc_data_structures::sync;
use rustc_data_structures::unord::UnordMap;
use rustc_errors::{DecorateLint, DiagnosticBuilder, DiagnosticMessage, MultiSpan};
use rustc_feature::Features;
use rustc_hir as hir;
Expand Down Expand Up @@ -69,10 +70,10 @@ pub struct LintStore {
pub late_module_passes: Vec<Box<LateLintPassFactory>>,

/// Lints indexed by name.
by_name: FxHashMap<String, TargetLint>,
by_name: UnordMap<String, TargetLint>,

/// Map of registered lint groups to what lints they expand to.
lint_groups: FxHashMap<&'static str, LintGroup>,
lint_groups: FxIndexMap<&'static str, LintGroup>,
}

impl LintStoreMarker for LintStore {}
Expand Down Expand Up @@ -326,9 +327,11 @@ impl LintStore {

/// True if this symbol represents a lint group name.
pub fn is_lint_group(&self, lint_name: Symbol) -> bool {
#[allow(rustc::potential_query_instability)]
let lint_groups = self.lint_groups.keys().collect::<Vec<_>>();
debug!("is_lint_group(lint_name={:?}, lint_groups={:?})", lint_name, lint_groups);
debug!(
"is_lint_group(lint_name={:?}, lint_groups={:?})",
lint_name,
self.lint_groups.keys().collect::<Vec<_>>()
);
let lint_name_str = lint_name.as_str();
self.lint_groups.contains_key(lint_name_str) || {
let warnings_name_str = crate::WARNINGS.name_lower();
Expand Down Expand Up @@ -372,12 +375,9 @@ impl LintStore {
None => {
// 1. The tool is currently running, so this lint really doesn't exist.
// FIXME: should this handle tools that never register a lint, like rustfmt?
#[allow(rustc::potential_query_instability)]
let lints = self.by_name.keys().collect::<Vec<_>>();
debug!("lints={:?}", lints);
debug!("lints={:?}", self.by_name.keys().into_sorted_stable_ord());
let tool_prefix = format!("{tool_name}::");

#[allow(rustc::potential_query_instability)]
return if self.by_name.keys().any(|lint| lint.starts_with(&tool_prefix)) {
self.no_lint_suggestion(&complete_name, tool_name.as_str())
} else {
Expand Down
7 changes: 4 additions & 3 deletions compiler/rustc_middle/src/mir/mono.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use rustc_attr::InlineAttr;
use rustc_data_structures::base_n;
use rustc_data_structures::fingerprint::Fingerprint;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::fx::FxIndexMap;
use rustc_data_structures::stable_hasher::{Hash128, HashStable, StableHasher};
use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
use rustc_hir::ItemId;
Expand Down Expand Up @@ -241,7 +242,7 @@ pub struct CodegenUnit<'tcx> {
/// contain something unique to this crate (e.g., a module path)
/// as well as the crate name and disambiguator.
name: Symbol,
items: FxHashMap<MonoItem<'tcx>, MonoItemData>,
items: FxIndexMap<MonoItem<'tcx>, MonoItemData>,
size_estimate: usize,
primary: bool,
/// True if this is CGU is used to hold code coverage information for dead code,
Expand Down Expand Up @@ -317,12 +318,12 @@ impl<'tcx> CodegenUnit<'tcx> {
}

/// The order of these items is non-determinstic.
pub fn items(&self) -> &FxHashMap<MonoItem<'tcx>, MonoItemData> {
pub fn items(&self) -> &FxIndexMap<MonoItem<'tcx>, MonoItemData> {
&self.items
}

/// The order of these items is non-determinstic.
pub fn items_mut(&mut self) -> &mut FxHashMap<MonoItem<'tcx>, MonoItemData> {
pub fn items_mut(&mut self) -> &mut FxIndexMap<MonoItem<'tcx>, MonoItemData> {
&mut self.items
}

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_monomorphize/src/partitioning.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ fn merge_codegen_units<'tcx>(
// Move the items from `cgu_src` to `cgu_dst`. Some of them may be
// duplicate inlined items, in which case the destination CGU is
// unaffected. Recalculate size estimates afterwards.
cgu_dst.items_mut().extend(cgu_src.items_mut().drain());
cgu_dst.items_mut().extend(cgu_src.items_mut().drain(..));
cgu_dst.compute_size_estimate();

// Record that `cgu_dst` now contains all the stuff that was in
Expand Down Expand Up @@ -407,7 +407,7 @@ fn merge_codegen_units<'tcx>(
// Move the items from `smallest` to `second_smallest`. Some of them
// may be duplicate inlined items, in which case the destination CGU is
// unaffected. Recalculate size estimates afterwards.
second_smallest.items_mut().extend(smallest.items_mut().drain());
second_smallest.items_mut().extend(smallest.items_mut().drain(..));
second_smallest.compute_size_estimate();

// Don't update `cgu_contents`, that's only for incremental builds.
Expand Down

0 comments on commit 99853c7

Please sign in to comment.