about summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--src/librustc_codegen_llvm/callee.rs2
-rw-r--r--src/librustc_codegen_llvm/consts.rs4
-rw-r--r--src/librustc_codegen_ssa/back/symbol_export.rs4
-rw-r--r--src/librustc_hir/definitions.rs8
-rw-r--r--src/librustc_infer/infer/error_reporting/mod.rs5
-rw-r--r--src/librustc_infer/infer/error_reporting/nice_region_error/find_anon_type.rs4
-rw-r--r--src/librustc_infer/infer/error_reporting/nice_region_error/outlives_closure.rs4
-rw-r--r--src/librustc_infer/infer/error_reporting/nice_region_error/util.rs2
-rw-r--r--src/librustc_lint/builtin.rs11
-rw-r--r--src/librustc_lint/late.rs6
-rw-r--r--src/librustc_lint/lib.rs6
-rw-r--r--src/librustc_metadata/rmeta/encoder.rs16
-rw-r--r--src/librustc_middle/dep_graph/mod.rs8
-rw-r--r--src/librustc_middle/hir/map/mod.rs20
-rw-r--r--src/librustc_middle/hir/mod.rs4
-rw-r--r--src/librustc_middle/middle/region.rs4
-rw-r--r--src/librustc_middle/mir/mod.rs10
-rw-r--r--src/librustc_middle/mir/mono.rs16
-rw-r--r--src/librustc_middle/query/mod.rs2
-rw-r--r--src/librustc_middle/ty/context.rs5
-rw-r--r--src/librustc_middle/ty/mod.rs18
-rw-r--r--src/librustc_middle/ty/print/pretty.rs8
-rw-r--r--src/librustc_middle/ty/sty.rs2
-rw-r--r--src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs10
-rw-r--r--src/librustc_mir/borrow_check/diagnostics/mod.rs6
-rw-r--r--src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs4
-rw-r--r--src/librustc_mir/borrow_check/diagnostics/region_name.rs10
-rw-r--r--src/librustc_mir/borrow_check/mod.rs37
-rw-r--r--src/librustc_mir/borrow_check/nll.rs2
-rw-r--r--src/librustc_mir/borrow_check/type_check/mod.rs2
-rw-r--r--src/librustc_mir/borrow_check/universal_regions.rs7
-rw-r--r--src/librustc_mir/const_eval/eval_queries.rs4
-rw-r--r--src/librustc_mir/const_eval/fn_queries.rs3
-rw-r--r--src/librustc_mir/monomorphize/collector.rs4
-rw-r--r--src/librustc_mir/transform/check_consts/mod.rs10
-rw-r--r--src/librustc_mir/transform/check_consts/validation.rs2
-rw-r--r--src/librustc_mir/transform/check_unsafety.rs21
-rw-r--r--src/librustc_mir/transform/const_prop.rs5
-rw-r--r--src/librustc_mir/transform/inline.rs10
-rw-r--r--src/librustc_mir/transform/mod.rs2
-rw-r--r--src/librustc_mir/transform/promote_consts.rs2
-rw-r--r--src/librustc_mir/transform/qualify_min_const_fn.rs2
-rw-r--r--src/librustc_mir/util/liveness.rs2
-rw-r--r--src/librustc_mir_build/build/mod.rs6
-rw-r--r--src/librustc_mir_build/hair/cx/expr.rs2
-rw-r--r--src/librustc_mir_build/hair/pattern/check_match.rs4
-rw-r--r--src/librustc_mir_build/lints.rs4
-rw-r--r--src/librustc_passes/dead.rs13
-rw-r--r--src/librustc_passes/reachable.rs22
-rw-r--r--src/librustc_passes/region.rs2
-rw-r--r--src/librustc_passes/upvars.rs2
-rw-r--r--src/librustc_privacy/lib.rs41
-rw-r--r--src/librustc_resolve/late/lifetimes.rs27
-rw-r--r--src/librustc_symbol_mangling/lib.rs16
-rw-r--r--src/librustc_trait_selection/opaque_types.rs26
-rw-r--r--src/librustc_trait_selection/traits/error_reporting/mod.rs3
-rw-r--r--src/librustc_trait_selection/traits/error_reporting/suggestions.rs10
-rw-r--r--src/librustc_trait_selection/traits/specialize/mod.rs27
-rw-r--r--src/librustc_traits/lowering/environment.rs2
-rw-r--r--src/librustc_ty/ty.rs20
-rw-r--r--src/librustc_typeck/astconv.rs21
-rw-r--r--src/librustc_typeck/check/coercion.rs2
-rw-r--r--src/librustc_typeck/check/compare_method.rs84
-rw-r--r--src/librustc_typeck/check/dropck.rs21
-rw-r--r--src/librustc_typeck/check/expr.rs4
-rw-r--r--src/librustc_typeck/check/method/suggest.rs124
-rw-r--r--src/librustc_typeck/check/mod.rs34
-rw-r--r--src/librustc_typeck/check/wfcheck.rs14
-rw-r--r--src/librustc_typeck/check/writeback.rs2
-rw-r--r--src/librustc_typeck/check_unused.rs4
-rw-r--r--src/librustc_typeck/coherence/builtin.rs11
-rw-r--r--src/librustc_typeck/collect.rs39
-rw-r--r--src/librustc_typeck/collect/type_of.rs12
-rw-r--r--src/librustc_typeck/impl_wf_check/min_specialization.rs13
-rw-r--r--src/librustc_typeck/lib.rs10
-rw-r--r--src/librustc_typeck/outlives/implicit_infer.rs8
-rw-r--r--src/librustc_typeck/outlives/mod.rs2
-rw-r--r--src/librustc_typeck/variance/constraints.rs12
-rw-r--r--src/librustc_typeck/variance/mod.rs2
-rw-r--r--src/librustc_typeck/variance/terms.rs4
-rw-r--r--src/librustdoc/clean/inline.rs31
-rw-r--r--src/librustdoc/clean/mod.rs12
-rw-r--r--src/librustdoc/clean/utils.rs4
-rw-r--r--src/librustdoc/core.rs2
-rw-r--r--src/librustdoc/passes/collect_intra_doc_links.rs6
-rw-r--r--src/librustdoc/visit_ast.rs4
86 files changed, 579 insertions, 444 deletions
diff --git a/src/librustc_codegen_llvm/callee.rs b/src/librustc_codegen_llvm/callee.rs
index 9db5c40c8e3..6ad75cff3dd 100644
--- a/src/librustc_codegen_llvm/callee.rs
+++ b/src/librustc_codegen_llvm/callee.rs
@@ -116,7 +116,7 @@ pub fn get_fn(cx: &CodegenCx<'ll, 'tcx>, instance: Instance<'tcx>) -> &'ll Value
                 if cx.tcx.sess.opts.share_generics() {
                     // We are in share_generics mode.
 
-                    if instance_def_id.is_local() {
+                    if let Some(instance_def_id) = instance_def_id.as_local() {
                         // This is a definition from the current crate. If the
                         // definition is unreachable for downstream crates or
                         // the current crate does not re-export generics, the
diff --git a/src/librustc_codegen_llvm/consts.rs b/src/librustc_codegen_llvm/consts.rs
index 9fd22c8b07b..ac2f47a740d 100644
--- a/src/librustc_codegen_llvm/consts.rs
+++ b/src/librustc_codegen_llvm/consts.rs
@@ -209,7 +209,9 @@ impl CodegenCx<'ll, 'tcx> {
 
         debug!("get_static: sym={} instance={:?}", sym, instance);
 
-        let g = if let Some(id) = self.tcx.hir().as_local_hir_id(def_id) {
+        let g = if let Some(id) =
+            def_id.as_local().map(|def_id| self.tcx.hir().as_local_hir_id(def_id).unwrap())
+        {
             let llty = self.layout_of(ty).llvm_type(self);
             let (g, attrs) = match self.tcx.hir().get(id) {
                 Node::Item(&hir::Item { attrs, span, kind: hir::ItemKind::Static(..), .. }) => {
diff --git a/src/librustc_codegen_ssa/back/symbol_export.rs b/src/librustc_codegen_ssa/back/symbol_export.rs
index 38a5f8d6d71..5970059bb4c 100644
--- a/src/librustc_codegen_ssa/back/symbol_export.rs
+++ b/src/librustc_codegen_ssa/back/symbol_export.rs
@@ -361,8 +361,8 @@ fn upstream_drop_glue_for_provider<'tcx>(
 }
 
 fn is_unreachable_local_definition_provider(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
-    if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
-        !tcx.reachable_set(LOCAL_CRATE).contains(&hir_id)
+    if let Some(def_id) = def_id.as_local() {
+        !tcx.reachable_set(LOCAL_CRATE).contains(&tcx.hir().as_local_hir_id(def_id).unwrap())
     } else {
         bug!("is_unreachable_local_definition called with non-local DefId: {:?}", def_id)
     }
diff --git a/src/librustc_hir/definitions.rs b/src/librustc_hir/definitions.rs
index 1ac23677d47..8927814ee04 100644
--- a/src/librustc_hir/definitions.rs
+++ b/src/librustc_hir/definitions.rs
@@ -342,12 +342,8 @@ impl Definitions {
     }
 
     #[inline]
-    pub fn as_local_hir_id(&self, def_id: DefId) -> Option<hir::HirId> {
-        if let Some(def_id) = def_id.as_local() {
-            Some(self.local_def_id_to_hir_id(def_id))
-        } else {
-            None
-        }
+    pub fn as_local_hir_id(&self, def_id: LocalDefId) -> Option<hir::HirId> {
+        Some(self.local_def_id_to_hir_id(def_id))
     }
 
     #[inline]
diff --git a/src/librustc_infer/infer/error_reporting/mod.rs b/src/librustc_infer/infer/error_reporting/mod.rs
index 6ae2bd33901..7d8924718bb 100644
--- a/src/librustc_infer/infer/error_reporting/mod.rs
+++ b/src/librustc_infer/infer/error_reporting/mod.rs
@@ -191,7 +191,7 @@ fn msg_span_from_early_bound_and_free_regions(
     let sm = tcx.sess.source_map();
 
     let scope = region.free_region_binding_scope(tcx);
-    let node = tcx.hir().as_local_hir_id(scope).unwrap();
+    let node = tcx.hir().as_local_hir_id(scope.expect_local()).unwrap();
     let tag = match tcx.hir().find(node) {
         Some(Node::Block(_) | Node::Expr(_)) => "body",
         Some(Node::Item(it)) => item_scope_tag(&it),
@@ -1782,10 +1782,11 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
                     if !(generics.has_self && param.index == 0) {
                         let type_param = generics.type_param(param, self.tcx);
                         let hir = &self.tcx.hir();
-                        hir.as_local_hir_id(type_param.def_id).map(|id| {
+                        type_param.def_id.as_local().map(|def_id| {
                             // Get the `hir::Param` to verify whether it already has any bounds.
                             // We do this to avoid suggesting code that ends up as `T: 'a'b`,
                             // instead we suggest `T: 'a + 'b` in that case.
+                            let id = hir.as_local_hir_id(def_id).unwrap();
                             let mut has_bounds = false;
                             if let Node::GenericParam(param) = hir.get(id) {
                                 has_bounds = !param.bounds.is_empty();
diff --git a/src/librustc_infer/infer/error_reporting/nice_region_error/find_anon_type.rs b/src/librustc_infer/infer/error_reporting/nice_region_error/find_anon_type.rs
index 448ce373498..d0141dc062a 100644
--- a/src/librustc_infer/infer/error_reporting/nice_region_error/find_anon_type.rs
+++ b/src/librustc_infer/infer/error_reporting/nice_region_error/find_anon_type.rs
@@ -29,7 +29,9 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
     ) -> Option<(&hir::Ty<'_>, &hir::FnDecl<'_>)> {
         if let Some(anon_reg) = self.tcx().is_suitable_region(region) {
             let def_id = anon_reg.def_id;
-            if let Some(hir_id) = self.tcx().hir().as_local_hir_id(def_id) {
+            if let Some(hir_id) =
+                def_id.as_local().map(|def_id| self.tcx().hir().as_local_hir_id(def_id).unwrap())
+            {
                 let fndecl = match self.tcx().hir().get(hir_id) {
                     Node::Item(&hir::Item { kind: hir::ItemKind::Fn(ref m, ..), .. })
                     | Node::TraitItem(&hir::TraitItem {
diff --git a/src/librustc_infer/infer/error_reporting/nice_region_error/outlives_closure.rs b/src/librustc_infer/infer/error_reporting/nice_region_error/outlives_closure.rs
index 70c30271043..6bf60db0094 100644
--- a/src/librustc_infer/infer/error_reporting/nice_region_error/outlives_closure.rs
+++ b/src/librustc_infer/infer/error_reporting/nice_region_error/outlives_closure.rs
@@ -46,7 +46,9 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
             ) = (&sub_origin, sup_region)
             {
                 let hir = &self.tcx().hir();
-                if let Some(hir_id) = hir.as_local_hir_id(free_region.scope) {
+                if let Some(hir_id) =
+                    free_region.scope.as_local().map(|def_id| hir.as_local_hir_id(def_id).unwrap())
+                {
                     if let Node::Expr(Expr { kind: Closure(_, _, _, closure_span, None), .. }) =
                         hir.get(hir_id)
                     {
diff --git a/src/librustc_infer/infer/error_reporting/nice_region_error/util.rs b/src/librustc_infer/infer/error_reporting/nice_region_error/util.rs
index 7bbd2127bcf..ab74513a675 100644
--- a/src/librustc_infer/infer/error_reporting/nice_region_error/util.rs
+++ b/src/librustc_infer/infer/error_reporting/nice_region_error/util.rs
@@ -51,7 +51,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
         };
 
         let hir = &self.tcx().hir();
-        let hir_id = hir.as_local_hir_id(id)?;
+        let hir_id = hir.as_local_hir_id(id.as_local()?)?;
         let body_id = hir.maybe_body_owned_by(hir_id)?;
         let body = hir.body(body_id);
         let owner_id = hir.body_owner(body_id);
diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs
index 0fba510e101..4040545db96 100644
--- a/src/librustc_lint/builtin.rs
+++ b/src/librustc_lint/builtin.rs
@@ -436,7 +436,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
                 // If the trait is private, add the impl items to `private_traits` so they don't get
                 // reported for missing docs.
                 let real_trait = trait_ref.path.res.def_id();
-                if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(real_trait) {
+                if let Some(hir_id) = real_trait
+                    .as_local()
+                    .map(|def_id| cx.tcx.hir().as_local_hir_id(def_id).unwrap())
+                {
                     if let Some(Node::Item(item)) = cx.tcx.hir().find(hir_id) {
                         if let hir::VisibilityKind::Inherited = item.vis.node {
                             for impl_item_ref in items {
@@ -609,7 +612,11 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
             let mut impls = HirIdSet::default();
             cx.tcx.for_each_impl(debug, |d| {
                 if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() {
-                    if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(ty_def.did) {
+                    if let Some(hir_id) = ty_def
+                        .did
+                        .as_local()
+                        .map(|def_id| cx.tcx.hir().as_local_hir_id(def_id).unwrap())
+                    {
                         impls.insert(hir_id);
                     }
                 }
diff --git a/src/librustc_lint/late.rs b/src/librustc_lint/late.rs
index 1999a8ec5f6..0a0505e89d4 100644
--- a/src/librustc_lint/late.rs
+++ b/src/librustc_lint/late.rs
@@ -19,7 +19,7 @@ use rustc_ast::ast;
 use rustc_ast::walk_list;
 use rustc_data_structures::sync::{join, par_iter, ParallelIterator};
 use rustc_hir as hir;
-use rustc_hir::def_id::{DefId, LOCAL_CRATE};
+use rustc_hir::def_id::{LocalDefId, LOCAL_CRATE};
 use rustc_hir::intravisit as hir_visit;
 use rustc_hir::intravisit::Visitor;
 use rustc_middle::hir::map::Map;
@@ -353,7 +353,7 @@ crate::late_lint_methods!(late_lint_pass_impl, [], ['tcx]);
 
 fn late_lint_mod_pass<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(
     tcx: TyCtxt<'tcx>,
-    module_def_id: DefId,
+    module_def_id: LocalDefId,
     pass: T,
 ) {
     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
@@ -382,7 +382,7 @@ fn late_lint_mod_pass<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(
 
 pub fn late_lint_mod<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(
     tcx: TyCtxt<'tcx>,
-    module_def_id: DefId,
+    module_def_id: LocalDefId,
     builtin_lints: T,
 ) {
     if tcx.sess.opts.debugging_opts.no_interleave_lints {
diff --git a/src/librustc_lint/lib.rs b/src/librustc_lint/lib.rs
index bcd59702289..1041ad01866 100644
--- a/src/librustc_lint/lib.rs
+++ b/src/librustc_lint/lib.rs
@@ -91,7 +91,11 @@ pub fn provide(providers: &mut Providers<'_>) {
 }
 
 fn lint_mod(tcx: TyCtxt<'_>, module_def_id: DefId) {
-    late::late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new());
+    late::late_lint_mod(
+        tcx,
+        module_def_id.expect_local(),
+        BuiltinCombinedModuleLateLintPass::new(),
+    );
 }
 
 macro_rules! pre_expansion_lint_passes {
diff --git a/src/librustc_metadata/rmeta/encoder.rs b/src/librustc_metadata/rmeta/encoder.rs
index ab5a6a798a5..7abd454a6f3 100644
--- a/src/librustc_metadata/rmeta/encoder.rs
+++ b/src/librustc_metadata/rmeta/encoder.rs
@@ -617,7 +617,7 @@ impl EncodeContext<'tcx> {
             ctor: variant.ctor_def_id.map(|did| did.index),
         };
 
-        let enum_id = tcx.hir().as_local_hir_id(def.did).unwrap();
+        let enum_id = tcx.hir().as_local_hir_id(def.did.expect_local()).unwrap();
         let enum_vis = &tcx.hir().expect_item(enum_id).vis;
 
         record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
@@ -663,7 +663,7 @@ impl EncodeContext<'tcx> {
 
         // Variant constructors have the same visibility as the parent enums, unless marked as
         // non-exhaustive, in which case they are lowered to `pub(crate)`.
-        let enum_id = tcx.hir().as_local_hir_id(def.did).unwrap();
+        let enum_id = tcx.hir().as_local_hir_id(def.did.expect_local()).unwrap();
         let enum_vis = &tcx.hir().expect_item(enum_id).vis;
         let mut ctor_vis = ty::Visibility::from_hir(enum_vis, enum_id, tcx);
         if variant.is_field_list_non_exhaustive() && ctor_vis == ty::Visibility::Public {
@@ -729,7 +729,7 @@ impl EncodeContext<'tcx> {
         let def_id = field.did;
         debug!("EncodeContext::encode_field({:?})", def_id);
 
-        let variant_id = tcx.hir().as_local_hir_id(variant.def_id).unwrap();
+        let variant_id = tcx.hir().as_local_hir_id(variant.def_id.expect_local()).unwrap();
         let variant_data = tcx.hir().expect_variant_data(variant_id);
 
         record!(self.tables.kind[def_id] <- EntryKind::Field);
@@ -756,7 +756,7 @@ impl EncodeContext<'tcx> {
             ctor: Some(def_id.index),
         };
 
-        let struct_id = tcx.hir().as_local_hir_id(adt_def.did).unwrap();
+        let struct_id = tcx.hir().as_local_hir_id(adt_def.did.expect_local()).unwrap();
         let struct_vis = &tcx.hir().expect_item(struct_id).vis;
         let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
         for field in &variant.fields {
@@ -818,7 +818,7 @@ impl EncodeContext<'tcx> {
         debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
         let tcx = self.tcx;
 
-        let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+        let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
         let ast_item = tcx.hir().expect_trait_item(hir_id);
         let trait_item = tcx.associated_item(def_id);
 
@@ -909,7 +909,7 @@ impl EncodeContext<'tcx> {
         debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
         let tcx = self.tcx;
 
-        let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
+        let hir_id = self.tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
         let ast_item = self.tcx.hir().expect_impl_item(hir_id);
         let impl_item = self.tcx.associated_item(def_id);
 
@@ -1309,7 +1309,6 @@ impl EncodeContext<'tcx> {
     }
 
     fn encode_info_for_closure(&mut self, def_id: LocalDefId) {
-        let def_id = def_id.to_def_id();
         debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
 
         // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
@@ -1317,6 +1316,7 @@ impl EncodeContext<'tcx> {
         let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
         let ty = self.tcx.typeck_tables_of(def_id).node_type(hir_id);
 
+        let def_id = def_id.to_def_id();
         record!(self.tables.kind[def_id] <- match ty.kind {
             ty::Generator(..) => {
                 let data = self.tcx.generator_kind(def_id).unwrap();
@@ -1340,11 +1340,11 @@ impl EncodeContext<'tcx> {
     }
 
     fn encode_info_for_anon_const(&mut self, def_id: LocalDefId) {
-        let def_id = def_id.to_def_id();
         debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
         let id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
         let body_id = self.tcx.hir().body_owned_by(id);
         let const_data = self.encode_rendered_const_for_body(body_id);
+        let def_id = def_id.to_def_id();
         let qualifs = self.tcx.mir_const_qualif(def_id);
 
         record!(self.tables.kind[def_id] <- EntryKind::Const(qualifs, const_data));
diff --git a/src/librustc_middle/dep_graph/mod.rs b/src/librustc_middle/dep_graph/mod.rs
index f56df19bfb0..0aca0f6e5b7 100644
--- a/src/librustc_middle/dep_graph/mod.rs
+++ b/src/librustc_middle/dep_graph/mod.rs
@@ -5,7 +5,7 @@ use rustc_data_structures::profiling::SelfProfilerRef;
 use rustc_data_structures::sync::Lock;
 use rustc_data_structures::thin_vec::ThinVec;
 use rustc_errors::Diagnostic;
-use rustc_hir::def_id::DefId;
+use rustc_hir::def_id::LocalDefId;
 
 mod dep_node;
 
@@ -106,7 +106,7 @@ impl<'tcx> DepContext for TyCtxt<'tcx> {
         match dep_node.kind {
             DepKind::hir_owner | DepKind::hir_owner_nodes | DepKind::CrateMetadata => {
                 if let Some(def_id) = dep_node.extract_def_id(*self) {
-                    if def_id_corresponds_to_hir_dep_node(*self, def_id) {
+                    if def_id_corresponds_to_hir_dep_node(*self, def_id.expect_local()) {
                         if dep_node.kind == DepKind::CrateMetadata {
                             // The `DefPath` has corresponding node,
                             // and that node should have been marked
@@ -180,7 +180,7 @@ impl<'tcx> DepContext for TyCtxt<'tcx> {
     }
 }
 
-fn def_id_corresponds_to_hir_dep_node(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
+fn def_id_corresponds_to_hir_dep_node(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
-    def_id.index == hir_id.owner.local_def_index
+    def_id == hir_id.owner
 }
diff --git a/src/librustc_middle/hir/map/mod.rs b/src/librustc_middle/hir/map/mod.rs
index f18410cedf3..1dbb333708e 100644
--- a/src/librustc_middle/hir/map/mod.rs
+++ b/src/librustc_middle/hir/map/mod.rs
@@ -198,7 +198,7 @@ impl<'hir> Map<'hir> {
     }
 
     #[inline]
-    pub fn as_local_hir_id(&self, def_id: DefId) -> Option<HirId> {
+    pub fn as_local_hir_id(&self, def_id: LocalDefId) -> Option<HirId> {
         self.tcx.definitions.as_local_hir_id(def_id)
     }
 
@@ -448,7 +448,7 @@ impl<'hir> Map<'hir> {
         }
     }
 
-    pub fn get_module(&self, module: DefId) -> (&'hir Mod<'hir>, Span, HirId) {
+    pub fn get_module(&self, module: LocalDefId) -> (&'hir Mod<'hir>, Span, HirId) {
         let hir_id = self.as_local_hir_id(module).unwrap();
         match self.get_entry(hir_id).node {
             Node::Item(&Item { span, kind: ItemKind::Mod(ref m), .. }) => (m, span, hir_id),
@@ -482,7 +482,11 @@ impl<'hir> Map<'hir> {
     }
 
     pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
-        self.as_local_hir_id(id).map(|id| self.get(id))
+        if let Some(id) = id.as_local() {
+            self.as_local_hir_id(id).map(|id| self.get(id))
+        } else {
+            None
+        }
     }
 
     pub fn get_generics(&self, id: DefId) -> Option<&'hir Generics<'hir>> {
@@ -883,7 +887,11 @@ impl<'hir> Map<'hir> {
     }
 
     pub fn span_if_local(&self, id: DefId) -> Option<Span> {
-        self.as_local_hir_id(id).map(|id| self.span(id))
+        if let Some(id) = id.as_local() {
+            self.as_local_hir_id(id).map(|id| self.span(id))
+        } else {
+            None
+        }
     }
 
     pub fn res_span(&self, res: Res) -> Option<Span> {
@@ -1083,8 +1091,8 @@ fn hir_id_to_string(map: &Map<'_>, id: HirId) -> String {
 
 pub fn provide(providers: &mut Providers<'_>) {
     providers.def_kind = |tcx, def_id| {
-        if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
-            tcx.hir().def_kind(hir_id)
+        if let Some(def_id) = def_id.as_local() {
+            tcx.hir().def_kind(tcx.hir().as_local_hir_id(def_id).unwrap())
         } else {
             bug!("calling local def_kind query provider for upstream DefId: {:?}", def_id);
         }
diff --git a/src/librustc_middle/hir/mod.rs b/src/librustc_middle/hir/mod.rs
index 3d3d9dcf41d..c44a8b0b12e 100644
--- a/src/librustc_middle/hir/mod.rs
+++ b/src/librustc_middle/hir/mod.rs
@@ -68,13 +68,13 @@ impl<'tcx> TyCtxt<'tcx> {
 pub fn provide(providers: &mut Providers<'_>) {
     providers.parent_module_from_def_id = |tcx, id| {
         let hir = tcx.hir();
-        hir.local_def_id(hir.get_module_parent_node(hir.as_local_hir_id(id.to_def_id()).unwrap()))
+        hir.local_def_id(hir.get_module_parent_node(hir.as_local_hir_id(id).unwrap()))
     };
     providers.hir_crate = |tcx, _| tcx.untracked_crate;
     providers.index_hir = map::index_hir;
     providers.hir_module_items = |tcx, id| {
         let hir = tcx.hir();
-        let module = hir.as_local_hir_id(id.to_def_id()).unwrap();
+        let module = hir.as_local_hir_id(id).unwrap();
         &tcx.untracked_crate.modules[&module]
     };
     providers.hir_owner = |tcx, id| tcx.index_hir(LOCAL_CRATE).map[id].signature;
diff --git a/src/librustc_middle/middle/region.rs b/src/librustc_middle/middle/region.rs
index 2ad6fe14ec7..41f712f600a 100644
--- a/src/librustc_middle/middle/region.rs
+++ b/src/librustc_middle/middle/region.rs
@@ -554,7 +554,7 @@ impl<'tcx> ScopeTree {
     pub fn early_free_scope(&self, tcx: TyCtxt<'tcx>, br: &ty::EarlyBoundRegion) -> Scope {
         let param_owner = tcx.parent(br.def_id).unwrap();
 
-        let param_owner_id = tcx.hir().as_local_hir_id(param_owner).unwrap();
+        let param_owner_id = tcx.hir().as_local_hir_id(param_owner.expect_local()).unwrap();
         let scope = tcx
             .hir()
             .maybe_body_owned_by(param_owner_id)
@@ -595,7 +595,7 @@ impl<'tcx> ScopeTree {
         // on the same function that they ended up being freed in.
         assert_eq!(param_owner, fr.scope);
 
-        let param_owner_id = tcx.hir().as_local_hir_id(param_owner).unwrap();
+        let param_owner_id = tcx.hir().as_local_hir_id(param_owner.expect_local()).unwrap();
         let body_id = tcx.hir().body_owned_by(param_owner_id);
         Scope { id: tcx.hir().body(body_id).value.hir_id.local_id, data: ScopeData::CallSite }
     }
diff --git a/src/librustc_middle/mir/mod.rs b/src/librustc_middle/mir/mod.rs
index e476729c11b..96012c9e653 100644
--- a/src/librustc_middle/mir/mod.rs
+++ b/src/librustc_middle/mir/mod.rs
@@ -2338,7 +2338,10 @@ impl<'tcx> Debug for Rvalue<'tcx> {
                     }
 
                     AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| {
-                        if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
+                        if let Some(hir_id) = def_id
+                            .as_local()
+                            .map(|def_id| tcx.hir().as_local_hir_id(def_id).unwrap())
+                        {
                             let name = if tcx.sess.opts.debugging_opts.span_free_formats {
                                 let substs = tcx.lift(&substs).unwrap();
                                 format!(
@@ -2364,7 +2367,10 @@ impl<'tcx> Debug for Rvalue<'tcx> {
                     }),
 
                     AggregateKind::Generator(def_id, _, _) => ty::tls::with(|tcx| {
-                        if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
+                        if let Some(hir_id) = def_id
+                            .as_local()
+                            .map(|def_id| tcx.hir().as_local_hir_id(def_id).unwrap())
+                        {
                             let name = format!("[generator@{:?}]", tcx.hir().span(hir_id));
                             let mut struct_fmt = fmt.debug_struct(&name);
 
diff --git a/src/librustc_middle/mir/mono.rs b/src/librustc_middle/mir/mono.rs
index 0b64cb479d5..1b18060c886 100644
--- a/src/librustc_middle/mir/mono.rs
+++ b/src/librustc_middle/mir/mono.rs
@@ -197,8 +197,12 @@ impl<'tcx> MonoItem<'tcx> {
 
     pub fn local_span(&self, tcx: TyCtxt<'tcx>) -> Option<Span> {
         match *self {
-            MonoItem::Fn(Instance { def, .. }) => tcx.hir().as_local_hir_id(def.def_id()),
-            MonoItem::Static(def_id) => tcx.hir().as_local_hir_id(def_id),
+            MonoItem::Fn(Instance { def, .. }) => {
+                def.def_id().as_local().map(|def_id| tcx.hir().as_local_hir_id(def_id).unwrap())
+            }
+            MonoItem::Static(def_id) => {
+                def_id.as_local().map(|def_id| tcx.hir().as_local_hir_id(def_id).unwrap())
+            }
             MonoItem::GlobalAsm(hir_id) => Some(hir_id),
         }
         .map(|hir_id| tcx.hir().span(hir_id))
@@ -339,7 +343,9 @@ impl<'tcx> CodegenUnit<'tcx> {
                             // instances into account. The others don't matter for
                             // the codegen tests and can even make item order
                             // unstable.
-                            InstanceDef::Item(def_id) => tcx.hir().as_local_hir_id(def_id),
+                            InstanceDef::Item(def_id) => def_id
+                                .as_local()
+                                .map(|def_id| tcx.hir().as_local_hir_id(def_id).unwrap()),
                             InstanceDef::VtableShim(..)
                             | InstanceDef::ReifyShim(..)
                             | InstanceDef::Intrinsic(..)
@@ -350,7 +356,9 @@ impl<'tcx> CodegenUnit<'tcx> {
                             | InstanceDef::CloneShim(..) => None,
                         }
                     }
-                    MonoItem::Static(def_id) => tcx.hir().as_local_hir_id(def_id),
+                    MonoItem::Static(def_id) => {
+                        def_id.as_local().map(|def_id| tcx.hir().as_local_hir_id(def_id).unwrap())
+                    }
                     MonoItem::GlobalAsm(hir_id) => Some(hir_id),
                 },
                 item.symbol_name(tcx),
diff --git a/src/librustc_middle/query/mod.rs b/src/librustc_middle/query/mod.rs
index c7eaf9cdbd0..618a83dc38f 100644
--- a/src/librustc_middle/query/mod.rs
+++ b/src/librustc_middle/query/mod.rs
@@ -277,7 +277,7 @@ rustc_queries! {
         /// per-type-parameter predicates for resolving `T::AssocTy`.
         query type_param_predicates(key: (DefId, DefId)) -> ty::GenericPredicates<'tcx> {
             desc { |tcx| "computing the bounds for type parameter `{}`", {
-                let id = tcx.hir().as_local_hir_id(key.1).unwrap();
+                let id = tcx.hir().as_local_hir_id(key.1.expect_local()).unwrap();
                 tcx.hir().ty_param_name(id)
             }}
         }
diff --git a/src/librustc_middle/ty/context.rs b/src/librustc_middle/ty/context.rs
index 7f15179f707..85d216d9ca9 100644
--- a/src/librustc_middle/ty/context.rs
+++ b/src/librustc_middle/ty/context.rs
@@ -1413,7 +1413,8 @@ impl<'tcx> TyCtxt<'tcx> {
             _ => return None, // not a free region
         };
 
-        let hir_id = self.hir().as_local_hir_id(suitable_region_binding_scope).unwrap();
+        let hir_id =
+            self.hir().as_local_hir_id(suitable_region_binding_scope.expect_local()).unwrap();
         let is_impl_item = match self.hir().find(hir_id) {
             Some(Node::Item(..) | Node::TraitItem(..)) => false,
             Some(Node::ImplItem(..)) => {
@@ -1431,7 +1432,7 @@ impl<'tcx> TyCtxt<'tcx> {
 
     pub fn return_type_impl_trait(&self, scope_def_id: DefId) -> Option<(Ty<'tcx>, Span)> {
         // HACK: `type_of_def_id()` will fail on these (#55796), so return `None`.
-        let hir_id = self.hir().as_local_hir_id(scope_def_id).unwrap();
+        let hir_id = self.hir().as_local_hir_id(scope_def_id.expect_local()).unwrap();
         match self.hir().get(hir_id) {
             Node::Item(item) => {
                 match item.kind {
diff --git a/src/librustc_middle/ty/mod.rs b/src/librustc_middle/ty/mod.rs
index 97bc3fdb100..9839bd806bd 100644
--- a/src/librustc_middle/ty/mod.rs
+++ b/src/librustc_middle/ty/mod.rs
@@ -2667,12 +2667,14 @@ impl<'tcx> TyCtxt<'tcx> {
     }
 
     pub fn opt_item_name(self, def_id: DefId) -> Option<Ident> {
-        self.hir().as_local_hir_id(def_id).and_then(|hir_id| self.hir().get(hir_id).ident())
+        def_id
+            .as_local()
+            .and_then(|def_id| self.hir().get(self.hir().as_local_hir_id(def_id).unwrap()).ident())
     }
 
     pub fn opt_associated_item(self, def_id: DefId) -> Option<AssocItem> {
-        let is_associated_item = if let Some(hir_id) = self.hir().as_local_hir_id(def_id) {
-            match self.hir().get(hir_id) {
+        let is_associated_item = if let Some(def_id) = def_id.as_local() {
+            match self.hir().get(self.hir().as_local_hir_id(def_id).unwrap()) {
                 Node::TraitItem(_) | Node::ImplItem(_) => true,
                 _ => false,
             }
@@ -2824,8 +2826,8 @@ impl<'tcx> TyCtxt<'tcx> {
 
     /// Gets the attributes of a definition.
     pub fn get_attrs(self, did: DefId) -> Attributes<'tcx> {
-        if let Some(id) = self.hir().as_local_hir_id(did) {
-            self.hir().attrs(id)
+        if let Some(did) = did.as_local() {
+            self.hir().attrs(self.hir().as_local_hir_id(did).unwrap())
         } else {
             self.item_attrs(did)
         }
@@ -2863,7 +2865,7 @@ impl<'tcx> TyCtxt<'tcx> {
     /// Looks up the span of `impl_did` if the impl is local; otherwise returns `Err`
     /// with the name of the crate containing the impl.
     pub fn span_of_impl(self, impl_did: DefId) -> Result<Span, Symbol> {
-        if impl_did.is_local() {
+        if let Some(impl_did) = impl_did.as_local() {
             let hir_id = self.hir().as_local_hir_id(impl_did).unwrap();
             Ok(self.hir().span(hir_id))
         } else {
@@ -2924,8 +2926,8 @@ pub struct AdtSizedConstraint<'tcx>(pub &'tcx [Ty<'tcx>]);
 
 /// Yields the parent function's `DefId` if `def_id` is an `impl Trait` definition.
 pub fn is_impl_trait_defn(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
-    if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
-        if let Node::Item(item) = tcx.hir().get(hir_id) {
+    if let Some(def_id) = def_id.as_local() {
+        if let Node::Item(item) = tcx.hir().get(tcx.hir().as_local_hir_id(def_id).unwrap()) {
             if let hir::ItemKind::OpaqueTy(ref opaque_ty) = item.kind {
                 return opaque_ty.impl_trait_fn;
             }
diff --git a/src/librustc_middle/ty/print/pretty.rs b/src/librustc_middle/ty/print/pretty.rs
index a8825e8fc61..646fc6fc8eb 100644
--- a/src/librustc_middle/ty/print/pretty.rs
+++ b/src/librustc_middle/ty/print/pretty.rs
@@ -608,7 +608,9 @@ pub trait PrettyPrinter<'tcx>:
                 }
 
                 // FIXME(eddyb) should use `def_span`.
-                if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
+                if let Some(hir_id) =
+                    did.as_local().map(|did| self.tcx().hir().as_local_hir_id(did).unwrap())
+                {
                     p!(write("@{:?}", self.tcx().hir().span(hir_id)));
 
                     if substs.as_generator().is_valid() {
@@ -652,7 +654,9 @@ pub trait PrettyPrinter<'tcx>:
                 p!(write("[closure"));
 
                 // FIXME(eddyb) should use `def_span`.
-                if let Some(hir_id) = self.tcx().hir().as_local_hir_id(did) {
+                if let Some(hir_id) =
+                    did.as_local().map(|did| self.tcx().hir().as_local_hir_id(did).unwrap())
+                {
                     if self.tcx().sess.opts.debugging_opts.span_free_formats {
                         p!(write("@"), print_def_path(did, substs));
                     } else {
diff --git a/src/librustc_middle/ty/sty.rs b/src/librustc_middle/ty/sty.rs
index 0134ea1a4e9..4edd8420ebe 100644
--- a/src/librustc_middle/ty/sty.rs
+++ b/src/librustc_middle/ty/sty.rs
@@ -2266,7 +2266,7 @@ impl<'tcx> Const<'tcx> {
             ExprKind::Path(QPath::Resolved(_, &Path { res: Res::Def(ConstParam, def_id), .. })) => {
                 // Find the name and index of the const parameter by indexing the generics of
                 // the parent item and construct a `ParamConst`.
-                let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+                let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
                 let item_id = tcx.hir().get_parent_node(hir_id);
                 let item_def_id = tcx.hir().local_def_id(item_id);
                 let generics = tcx.generics_of(item_def_id.to_def_id());
diff --git a/src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs b/src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs
index 22947610448..f4e75b1c971 100644
--- a/src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs
+++ b/src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs
@@ -192,7 +192,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
             let needs_note = match ty.kind {
                 ty::Closure(id, _) => {
                     let tables = self.infcx.tcx.typeck_tables_of(id);
-                    let hir_id = self.infcx.tcx.hir().as_local_hir_id(id).unwrap();
+                    let hir_id = self.infcx.tcx.hir().as_local_hir_id(id.expect_local()).unwrap();
 
                     tables.closure_kind_origins().get(hir_id).is_none()
                 }
@@ -864,7 +864,11 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
                 format!("`{}` would have to be valid for `{}`...", name, region_name),
             );
 
-            if let Some(fn_hir_id) = self.infcx.tcx.hir().as_local_hir_id(self.mir_def_id) {
+            if let Some(fn_hir_id) = self
+                .mir_def_id
+                .as_local()
+                .map(|def_id| self.infcx.tcx.hir().as_local_hir_id(def_id).unwrap())
+            {
                 err.span_label(
                     drop_span,
                     format!(
@@ -1782,7 +1786,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
     ) -> Option<AnnotatedBorrowFnSignature<'tcx>> {
         debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
         let is_closure = self.infcx.tcx.is_closure(did);
-        let fn_hir_id = self.infcx.tcx.hir().as_local_hir_id(did)?;
+        let fn_hir_id = self.infcx.tcx.hir().as_local_hir_id(did.as_local()?)?;
         let fn_decl = self.infcx.tcx.hir().fn_decl_by_hir_id(fn_hir_id)?;
 
         // We need to work out which arguments to highlight. We do this by looking
diff --git a/src/librustc_mir/borrow_check/diagnostics/mod.rs b/src/librustc_mir/borrow_check/diagnostics/mod.rs
index 91d8d853eaf..b3c6bee03ae 100644
--- a/src/librustc_mir/borrow_check/diagnostics/mod.rs
+++ b/src/librustc_mir/borrow_check/diagnostics/mod.rs
@@ -97,7 +97,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
 
                 debug!("add_moved_or_invoked_closure_note: closure={:?}", closure);
                 if let ty::Closure(did, _) = self.body.local_decls[closure].ty.kind {
-                    let hir_id = self.infcx.tcx.hir().as_local_hir_id(did).unwrap();
+                    let hir_id = self.infcx.tcx.hir().as_local_hir_id(did.expect_local()).unwrap();
 
                     if let Some((span, name)) =
                         self.infcx.tcx.typeck_tables_of(did).closure_kind_origins().get(hir_id)
@@ -119,7 +119,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
         // Check if we are just moving a closure after it has been invoked.
         if let Some(target) = target {
             if let ty::Closure(did, _) = self.body.local_decls[target].ty.kind {
-                let hir_id = self.infcx.tcx.hir().as_local_hir_id(did).unwrap();
+                let hir_id = self.infcx.tcx.hir().as_local_hir_id(did.expect_local()).unwrap();
 
                 if let Some((span, name)) =
                     self.infcx.tcx.typeck_tables_of(did).closure_kind_origins().get(hir_id)
@@ -803,7 +803,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
             "closure_span: def_id={:?} target_place={:?} places={:?}",
             def_id, target_place, places
         );
-        let hir_id = self.infcx.tcx.hir().as_local_hir_id(def_id)?;
+        let hir_id = self.infcx.tcx.hir().as_local_hir_id(def_id.as_local()?)?;
         let expr = &self.infcx.tcx.hir().expect_expr(hir_id).kind;
         debug!("closure_span: hir_id={:?} expr={:?}", hir_id, expr);
         if let hir::ExprKind::Closure(.., body_id, args_span, _) = expr {
diff --git a/src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs b/src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs
index c0aee31781e..0614538f4e4 100644
--- a/src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs
+++ b/src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs
@@ -492,7 +492,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
         err.span_label(sp, format!("cannot {}", act));
 
         let hir = self.infcx.tcx.hir();
-        let closure_id = hir.as_local_hir_id(self.mir_def_id).unwrap();
+        let closure_id = hir.as_local_hir_id(self.mir_def_id.expect_local()).unwrap();
         let fn_call_id = hir.get_parent_node(closure_id);
         let node = hir.get(fn_call_id);
         let item_id = hir.get_parent_item(fn_call_id);
@@ -691,7 +691,7 @@ fn annotate_struct_field(
         if let ty::Adt(def, _) = ty.kind {
             let field = def.all_fields().nth(field.index())?;
             // Use the HIR types to construct the diagnostic message.
-            let hir_id = tcx.hir().as_local_hir_id(field.did)?;
+            let hir_id = tcx.hir().as_local_hir_id(field.did.as_local()?)?;
             let node = tcx.hir().find(hir_id)?;
             // Now we're dealing with the actual struct that we're going to suggest a change to,
             // we can expect a field that is an immutable reference to a type.
diff --git a/src/librustc_mir/borrow_check/diagnostics/region_name.rs b/src/librustc_mir/borrow_check/diagnostics/region_name.rs
index 70375921471..74cdccd7e3f 100644
--- a/src/librustc_mir/borrow_check/diagnostics/region_name.rs
+++ b/src/librustc_mir/borrow_check/diagnostics/region_name.rs
@@ -241,8 +241,8 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> {
                         .infcx
                         .tcx
                         .hir()
-                        .as_local_hir_id(self.mir_def_id)
-                        .expect("non-local mir");
+                        .as_local_hir_id(self.mir_def_id.expect_local())
+                        .unwrap();
                     let def_ty = self.regioncx.universal_regions().defining_ty;
 
                     if let DefiningTy::Closure(_, substs) = def_ty {
@@ -328,7 +328,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> {
         argument_ty: Ty<'tcx>,
         argument_index: usize,
     ) -> Option<RegionName> {
-        let mir_hir_id = self.infcx.tcx.hir().as_local_hir_id(self.mir_def_id)?;
+        let mir_hir_id = self.infcx.tcx.hir().as_local_hir_id(self.mir_def_id.as_local()?)?;
         let fn_decl = self.infcx.tcx.hir().fn_decl_by_hir_id(mir_hir_id)?;
         let argument_hir_ty: &hir::Ty<'_> = fn_decl.inputs.get(argument_index)?;
         match argument_hir_ty.kind {
@@ -639,7 +639,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> {
         highlight.highlighting_region_vid(fr, *self.next_region_name.try_borrow().unwrap());
         let type_name = self.infcx.extract_type_name(&return_ty, Some(highlight)).0;
 
-        let mir_hir_id = tcx.hir().as_local_hir_id(self.mir_def_id).expect("non-local mir");
+        let mir_hir_id = tcx.hir().as_local_hir_id(self.mir_def_id.expect_local()).unwrap();
 
         let (return_span, mir_description) = match tcx.hir().get(mir_hir_id) {
             hir::Node::Expr(hir::Expr {
@@ -691,7 +691,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> {
         highlight.highlighting_region_vid(fr, *self.next_region_name.try_borrow().unwrap());
         let type_name = self.infcx.extract_type_name(&yield_ty, Some(highlight)).0;
 
-        let mir_hir_id = tcx.hir().as_local_hir_id(self.mir_def_id).expect("non-local mir");
+        let mir_hir_id = tcx.hir().as_local_hir_id(self.mir_def_id.expect_local()).unwrap();
 
         let yield_span = match tcx.hir().get(mir_hir_id) {
             hir::Node::Expr(hir::Expr {
diff --git a/src/librustc_mir/borrow_check/mod.rs b/src/librustc_mir/borrow_check/mod.rs
index a330dc95f23..7de890dfa6c 100644
--- a/src/librustc_mir/borrow_check/mod.rs
+++ b/src/librustc_mir/borrow_check/mod.rs
@@ -5,7 +5,10 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet};
 use rustc_data_structures::graph::dominators::Dominators;
 use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorReported};
 use rustc_hir as hir;
-use rustc_hir::{def_id::DefId, HirId, Node};
+use rustc_hir::{
+    def_id::{DefId, LocalDefId},
+    HirId, Node,
+};
 use rustc_index::bit_set::BitSet;
 use rustc_index::vec::IndexVec;
 use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
@@ -96,7 +99,7 @@ fn mir_borrowck(tcx: TyCtxt<'_>, def_id: DefId) -> &BorrowCheckResult<'_> {
     let opt_closure_req = tcx.infer_ctxt().enter(|infcx| {
         let input_body: &Body<'_> = &input_body.borrow();
         let promoted: &IndexVec<_, _> = &promoted.borrow();
-        do_mir_borrowck(&infcx, input_body, promoted, def_id)
+        do_mir_borrowck(&infcx, input_body, promoted, def_id.expect_local())
     });
     debug!("mir_borrowck done");
 
@@ -107,13 +110,13 @@ fn do_mir_borrowck<'a, 'tcx>(
     infcx: &InferCtxt<'a, 'tcx>,
     input_body: &Body<'tcx>,
     input_promoted: &IndexVec<Promoted, Body<'tcx>>,
-    def_id: DefId,
+    def_id: LocalDefId,
 ) -> BorrowCheckResult<'tcx> {
     debug!("do_mir_borrowck(def_id = {:?})", def_id);
 
     let tcx = infcx.tcx;
     let param_env = tcx.param_env(def_id);
-    let id = tcx.hir().as_local_hir_id(def_id).expect("do_mir_borrowck: non-local DefId");
+    let id = tcx.hir().as_local_hir_id(def_id).unwrap();
 
     let mut local_names = IndexVec::from_elem(None, &input_body.local_decls);
     for var_debug_info in &input_body.var_debug_info {
@@ -140,7 +143,7 @@ fn do_mir_borrowck<'a, 'tcx>(
     }
     let upvars: Vec<_> = tables
         .upvar_list
-        .get(&def_id)
+        .get(&def_id.to_def_id())
         .into_iter()
         .flat_map(|v| v.values())
         .map(|upvar_id| {
@@ -171,7 +174,7 @@ fn do_mir_borrowck<'a, 'tcx>(
     let mut body = input_body.clone();
     let mut promoted = input_promoted.clone();
     let free_regions =
-        nll::replace_regions_in_mir(infcx, def_id, param_env, &mut body, &mut promoted);
+        nll::replace_regions_in_mir(infcx, def_id.to_def_id(), param_env, &mut body, &mut promoted);
     let body = &body; // no further changes
 
     let location_table = &LocationTable::new(&body);
@@ -186,7 +189,7 @@ fn do_mir_borrowck<'a, 'tcx>(
     let mdpe = MoveDataParamEnv { move_data, param_env };
 
     let mut flow_inits = MaybeInitializedPlaces::new(tcx, &body, &mdpe)
-        .into_engine(tcx, &body, def_id)
+        .into_engine(tcx, &body, def_id.to_def_id())
         .iterate_to_fixpoint()
         .into_results_cursor(&body);
 
@@ -203,7 +206,7 @@ fn do_mir_borrowck<'a, 'tcx>(
         nll_errors,
     } = nll::compute_regions(
         infcx,
-        def_id,
+        def_id.to_def_id(),
         free_regions,
         body,
         &promoted,
@@ -216,14 +219,20 @@ fn do_mir_borrowck<'a, 'tcx>(
 
     // Dump MIR results into a file, if that is enabled. This let us
     // write unit-tests, as well as helping with debugging.
-    nll::dump_mir_results(infcx, MirSource::item(def_id), &body, &regioncx, &opt_closure_req);
+    nll::dump_mir_results(
+        infcx,
+        MirSource::item(def_id.to_def_id()),
+        &body,
+        &regioncx,
+        &opt_closure_req,
+    );
 
     // We also have a `#[rustc_regions]` annotation that causes us to dump
     // information.
     nll::dump_annotation(
         infcx,
         &body,
-        def_id,
+        def_id.to_def_id(),
         &regioncx,
         &opt_closure_req,
         &opaque_type_values,
@@ -238,13 +247,13 @@ fn do_mir_borrowck<'a, 'tcx>(
     let regioncx = Rc::new(regioncx);
 
     let flow_borrows = Borrows::new(tcx, &body, regioncx.clone(), &borrow_set)
-        .into_engine(tcx, &body, def_id)
+        .into_engine(tcx, &body, def_id.to_def_id())
         .iterate_to_fixpoint();
     let flow_uninits = MaybeUninitializedPlaces::new(tcx, &body, &mdpe)
-        .into_engine(tcx, &body, def_id)
+        .into_engine(tcx, &body, def_id.to_def_id())
         .iterate_to_fixpoint();
     let flow_ever_inits = EverInitializedPlaces::new(tcx, &body, &mdpe)
-        .into_engine(tcx, &body, def_id)
+        .into_engine(tcx, &body, def_id.to_def_id())
         .iterate_to_fixpoint();
 
     let movable_generator = match tcx.hir().get(id) {
@@ -260,7 +269,7 @@ fn do_mir_borrowck<'a, 'tcx>(
     let mut mbcx = MirBorrowckCtxt {
         infcx,
         body,
-        mir_def_id: def_id,
+        mir_def_id: def_id.to_def_id(),
         move_data: &mdpe.move_data,
         location_table,
         movable_generator,
diff --git a/src/librustc_mir/borrow_check/nll.rs b/src/librustc_mir/borrow_check/nll.rs
index 141ed00e789..e0cfcdb87a5 100644
--- a/src/librustc_mir/borrow_check/nll.rs
+++ b/src/librustc_mir/borrow_check/nll.rs
@@ -66,7 +66,7 @@ pub(in crate::borrow_check) fn replace_regions_in_mir<'cx, 'tcx>(
     debug!("replace_regions_in_mir(def_id={:?})", def_id);
 
     // Compute named region information. This also renumbers the inputs/outputs.
-    let universal_regions = UniversalRegions::new(infcx, def_id, param_env);
+    let universal_regions = UniversalRegions::new(infcx, def_id.expect_local(), param_env);
 
     // Replace all remaining regions with fresh inference variables.
     renumber::renumber_mir(infcx, body, promoted);
diff --git a/src/librustc_mir/borrow_check/type_check/mod.rs b/src/librustc_mir/borrow_check/type_check/mod.rs
index 179641ec7c0..931e01d3071 100644
--- a/src/librustc_mir/borrow_check/type_check/mod.rs
+++ b/src/librustc_mir/borrow_check/type_check/mod.rs
@@ -1989,7 +1989,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
                         if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
                             let ccx = ConstCx::new_with_param_env(
                                 tcx,
-                                self.mir_def_id,
+                                self.mir_def_id.expect_local(),
                                 body,
                                 self.param_env,
                             );
diff --git a/src/librustc_mir/borrow_check/universal_regions.rs b/src/librustc_mir/borrow_check/universal_regions.rs
index 2dbfcb69017..de985cb37c5 100644
--- a/src/librustc_mir/borrow_check/universal_regions.rs
+++ b/src/librustc_mir/borrow_check/universal_regions.rs
@@ -16,7 +16,7 @@ use either::Either;
 use rustc_data_structures::fx::FxHashMap;
 use rustc_errors::DiagnosticBuilder;
 use rustc_hir as hir;
-use rustc_hir::def_id::DefId;
+use rustc_hir::def_id::{DefId, LocalDefId};
 use rustc_hir::lang_items;
 use rustc_hir::{BodyOwnerKind, HirId};
 use rustc_index::vec::{Idx, IndexVec};
@@ -220,12 +220,13 @@ impl<'tcx> UniversalRegions<'tcx> {
     /// known between those regions.
     pub fn new(
         infcx: &InferCtxt<'_, 'tcx>,
-        mir_def_id: DefId,
+        mir_def_id: LocalDefId,
         param_env: ty::ParamEnv<'tcx>,
     ) -> Self {
         let tcx = infcx.tcx;
         let mir_hir_id = tcx.hir().as_local_hir_id(mir_def_id).unwrap();
-        UniversalRegionsBuilder { infcx, mir_def_id, mir_hir_id, param_env }.build()
+        UniversalRegionsBuilder { infcx, mir_def_id: mir_def_id.to_def_id(), mir_hir_id, param_env }
+            .build()
     }
 
     /// Given a reference to a closure type, extracts all the values
diff --git a/src/librustc_mir/const_eval/eval_queries.rs b/src/librustc_mir/const_eval/eval_queries.rs
index 1592207e4d2..6b6d02dedcb 100644
--- a/src/librustc_mir/const_eval/eval_queries.rs
+++ b/src/librustc_mir/const_eval/eval_queries.rs
@@ -342,7 +342,7 @@ pub fn const_eval_raw_provider<'tcx>(
                     // validation thus preventing such a hard error from being a backwards
                     // compatibility hazard
                     Some(DefKind::Const | DefKind::AssocConst) => {
-                        let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+                        let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
                         err.report_as_lint(
                             tcx.at(tcx.def_span(def_id)),
                             "any use of this value will cause an error",
@@ -365,7 +365,7 @@ pub fn const_eval_raw_provider<'tcx>(
                                 err.report_as_lint(
                                     tcx.at(span),
                                     "reaching this expression at runtime will panic or abort",
-                                    tcx.hir().as_local_hir_id(def_id).unwrap(),
+                                    tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap(),
                                     Some(err.span),
                                 )
                             }
diff --git a/src/librustc_mir/const_eval/fn_queries.rs b/src/librustc_mir/const_eval/fn_queries.rs
index bb33372692d..8decebf6f8c 100644
--- a/src/librustc_mir/const_eval/fn_queries.rs
+++ b/src/librustc_mir/const_eval/fn_queries.rs
@@ -90,8 +90,7 @@ pub fn is_parent_const_impl_raw(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool {
 /// Checks whether the function has a `const` modifier or, in case it is an intrinsic, whether
 /// said intrinsic is on the whitelist for being const callable.
 fn is_const_fn_raw(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
-    let hir_id =
-        tcx.hir().as_local_hir_id(def_id).expect("Non-local call to local provider is_const_fn");
+    let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
 
     let node = tcx.hir().get(hir_id);
 
diff --git a/src/librustc_mir/monomorphize/collector.rs b/src/librustc_mir/monomorphize/collector.rs
index b8f7596070f..a65b14e64f1 100644
--- a/src/librustc_mir/monomorphize/collector.rs
+++ b/src/librustc_mir/monomorphize/collector.rs
@@ -430,7 +430,9 @@ fn check_recursion_limit<'tcx>(
     // infinite expansion.
     if adjusted_recursion_depth > *tcx.sess.recursion_limit.get() {
         let error = format!("reached the recursion limit while instantiating `{}`", instance);
-        if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
+        if let Some(hir_id) =
+            def_id.as_local().map(|def_id| tcx.hir().as_local_hir_id(def_id).unwrap())
+        {
             tcx.sess.span_fatal(tcx.hir().span(hir_id), &error);
         } else {
             tcx.sess.fatal(&error);
diff --git a/src/librustc_mir/transform/check_consts/mod.rs b/src/librustc_mir/transform/check_consts/mod.rs
index a630c56ee97..a0692cf8a70 100644
--- a/src/librustc_mir/transform/check_consts/mod.rs
+++ b/src/librustc_mir/transform/check_consts/mod.rs
@@ -5,7 +5,7 @@
 //! it finds operations that are invalid in a certain context.
 
 use rustc_hir as hir;
-use rustc_hir::def_id::DefId;
+use rustc_hir::def_id::{DefId, LocalDefId};
 use rustc_middle::mir;
 use rustc_middle::ty::{self, TyCtxt};
 
@@ -29,20 +29,20 @@ pub struct ConstCx<'mir, 'tcx> {
 }
 
 impl ConstCx<'mir, 'tcx> {
-    pub fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &'mir mir::Body<'tcx>) -> Self {
+    pub fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId, body: &'mir mir::Body<'tcx>) -> Self {
         let param_env = tcx.param_env(def_id);
         Self::new_with_param_env(tcx, def_id, body, param_env)
     }
 
     pub fn new_with_param_env(
         tcx: TyCtxt<'tcx>,
-        def_id: DefId,
+        def_id: LocalDefId,
         body: &'mir mir::Body<'tcx>,
         param_env: ty::ParamEnv<'tcx>,
     ) -> Self {
         let const_kind = ConstKind::for_item(tcx, def_id);
 
-        ConstCx { body, tcx, def_id, param_env, const_kind }
+        ConstCx { body, tcx, def_id: def_id.to_def_id(), param_env, const_kind }
     }
 
     /// Returns the kind of const context this `Item` represents (`const`, `static`, etc.).
@@ -69,7 +69,7 @@ pub enum ConstKind {
 impl ConstKind {
     /// Returns the validation mode for the item with the given `DefId`, or `None` if this item
     /// does not require validation (e.g. a non-const `fn`).
-    pub fn for_item(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<Self> {
+    pub fn for_item(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Option<Self> {
         use hir::BodyOwnerKind as HirKind;
 
         let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
diff --git a/src/librustc_mir/transform/check_consts/validation.rs b/src/librustc_mir/transform/check_consts/validation.rs
index 45d8e1d08b7..609499d25fd 100644
--- a/src/librustc_mir/transform/check_consts/validation.rs
+++ b/src/librustc_mir/transform/check_consts/validation.rs
@@ -190,7 +190,7 @@ impl Validator<'a, 'mir, 'tcx> {
             const_kind == Some(ConstKind::Static) && !tcx.has_attr(def_id, sym::thread_local);
 
         if should_check_for_sync {
-            let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+            let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
             check_return_ty_is_sync(tcx, &body, hir_id);
         }
     }
diff --git a/src/librustc_mir/transform/check_unsafety.rs b/src/librustc_mir/transform/check_unsafety.rs
index 5215c985107..6f9d007f9d3 100644
--- a/src/librustc_mir/transform/check_unsafety.rs
+++ b/src/librustc_mir/transform/check_unsafety.rs
@@ -1,7 +1,7 @@
 use rustc_data_structures::fx::FxHashSet;
 use rustc_errors::struct_span_err;
 use rustc_hir as hir;
-use rustc_hir::def_id::DefId;
+use rustc_hir::def_id::{DefId, LocalDefId};
 use rustc_hir::intravisit;
 use rustc_hir::Node;
 use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor};
@@ -465,12 +465,11 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
 
 fn check_unused_unsafe(
     tcx: TyCtxt<'_>,
-    def_id: DefId,
+    def_id: LocalDefId,
     used_unsafe: &FxHashSet<hir::HirId>,
     unsafe_blocks: &mut Vec<(hir::HirId, bool)>,
 ) {
-    let body_id =
-        tcx.hir().as_local_hir_id(def_id).and_then(|hir_id| tcx.hir().maybe_body_owned_by(hir_id));
+    let body_id = tcx.hir().maybe_body_owned_by(tcx.hir().as_local_hir_id(def_id).unwrap());
 
     let body_id = match body_id {
         Some(body) => body,
@@ -495,7 +494,7 @@ fn unsafety_check_result(tcx: TyCtxt<'_>, def_id: DefId) -> UnsafetyCheckResult
 
     let param_env = tcx.param_env(def_id);
 
-    let id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    let id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
     let (const_context, min_const_fn) = match tcx.hir().body_owner_kind(id) {
         hir::BodyOwnerKind::Closure => (false, false),
         hir::BodyOwnerKind::Fn => (is_const_fn(tcx, def_id), is_min_const_fn(tcx, def_id)),
@@ -504,7 +503,12 @@ fn unsafety_check_result(tcx: TyCtxt<'_>, def_id: DefId) -> UnsafetyCheckResult
     let mut checker = UnsafetyChecker::new(const_context, min_const_fn, body, tcx, param_env);
     checker.visit_body(&body);
 
-    check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
+    check_unused_unsafe(
+        tcx,
+        def_id.expect_local(),
+        &checker.used_unsafe,
+        &mut checker.inherited_blocks,
+    );
     UnsafetyCheckResult {
         violations: checker.violations.into(),
         unsafe_blocks: checker.inherited_blocks.into(),
@@ -512,10 +516,7 @@ fn unsafety_check_result(tcx: TyCtxt<'_>, def_id: DefId) -> UnsafetyCheckResult
 }
 
 fn unsafe_derive_on_repr_packed(tcx: TyCtxt<'_>, def_id: DefId) {
-    let lint_hir_id = tcx
-        .hir()
-        .as_local_hir_id(def_id)
-        .unwrap_or_else(|| bug!("checking unsafety for non-local def id {:?}", def_id));
+    let lint_hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
 
     tcx.struct_span_lint_hir(SAFE_PACKED_BORROWS, lint_hir_id, tcx.def_span(def_id), |lint| {
         // FIXME: when we make this a hard error, this should have its
diff --git a/src/librustc_mir/transform/const_prop.rs b/src/librustc_mir/transform/const_prop.rs
index beabdf7f784..8647c3f0727 100644
--- a/src/librustc_mir/transform/const_prop.rs
+++ b/src/librustc_mir/transform/const_prop.rs
@@ -66,10 +66,7 @@ impl<'tcx> MirPass<'tcx> for ConstProp {
         }
 
         use rustc_middle::hir::map::blocks::FnLikeNode;
-        let hir_id = tcx
-            .hir()
-            .as_local_hir_id(source.def_id())
-            .expect("Non-local call to local provider is_const_fn");
+        let hir_id = tcx.hir().as_local_hir_id(source.def_id().expect_local()).unwrap();
 
         let is_fn_like = FnLikeNode::from_node(tcx.hir().get(hir_id)).is_some();
         let is_assoc_const = match tcx.def_kind(source.def_id()) {
diff --git a/src/librustc_mir/transform/inline.rs b/src/librustc_mir/transform/inline.rs
index d8bb8a0b52c..cf0197659c8 100644
--- a/src/librustc_mir/transform/inline.rs
+++ b/src/librustc_mir/transform/inline.rs
@@ -69,7 +69,7 @@ impl Inliner<'tcx> {
         let param_env = self.tcx.param_env(self.source.def_id()).with_reveal_all();
 
         // Only do inlining into fn bodies.
-        let id = self.tcx.hir().as_local_hir_id(self.source.def_id()).unwrap();
+        let id = self.tcx.hir().as_local_hir_id(self.source.def_id().expect_local()).unwrap();
         if self.tcx.hir().body_owner_kind(id).is_fn_or_closure() && self.source.promoted.is_none() {
             for (bb, bb_data) in caller_body.basic_blocks().iter_enumerated() {
                 if let Some(callsite) =
@@ -94,10 +94,14 @@ impl Inliner<'tcx> {
                     continue;
                 }
 
-                let callee_hir_id = self.tcx.hir().as_local_hir_id(callsite.callee);
+                let callee_hir_id = self.tcx.hir().as_local_hir_id(callsite.callee.expect_local());
 
                 let callee_body = if let Some(callee_hir_id) = callee_hir_id {
-                    let self_hir_id = self.tcx.hir().as_local_hir_id(self.source.def_id()).unwrap();
+                    let self_hir_id = self
+                        .tcx
+                        .hir()
+                        .as_local_hir_id(self.source.def_id().expect_local())
+                        .unwrap();
                     // Avoid a cycle here by only using `optimized_mir` only if we have
                     // a lower `HirId` than the callee. This ensures that the callee will
                     // not inline us. This trick only works without incremental compilation.
diff --git a/src/librustc_mir/transform/mod.rs b/src/librustc_mir/transform/mod.rs
index 40f26d5c52c..a5ed059ba09 100644
--- a/src/librustc_mir/transform/mod.rs
+++ b/src/librustc_mir/transform/mod.rs
@@ -176,7 +176,7 @@ pub fn run_passes(
 }
 
 fn mir_const_qualif(tcx: TyCtxt<'_>, def_id: DefId) -> ConstQualifs {
-    let const_kind = check_consts::ConstKind::for_item(tcx, def_id);
+    let const_kind = check_consts::ConstKind::for_item(tcx, def_id.expect_local());
 
     // No need to const-check a non-const `fn`.
     if const_kind.is_none() {
diff --git a/src/librustc_mir/transform/promote_consts.rs b/src/librustc_mir/transform/promote_consts.rs
index 998af4ba390..0b73643e339 100644
--- a/src/librustc_mir/transform/promote_consts.rs
+++ b/src/librustc_mir/transform/promote_consts.rs
@@ -62,7 +62,7 @@ impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> {
         let def_id = src.def_id();
 
         let mut rpo = traversal::reverse_postorder(body);
-        let ccx = ConstCx::new(tcx, def_id, body);
+        let ccx = ConstCx::new(tcx, def_id.expect_local(), body);
         let (temps, all_candidates) = collect_temps_and_candidates(&ccx, &mut rpo);
 
         let promotable_candidates = validate_candidates(&ccx, &temps, &all_candidates);
diff --git a/src/librustc_mir/transform/qualify_min_const_fn.rs b/src/librustc_mir/transform/qualify_min_const_fn.rs
index d28d76e1470..d2f1920b263 100644
--- a/src/librustc_mir/transform/qualify_min_const_fn.rs
+++ b/src/librustc_mir/transform/qualify_min_const_fn.rs
@@ -13,7 +13,7 @@ type McfResult = Result<(), (Span, Cow<'static, str>)>;
 pub fn is_min_const_fn(tcx: TyCtxt<'tcx>, def_id: DefId, body: &'a Body<'tcx>) -> McfResult {
     // Prevent const trait methods from being annotated as `stable`.
     if tcx.features().staged_api {
-        let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+        let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
         if crate::const_eval::is_parent_const_impl_raw(tcx, hir_id) {
             return Err((body.span, "trait methods cannot be stable const fn".into()));
         }
diff --git a/src/librustc_mir/util/liveness.rs b/src/librustc_mir/util/liveness.rs
index 80b31be84ca..595f39d028d 100644
--- a/src/librustc_mir/util/liveness.rs
+++ b/src/librustc_mir/util/liveness.rs
@@ -285,7 +285,7 @@ fn dump_matched_mir_node<'tcx>(
 ) {
     let mut file_path = PathBuf::new();
     file_path.push(Path::new(&tcx.sess.opts.debugging_opts.dump_mir_dir));
-    let item_id = tcx.hir().as_local_hir_id(source.def_id()).unwrap();
+    let item_id = tcx.hir().as_local_hir_id(source.def_id().expect_local()).unwrap();
     let file_name = format!("rustc.node{}{}-liveness.mir", item_id, pass_name);
     file_path.push(&file_name);
     let _ = fs::File::create(&file_path).and_then(|file| {
diff --git a/src/librustc_mir_build/build/mod.rs b/src/librustc_mir_build/build/mod.rs
index 2d76e274510..ce3df93bf1e 100644
--- a/src/librustc_mir_build/build/mod.rs
+++ b/src/librustc_mir_build/build/mod.rs
@@ -22,11 +22,11 @@ use rustc_target::spec::PanicStrategy;
 use super::lints;
 
 crate fn mir_built(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::steal::Steal<Body<'_>> {
-    tcx.alloc_steal_mir(mir_build(tcx, def_id))
+    tcx.alloc_steal_mir(mir_build(tcx, def_id.expect_local()))
 }
 
 /// Construct the MIR for a given `DefId`.
-fn mir_build(tcx: TyCtxt<'_>, def_id: DefId) -> Body<'_> {
+fn mir_build(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Body<'_> {
     let id = tcx.hir().as_local_hir_id(def_id).unwrap();
 
     // Figure out what primary body this item has.
@@ -181,7 +181,7 @@ fn mir_build(tcx: TyCtxt<'_>, def_id: DefId) -> Body<'_> {
             build::construct_const(cx, body_id, return_ty, return_ty_span)
         };
 
-        lints::check(tcx, &body, def_id);
+        lints::check(tcx, &body, def_id.to_def_id());
 
         // The borrow checker will replace all the regions here with its own
         // inference variables. There's no point having non-erased regions here.
diff --git a/src/librustc_mir_build/hair/cx/expr.rs b/src/librustc_mir_build/hair/cx/expr.rs
index e5cd05da805..9669090eb46 100644
--- a/src/librustc_mir_build/hair/cx/expr.rs
+++ b/src/librustc_mir_build/hair/cx/expr.rs
@@ -690,7 +690,7 @@ fn convert_path_expr<'a, 'tcx>(
         }
 
         Res::Def(DefKind::ConstParam, def_id) => {
-            let hir_id = cx.tcx.hir().as_local_hir_id(def_id).unwrap();
+            let hir_id = cx.tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
             let item_id = cx.tcx.hir().get_parent_node(hir_id);
             let item_def_id = cx.tcx.hir().local_def_id(item_id);
             let generics = cx.tcx.generics_of(item_def_id);
diff --git a/src/librustc_mir_build/hair/pattern/check_match.rs b/src/librustc_mir_build/hair/pattern/check_match.rs
index cdbcaea0bef..14f36038232 100644
--- a/src/librustc_mir_build/hair/pattern/check_match.rs
+++ b/src/librustc_mir_build/hair/pattern/check_match.rs
@@ -21,9 +21,9 @@ use rustc_span::{sym, Span};
 use std::slice;
 
 crate fn check_match(tcx: TyCtxt<'_>, def_id: DefId) {
-    let body_id = match tcx.hir().as_local_hir_id(def_id) {
+    let body_id = match def_id.as_local() {
         None => return,
-        Some(id) => tcx.hir().body_owned_by(id),
+        Some(id) => tcx.hir().body_owned_by(tcx.hir().as_local_hir_id(id).unwrap()),
     };
 
     let mut visitor =
diff --git a/src/librustc_mir_build/lints.rs b/src/librustc_mir_build/lints.rs
index 66d56858527..dd2d6b06c18 100644
--- a/src/librustc_mir_build/lints.rs
+++ b/src/librustc_mir_build/lints.rs
@@ -11,7 +11,7 @@ use rustc_session::lint::builtin::UNCONDITIONAL_RECURSION;
 use rustc_span::Span;
 
 crate fn check<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, def_id: DefId) {
-    let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
 
     if let Some(fn_like_node) = FnLikeNode::from_node(tcx.hir().get(hir_id)) {
         if let FnKind::Closure(_) = fn_like_node.kind() {
@@ -37,7 +37,7 @@ crate fn check<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, def_id: DefId) {
 
         vis.reachable_recursive_calls.sort();
 
-        let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+        let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
         let sp = tcx.sess.source_map().guess_head_span(tcx.hir().span(hir_id));
         tcx.struct_span_lint_hir(UNCONDITIONAL_RECURSION, hir_id, sp, |lint| {
             let mut db = lint.build("function cannot return without recursing");
diff --git a/src/librustc_passes/dead.rs b/src/librustc_passes/dead.rs
index c07087db607..6ce1a7ef777 100644
--- a/src/librustc_passes/dead.rs
+++ b/src/librustc_passes/dead.rs
@@ -52,7 +52,8 @@ struct MarkSymbolVisitor<'a, 'tcx> {
 
 impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> {
     fn check_def_id(&mut self, def_id: DefId) {
-        if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
+        if let Some(def_id) = def_id.as_local() {
+            let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
             if should_explore(self.tcx, hir_id) || self.struct_constructors.contains_key(&hir_id) {
                 self.worklist.push(hir_id);
             }
@@ -61,7 +62,8 @@ impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> {
     }
 
     fn insert_def_id(&mut self, def_id: DefId) {
-        if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
+        if let Some(def_id) = def_id.as_local() {
+            let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
             debug_assert!(!should_explore(self.tcx, hir_id));
             self.live_symbols.insert(hir_id);
         }
@@ -450,7 +452,8 @@ fn create_and_seed_worklist<'tcx>(
         )
         .chain(
             // Seed entry point
-            tcx.entry_fn(LOCAL_CRATE).map(|(def_id, _)| tcx.hir().as_local_hir_id(def_id).unwrap()),
+            tcx.entry_fn(LOCAL_CRATE)
+                .map(|(def_id, _)| tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap()),
         )
         .collect::<Vec<_>>();
 
@@ -534,7 +537,9 @@ impl DeadVisitor<'tcx> {
         let inherent_impls = self.tcx.inherent_impls(def_id);
         for &impl_did in inherent_impls.iter() {
             for &item_did in &self.tcx.associated_item_def_ids(impl_did)[..] {
-                if let Some(item_hir_id) = self.tcx.hir().as_local_hir_id(item_did) {
+                if let Some(item_hir_id) =
+                    item_did.as_local().map(|did| self.tcx.hir().as_local_hir_id(did).unwrap())
+                {
                     if self.live_symbols.contains(&item_hir_id) {
                         return true;
                     }
diff --git a/src/librustc_passes/reachable.rs b/src/librustc_passes/reachable.rs
index bbd74e90ceb..a8ab127ddf8 100644
--- a/src/librustc_passes/reachable.rs
+++ b/src/librustc_passes/reachable.rs
@@ -53,7 +53,7 @@ fn method_might_be_inlined(
             return true;
         }
     }
-    if let Some(impl_hir_id) = tcx.hir().as_local_hir_id(impl_src.to_def_id()) {
+    if let Some(impl_hir_id) = tcx.hir().as_local_hir_id(impl_src) {
         match tcx.hir().find(impl_hir_id) {
             Some(Node::Item(item)) => item_might_be_inlined(tcx, &item, codegen_fn_attrs),
             Some(..) | None => span_bug!(impl_item.span, "impl did is not an item"),
@@ -108,9 +108,11 @@ impl<'a, 'tcx> Visitor<'tcx> for ReachableContext<'a, 'tcx> {
             }
             Some(res) => {
                 if let Some((hir_id, def_id)) = res.opt_def_id().and_then(|def_id| {
-                    self.tcx.hir().as_local_hir_id(def_id).map(|hir_id| (hir_id, def_id))
+                    def_id
+                        .as_local()
+                        .map(|def_id| (self.tcx.hir().as_local_hir_id(def_id).unwrap(), def_id))
                 }) {
-                    if self.def_id_represents_local_inlined_item(def_id) {
+                    if self.def_id_represents_local_inlined_item(def_id.to_def_id()) {
                         self.worklist.push(hir_id);
                     } else {
                         match res {
@@ -141,8 +143,8 @@ impl<'a, 'tcx> ReachableContext<'a, 'tcx> {
     // Returns true if the given def ID represents a local item that is
     // eligible for inlining and false otherwise.
     fn def_id_represents_local_inlined_item(&self, def_id: DefId) -> bool {
-        let hir_id = match self.tcx.hir().as_local_hir_id(def_id) {
-            Some(hir_id) => hir_id,
+        let hir_id = match def_id.as_local() {
+            Some(def_id) => self.tcx.hir().as_local_hir_id(def_id).unwrap(),
             None => {
                 return false;
             }
@@ -170,7 +172,7 @@ impl<'a, 'tcx> ReachableContext<'a, 'tcx> {
                         if generics.requires_monomorphization(self.tcx) || attrs.requests_inline() {
                             true
                         } else {
-                            let impl_did = self.tcx.hir().get_parent_did(hir_id).to_def_id();
+                            let impl_did = self.tcx.hir().get_parent_did(hir_id);
                             // Check the impl. If the generics on the self
                             // type of the impl require inlining, this method
                             // does too.
@@ -360,8 +362,9 @@ impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CollectPrivateImplItemsVisitor<'a, 'tcx
                 // FIXME(#53488) remove `let`
                 let tcx = self.tcx;
                 self.worklist.extend(
-                    tcx.provided_trait_methods(trait_def_id)
-                        .map(|assoc| tcx.hir().as_local_hir_id(assoc.def_id).unwrap()),
+                    tcx.provided_trait_methods(trait_def_id).map(|assoc| {
+                        tcx.hir().as_local_hir_id(assoc.def_id.expect_local()).unwrap()
+                    }),
                 );
             }
         }
@@ -400,7 +403,8 @@ fn reachable_set<'tcx>(tcx: TyCtxt<'tcx>, crate_num: CrateNum) -> &'tcx HirIdSet
     reachable_context.worklist.extend(access_levels.map.iter().map(|(id, _)| *id));
     for item in tcx.lang_items().items().iter() {
         if let Some(did) = *item {
-            if let Some(hir_id) = tcx.hir().as_local_hir_id(did) {
+            if let Some(hir_id) = did.as_local().map(|did| tcx.hir().as_local_hir_id(did).unwrap())
+            {
                 reachable_context.worklist.push(hir_id);
             }
         }
diff --git a/src/librustc_passes/region.rs b/src/librustc_passes/region.rs
index ecae5bc57cc..3a9edd0410e 100644
--- a/src/librustc_passes/region.rs
+++ b/src/librustc_passes/region.rs
@@ -807,7 +807,7 @@ fn region_scope_tree(tcx: TyCtxt<'_>, def_id: DefId) -> &ScopeTree {
         return tcx.region_scope_tree(closure_base_def_id);
     }
 
-    let id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    let id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
     let scope_tree = if let Some(body_id) = tcx.hir().maybe_body_owned_by(id) {
         let mut visitor = RegionResolutionVisitor {
             tcx,
diff --git a/src/librustc_passes/upvars.rs b/src/librustc_passes/upvars.rs
index fd046d9b66b..0cdc4f5bd8f 100644
--- a/src/librustc_passes/upvars.rs
+++ b/src/librustc_passes/upvars.rs
@@ -15,7 +15,7 @@ pub fn provide(providers: &mut Providers<'_>) {
             return None;
         }
 
-        let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+        let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
         let body = tcx.hir().body(tcx.hir().maybe_body_owned_by(hir_id)?);
 
         let mut local_collector = LocalCollector::default();
diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs
index e8d016aa07a..c268189c5b2 100644
--- a/src/librustc_privacy/lib.rs
+++ b/src/librustc_privacy/lib.rs
@@ -235,7 +235,7 @@ fn def_id_visibility<'tcx>(
     tcx: TyCtxt<'tcx>,
     def_id: DefId,
 ) -> (ty::Visibility, Span, &'static str) {
-    match tcx.hir().as_local_hir_id(def_id) {
+    match def_id.as_local().map(|def_id| tcx.hir().as_local_hir_id(def_id).unwrap()) {
         Some(hir_id) => {
             let vis = match tcx.hir().get(hir_id) {
                 Node::Item(item) => &item.vis,
@@ -445,7 +445,9 @@ impl VisibilityLike for Option<AccessLevel> {
     const SHALLOW: bool = true;
     fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self {
         cmp::min(
-            if let Some(hir_id) = find.tcx.hir().as_local_hir_id(def_id) {
+            if let Some(hir_id) =
+                def_id.as_local().map(|def_id| find.tcx.hir().as_local_hir_id(def_id).unwrap())
+            {
                 find.access_levels.map.get(&hir_id).cloned()
             } else {
                 Self::MAX
@@ -532,7 +534,7 @@ impl EmbargoVisitor<'tcx> {
 
     fn update_macro_reachable_mod(&mut self, reachable_mod: hir::HirId, defining_mod: DefId) {
         let module_def_id = self.tcx.hir().local_def_id(reachable_mod);
-        let module = self.tcx.hir().get_module(module_def_id.to_def_id()).0;
+        let module = self.tcx.hir().get_module(module_def_id).0;
         for item_id in module.item_ids {
             let hir_id = item_id.id;
             let item_def_id = self.tcx.hir().local_def_id(hir_id);
@@ -547,7 +549,10 @@ impl EmbargoVisitor<'tcx> {
                 if export.vis.is_accessible_from(defining_mod, self.tcx) {
                     if let Res::Def(def_kind, def_id) = export.res {
                         let vis = def_id_visibility(self.tcx, def_id).0;
-                        if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
+                        if let Some(hir_id) = def_id
+                            .as_local()
+                            .map(|def_id| self.tcx.hir().as_local_hir_id(def_id).unwrap())
+                        {
                             self.update_macro_reachable_def(hir_id, def_kind, vis, defining_mod);
                         }
                     }
@@ -654,7 +659,9 @@ impl EmbargoVisitor<'tcx> {
                 // If the module is `self`, i.e. the current crate,
                 // there will be no corresponding item.
                 .filter(|def_id| def_id.index != CRATE_DEF_INDEX || def_id.krate != LOCAL_CRATE)
-                .and_then(|def_id| self.tcx.hir().as_local_hir_id(def_id))
+                .and_then(|def_id| {
+                    def_id.as_local().map(|def_id| self.tcx.hir().as_local_hir_id(def_id).unwrap())
+                })
                 .map(|module_hir_id| self.tcx.hir().expect_item(module_hir_id))
             {
                 if let hir::ItemKind::Mod(m) = &item.kind {
@@ -908,7 +915,10 @@ impl Visitor<'tcx> for EmbargoVisitor<'tcx> {
                 for export in exports.iter() {
                     if export.vis == ty::Visibility::Public {
                         if let Some(def_id) = export.res.opt_def_id() {
-                            if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
+                            if let Some(hir_id) = def_id
+                                .as_local()
+                                .map(|def_id| self.tcx.hir().as_local_hir_id(def_id).unwrap())
+                            {
                                 self.update(hir_id, Some(AccessLevel::Exported));
                             }
                         }
@@ -996,10 +1006,11 @@ impl DefIdVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'tcx> {
         self.ev.tcx
     }
     fn visit_def_id(&mut self, def_id: DefId, _kind: &str, _descr: &dyn fmt::Display) -> bool {
-        if let Some(hir_id) = self.ev.tcx.hir().as_local_hir_id(def_id) {
+        if let Some(def_id) = def_id.as_local() {
+            let hir_id = self.ev.tcx.hir().as_local_hir_id(def_id).unwrap();
             if let ((ty::Visibility::Public, ..), _)
             | (_, Some(AccessLevel::ReachableFromImplTrait)) =
-                (def_id_visibility(self.tcx(), def_id), self.access_level)
+                (def_id_visibility(self.tcx(), def_id.to_def_id()), self.access_level)
             {
                 self.ev.update(hir_id, self.access_level);
             }
@@ -1443,10 +1454,10 @@ impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
 
         // A path can only be private if:
         // it's in this crate...
-        if let Some(hir_id) = self.tcx.hir().as_local_hir_id(did) {
+        if let Some(did) = did.as_local() {
             // .. and it corresponds to a private type in the AST (this returns
             // `None` for type parameters).
-            match self.tcx.hir().find(hir_id) {
+            match self.tcx.hir().find(self.tcx.hir().as_local_hir_id(did).unwrap()) {
                 Some(Node::Item(ref item)) => !item.vis.node.is_pub(),
                 Some(_) | None => false,
             }
@@ -1564,8 +1575,8 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> {
                     |tr| {
                         let did = tr.path.res.def_id();
 
-                        if let Some(hir_id) = self.tcx.hir().as_local_hir_id(did) {
-                            self.trait_is_public(hir_id)
+                        if let Some(did) = did.as_local() {
+                            self.trait_is_public(self.tcx.hir().as_local_hir_id(did).unwrap())
                         } else {
                             true // external traits must be public
                         }
@@ -1825,8 +1836,8 @@ impl SearchInterfaceForPrivateItemsVisitor<'tcx> {
             );
         }
 
-        let hir_id = match self.tcx.hir().as_local_hir_id(def_id) {
-            Some(hir_id) => hir_id,
+        let hir_id = match def_id.as_local() {
+            Some(def_id) => self.tcx.hir().as_local_hir_id(def_id).unwrap(),
             None => return false,
         };
 
@@ -2070,7 +2081,7 @@ fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: DefId) {
         current_item: None,
         empty_tables: &empty_tables,
     };
-    let (module, span, hir_id) = tcx.hir().get_module(module_def_id);
+    let (module, span, hir_id) = tcx.hir().get_module(module_def_id.expect_local());
 
     intravisit::walk_mod(&mut visitor, module, hir_id);
 
diff --git a/src/librustc_resolve/late/lifetimes.rs b/src/librustc_resolve/late/lifetimes.rs
index 5839b914906..225e6da5ced 100644
--- a/src/librustc_resolve/late/lifetimes.rs
+++ b/src/librustc_resolve/late/lifetimes.rs
@@ -596,7 +596,10 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
                         // In the future, this should be fixed and this error should be removed.
                         let def = self.map.defs.get(&lifetime.hir_id).cloned();
                         if let Some(Region::LateBound(_, def_id, _)) = def {
-                            if let Some(hir_id) = self.tcx.hir().as_local_hir_id(def_id) {
+                            if let Some(hir_id) = def_id
+                                .as_local()
+                                .map(|def_id| self.tcx.hir().as_local_hir_id(def_id).unwrap())
+                            {
                                 // Ensure that the parent of the def is an item, not HRTB
                                 let parent_id = self.tcx.hir().get_parent_node(hir_id);
                                 let parent_impl_id = hir::ImplItemId { hir_id: parent_id };
@@ -1166,7 +1169,8 @@ fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body<'_>) {
                     if let Some(def) =
                         lifetimes.get(&hir::ParamName::Plain(label.normalize_to_macros_2_0()))
                     {
-                        let hir_id = tcx.hir().as_local_hir_id(def.id().unwrap()).unwrap();
+                        let hir_id =
+                            tcx.hir().as_local_hir_id(def.id().unwrap().expect_local()).unwrap();
 
                         signal_shadowing_problem(
                             tcx,
@@ -1537,7 +1541,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
 
             match lifetimeuseset {
                 Some(LifetimeUseSet::One(lifetime)) => {
-                    let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
+                    let hir_id = self.tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
                     debug!("hir id first={:?}", hir_id);
                     if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
                         Node::Lifetime(hir_lifetime) => Some((
@@ -1556,8 +1560,9 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
                         }
 
                         if let Some(parent_def_id) = self.tcx.parent(def_id) {
-                            if let Some(parent_hir_id) =
-                                self.tcx.hir().as_local_hir_id(parent_def_id)
+                            if let Some(parent_hir_id) = parent_def_id
+                                .as_local()
+                                .map(|def_id| self.tcx.hir().as_local_hir_id(def_id).unwrap())
                             {
                                 // lifetimes in `derive` expansions don't count (Issue #53738)
                                 if self
@@ -1600,7 +1605,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
                     debug!("not one use lifetime");
                 }
                 None => {
-                    let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
+                    let hir_id = self.tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
                     if let Some((id, span, name)) = match self.tcx.hir().get(hir_id) {
                         Node::Lifetime(hir_lifetime) => Some((
                             hir_lifetime.hir_id,
@@ -1955,7 +1960,9 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
             };
 
             let map = &self.map;
-            let unsubst = if let Some(id) = self.tcx.hir().as_local_hir_id(def_id) {
+            let unsubst = if let Some(id) =
+                def_id.as_local().map(|def_id| self.tcx.hir().as_local_hir_id(def_id).unwrap())
+            {
                 &map.object_lifetime_defaults[&id]
             } else {
                 let tcx = self.tcx;
@@ -2661,7 +2668,11 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
 
                 Scope::Binder { ref lifetimes, s, .. } => {
                     if let Some(&def) = lifetimes.get(&param.name.normalize_to_macros_2_0()) {
-                        let hir_id = self.tcx.hir().as_local_hir_id(def.id().unwrap()).unwrap();
+                        let hir_id = self
+                            .tcx
+                            .hir()
+                            .as_local_hir_id(def.id().unwrap().expect_local())
+                            .unwrap();
 
                         signal_shadowing_problem(
                             self.tcx,
diff --git a/src/librustc_symbol_mangling/lib.rs b/src/librustc_symbol_mangling/lib.rs
index e97723d9fc0..c255b8304e5 100644
--- a/src/librustc_symbol_mangling/lib.rs
+++ b/src/librustc_symbol_mangling/lib.rs
@@ -165,22 +165,18 @@ fn compute_symbol_name(
 
     debug!("symbol_name(def_id={:?}, substs={:?})", def_id, substs);
 
-    let hir_id = tcx.hir().as_local_hir_id(def_id);
-
-    if def_id.is_local() {
-        if tcx.plugin_registrar_fn(LOCAL_CRATE) == Some(def_id) {
+    // FIXME(eddyb) Precompute a custom symbol name based on attributes.
+    let is_foreign = if let Some(def_id) = def_id.as_local() {
+        if tcx.plugin_registrar_fn(LOCAL_CRATE) == Some(def_id.to_def_id()) {
             let disambiguator = tcx.sess.local_crate_disambiguator();
             return tcx.sess.generate_plugin_registrar_symbol(disambiguator);
         }
-        if tcx.proc_macro_decls_static(LOCAL_CRATE) == Some(def_id) {
+        if tcx.proc_macro_decls_static(LOCAL_CRATE) == Some(def_id.to_def_id()) {
             let disambiguator = tcx.sess.local_crate_disambiguator();
             return tcx.sess.generate_proc_macro_decls_symbol(disambiguator);
         }
-    }
-
-    // FIXME(eddyb) Precompute a custom symbol name based on attributes.
-    let is_foreign = if let Some(id) = hir_id {
-        match tcx.hir().get(id) {
+        let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+        match tcx.hir().get(hir_id) {
             Node::ForeignItem(_) => true,
             _ => false,
         }
diff --git a/src/librustc_trait_selection/opaque_types.rs b/src/librustc_trait_selection/opaque_types.rs
index fffb41f8cb7..16fef2f6e36 100644
--- a/src/librustc_trait_selection/opaque_types.rs
+++ b/src/librustc_trait_selection/opaque_types.rs
@@ -3,7 +3,7 @@ use crate::traits::{self, PredicateObligation};
 use rustc_data_structures::fx::FxHashMap;
 use rustc_data_structures::sync::Lrc;
 use rustc_hir as hir;
-use rustc_hir::def_id::{DefId, DefIdMap};
+use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId};
 use rustc_hir::Node;
 use rustc_infer::infer::error_reporting::unexpected_hidden_region_diagnostic;
 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
@@ -1036,7 +1036,9 @@ impl<'a, 'tcx> Instantiator<'a, 'tcx> {
                     //     let x = || foo(); // returns the Opaque assoc with `foo`
                     // }
                     // ```
-                    if let Some(opaque_hir_id) = tcx.hir().as_local_hir_id(def_id) {
+                    if let Some(opaque_hir_id) =
+                        def_id.as_local().map(|def_id| tcx.hir().as_local_hir_id(def_id).unwrap())
+                    {
                         let parent_def_id = self.parent_def_id;
                         let def_scope_default = || {
                             let opaque_parent_hir_id = tcx.hir().get_parent_item(opaque_hir_id);
@@ -1057,14 +1059,22 @@ impl<'a, 'tcx> Instantiator<'a, 'tcx> {
                                     origin,
                                     ..
                                 }) => (
-                                    may_define_opaque_type(tcx, self.parent_def_id, opaque_hir_id),
+                                    may_define_opaque_type(
+                                        tcx,
+                                        self.parent_def_id.expect_local(),
+                                        opaque_hir_id,
+                                    ),
                                     origin,
                                 ),
                                 _ => (def_scope_default(), hir::OpaqueTyOrigin::TypeAlias),
                             },
                             Some(Node::ImplItem(item)) => match item.kind {
                                 hir::ImplItemKind::OpaqueTy(_) => (
-                                    may_define_opaque_type(tcx, self.parent_def_id, opaque_hir_id),
+                                    may_define_opaque_type(
+                                        tcx,
+                                        self.parent_def_id.expect_local(),
+                                        opaque_hir_id,
+                                    ),
                                     hir::OpaqueTyOrigin::TypeAlias,
                                 ),
                                 _ => (def_scope_default(), hir::OpaqueTyOrigin::TypeAlias),
@@ -1201,10 +1211,14 @@ impl<'a, 'tcx> Instantiator<'a, 'tcx> {
 /// }
 /// ```
 ///
-/// Here, `def_id` is the `DefId` of the defining use of the opaque type (e.g., `f1` or `f2`),
+/// Here, `def_id` is the `LocalDefId` of the defining use of the opaque type (e.g., `f1` or `f2`),
 /// and `opaque_hir_id` is the `HirId` of the definition of the opaque type `Baz`.
 /// For the above example, this function returns `true` for `f1` and `false` for `f2`.
-pub fn may_define_opaque_type(tcx: TyCtxt<'_>, def_id: DefId, opaque_hir_id: hir::HirId) -> bool {
+pub fn may_define_opaque_type(
+    tcx: TyCtxt<'_>,
+    def_id: LocalDefId,
+    opaque_hir_id: hir::HirId,
+) -> bool {
     let mut hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
 
     // Named opaque types can be defined by any siblings or children of siblings.
diff --git a/src/librustc_trait_selection/traits/error_reporting/mod.rs b/src/librustc_trait_selection/traits/error_reporting/mod.rs
index 8a9017960fb..c6c9b068a5e 100644
--- a/src/librustc_trait_selection/traits/error_reporting/mod.rs
+++ b/src/librustc_trait_selection/traits/error_reporting/mod.rs
@@ -507,7 +507,8 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
                             self.tcx.sess.source_map().guess_head_span(
                                 self.tcx.hir().span_if_local(closure_def_id).unwrap(),
                             );
-                        let hir_id = self.tcx.hir().as_local_hir_id(closure_def_id).unwrap();
+                        let hir_id =
+                            self.tcx.hir().as_local_hir_id(closure_def_id.expect_local()).unwrap();
                         let mut err = struct_span_err!(
                             self.tcx.sess,
                             closure_span,
diff --git a/src/librustc_trait_selection/traits/error_reporting/suggestions.rs b/src/librustc_trait_selection/traits/error_reporting/suggestions.rs
index e579393434e..b6d592b3143 100644
--- a/src/librustc_trait_selection/traits/error_reporting/suggestions.rs
+++ b/src/librustc_trait_selection/traits/error_reporting/suggestions.rs
@@ -430,7 +430,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
             };
 
         let hir = self.tcx.hir();
-        let hir_id = hir.as_local_hir_id(def_id)?;
+        let hir_id = hir.as_local_hir_id(def_id.as_local()?)?;
         let parent_node = hir.get_parent_node(hir_id);
         match hir.find(parent_node) {
             Some(hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Local(local), .. })) => {
@@ -1209,7 +1209,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
         let span = self.tcx.def_span(generator_did);
 
         // Do not ICE on closure typeck (#66868).
-        if hir.as_local_hir_id(generator_did).is_none() {
+        if !generator_did.is_local() {
             return false;
         }
 
@@ -1235,8 +1235,9 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
             }
         };
 
-        let generator_body = hir
-            .as_local_hir_id(generator_did)
+        let generator_body = generator_did
+            .as_local()
+            .map(|def_id| hir.as_local_hir_id(def_id).unwrap())
             .and_then(|hir_id| hir.maybe_body_owned_by(hir_id))
             .map(|body_id| hir.body(body_id));
         let mut visitor = AwaitsVisitor::default();
@@ -1386,6 +1387,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
                         GeneratorKind::Async(AsyncGeneratorKind::Fn) => self
                             .tcx
                             .parent(generator_did)
+                            .and_then(|parent_did| parent_did.as_local())
                             .and_then(|parent_did| hir.as_local_hir_id(parent_did))
                             .and_then(|parent_hir_id| hir.opt_name(parent_hir_id))
                             .map(|name| {
diff --git a/src/librustc_trait_selection/traits/specialize/mod.rs b/src/librustc_trait_selection/traits/specialize/mod.rs
index fabd8c89b72..95bc64fdaff 100644
--- a/src/librustc_trait_selection/traits/specialize/mod.rs
+++ b/src/librustc_trait_selection/traits/specialize/mod.rs
@@ -17,7 +17,7 @@ use crate::traits::select::IntercrateAmbiguityCause;
 use crate::traits::{self, coherence, FutureCompatOverlapErrorKind, ObligationCause, TraitEngine};
 use rustc_data_structures::fx::FxHashSet;
 use rustc_errors::struct_span_err;
-use rustc_hir::def_id::DefId;
+use rustc_hir::def_id::{DefId, LocalDefId};
 use rustc_middle::lint::LintDiagnosticBuilder;
 use rustc_middle::ty::subst::{InternalSubsts, Subst, SubstsRef};
 use rustc_middle::ty::{self, TyCtxt};
@@ -271,9 +271,9 @@ pub(super) fn specialization_graph_provider(
         .sort_unstable_by_key(|def_id| (-(def_id.krate.as_u32() as i64), def_id.index.index()));
 
     for impl_def_id in trait_impls {
-        if impl_def_id.is_local() {
+        if let Some(impl_def_id) = impl_def_id.as_local() {
             // This is where impl overlap checking happens:
-            let insert_result = sg.insert(tcx, impl_def_id);
+            let insert_result = sg.insert(tcx, impl_def_id.to_def_id());
             // Report error if there was one.
             let (overlap, used_to_be_allowed) = match insert_result {
                 Err(overlap) => (Some(overlap), None),
@@ -296,11 +296,11 @@ pub(super) fn specialization_graph_provider(
 fn report_overlap_conflict(
     tcx: TyCtxt<'_>,
     overlap: OverlapError,
-    impl_def_id: DefId,
+    impl_def_id: LocalDefId,
     used_to_be_allowed: Option<FutureCompatOverlapErrorKind>,
     sg: &mut specialization_graph::Graph,
 ) {
-    let impl_polarity = tcx.impl_polarity(impl_def_id);
+    let impl_polarity = tcx.impl_polarity(impl_def_id.to_def_id());
     let other_polarity = tcx.impl_polarity(overlap.with_impl);
     match (impl_polarity, other_polarity) {
         (ty::ImplPolarity::Negative, ty::ImplPolarity::Positive) => {
@@ -308,7 +308,7 @@ fn report_overlap_conflict(
                 tcx,
                 &overlap,
                 impl_def_id,
-                impl_def_id,
+                impl_def_id.to_def_id(),
                 overlap.with_impl,
                 sg,
             );
@@ -320,7 +320,7 @@ fn report_overlap_conflict(
                 &overlap,
                 impl_def_id,
                 overlap.with_impl,
-                impl_def_id,
+                impl_def_id.to_def_id(),
                 sg,
             );
         }
@@ -334,13 +334,15 @@ fn report_overlap_conflict(
 fn report_negative_positive_conflict(
     tcx: TyCtxt<'_>,
     overlap: &OverlapError,
-    local_impl_def_id: DefId,
+    local_impl_def_id: LocalDefId,
     negative_impl_def_id: DefId,
     positive_impl_def_id: DefId,
     sg: &mut specialization_graph::Graph,
 ) {
-    let impl_span =
-        tcx.sess.source_map().guess_head_span(tcx.span_of_impl(local_impl_def_id).unwrap());
+    let impl_span = tcx
+        .sess
+        .source_map()
+        .guess_head_span(tcx.span_of_impl(local_impl_def_id.to_def_id()).unwrap());
 
     let mut err = struct_span_err!(
         tcx.sess,
@@ -382,11 +384,12 @@ fn report_negative_positive_conflict(
 fn report_conflicting_impls(
     tcx: TyCtxt<'_>,
     overlap: OverlapError,
-    impl_def_id: DefId,
+    impl_def_id: LocalDefId,
     used_to_be_allowed: Option<FutureCompatOverlapErrorKind>,
     sg: &mut specialization_graph::Graph,
 ) {
-    let impl_span = tcx.sess.source_map().guess_head_span(tcx.span_of_impl(impl_def_id).unwrap());
+    let impl_span =
+        tcx.sess.source_map().guess_head_span(tcx.span_of_impl(impl_def_id.to_def_id()).unwrap());
 
     // Work to be done after we've built the DiagnosticBuilder. We have to define it
     // now because the struct_lint methods don't return back the DiagnosticBuilder
diff --git a/src/librustc_traits/lowering/environment.rs b/src/librustc_traits/lowering/environment.rs
index 612ab9b70eb..b598b6f4fb4 100644
--- a/src/librustc_traits/lowering/environment.rs
+++ b/src/librustc_traits/lowering/environment.rs
@@ -174,7 +174,7 @@ crate fn environment(tcx: TyCtxt<'_>, def_id: DefId) -> Environment<'_> {
         // could bound lifetimes.
         .map(Clause::ForAll);
 
-    let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
     let node = tcx.hir().get(hir_id);
 
     enum NodeKind {
diff --git a/src/librustc_ty/ty.rs b/src/librustc_ty/ty.rs
index a3bf297db80..1e215ebc42f 100644
--- a/src/librustc_ty/ty.rs
+++ b/src/librustc_ty/ty.rs
@@ -128,7 +128,7 @@ fn associated_item_from_impl_item_ref(
 }
 
 fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItem {
-    let id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    let id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
     let parent_id = tcx.hir().get_parent_item(id);
     let parent_def_id = tcx.hir().local_def_id(parent_id);
     let parent_item = tcx.hir().expect_item(parent_id);
@@ -166,7 +166,7 @@ fn associated_item(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItem {
 }
 
 fn impl_defaultness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::Defaultness {
-    let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
     let item = tcx.hir().expect_item(hir_id);
     if let hir::ItemKind::Impl { defaultness, .. } = item.kind {
         defaultness
@@ -200,7 +200,7 @@ fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AdtSizedConstrain
 }
 
 fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: DefId) -> &[DefId] {
-    let id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    let id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
     let item = tcx.hir().expect_item(id);
     match item.kind {
         hir::ItemKind::Trait(.., ref trait_item_refs) => tcx.arena.alloc_from_iter(
@@ -265,9 +265,12 @@ fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> {
     let unnormalized_env =
         ty::ParamEnv::new(tcx.intern_predicates(&predicates), traits::Reveal::UserFacing, None);
 
-    let body_id = tcx.hir().as_local_hir_id(def_id).map_or(hir::CRATE_HIR_ID, |id| {
-        tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
-    });
+    let body_id = def_id
+        .as_local()
+        .map(|def_id| tcx.hir().as_local_hir_id(def_id).unwrap())
+        .map_or(hir::CRATE_HIR_ID, |id| {
+            tcx.hir().maybe_body_owned_by(id).map_or(id, |body| body.hir_id)
+        });
     let cause = traits::ObligationCause::misc(tcx.def_span(def_id), body_id);
     traits::normalize_param_env_or_error(tcx, def_id, unnormalized_env, cause)
 }
@@ -352,10 +355,7 @@ fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Ty<'_>> {
 
 /// Check if a function is async.
 fn asyncness(tcx: TyCtxt<'_>, def_id: DefId) -> hir::IsAsync {
-    let hir_id = tcx
-        .hir()
-        .as_local_hir_id(def_id)
-        .unwrap_or_else(|| bug!("asyncness: expected local `DefId`, got `{:?}`", def_id));
+    let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
 
     let node = tcx.hir().get(hir_id);
 
diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs
index cd2f3af200e..1de01168c2f 100644
--- a/src/librustc_typeck/astconv.rs
+++ b/src/librustc_typeck/astconv.rs
@@ -15,7 +15,7 @@ use rustc_errors::ErrorReported;
 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId, FatalError};
 use rustc_hir as hir;
 use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
-use rustc_hir::def_id::DefId;
+use rustc_hir::def_id::{DefId, LocalDefId};
 use rustc_hir::intravisit::{walk_generics, Visitor as _};
 use rustc_hir::lang_items::SizedTraitLangItem;
 use rustc_hir::{Constness, GenericArg, GenericArgs};
@@ -153,7 +153,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
             Some(rl::Region::Static) => tcx.lifetimes.re_static,
 
             Some(rl::Region::LateBound(debruijn, id, _)) => {
-                let name = lifetime_name(id);
+                let name = lifetime_name(id.expect_local());
                 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrNamed(id, name)))
             }
 
@@ -162,12 +162,12 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
             }
 
             Some(rl::Region::EarlyBound(index, id, _)) => {
-                let name = lifetime_name(id);
+                let name = lifetime_name(id.expect_local());
                 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: id, index, name }))
             }
 
             Some(rl::Region::Free(scope, id)) => {
-                let name = lifetime_name(id);
+                let name = lifetime_name(id.expect_local());
                 tcx.mk_region(ty::ReFree(ty::FreeRegion {
                     scope,
                     bound_region: ty::BrNamed(id, name),
@@ -1974,7 +1974,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
     // any ambiguity.
     fn find_bound_for_assoc_item(
         &self,
-        ty_param_def_id: DefId,
+        ty_param_def_id: LocalDefId,
         assoc_name: ast::Ident,
         span: Span,
     ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> {
@@ -1985,7 +1985,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
             ty_param_def_id, assoc_name, span,
         );
 
-        let predicates = &self.get_type_parameter_bounds(span, ty_param_def_id).predicates;
+        let predicates =
+            &self.get_type_parameter_bounds(span, ty_param_def_id.to_def_id()).predicates;
 
         debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
 
@@ -2236,7 +2237,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
             (
                 &ty::Param(_),
                 Res::SelfTy(Some(param_did), None) | Res::Def(DefKind::TyParam, param_did),
-            ) => self.find_bound_for_assoc_item(param_did, assoc_ident, span)?,
+            ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
             _ => {
                 if variant_resolution.is_some() {
                     // Variant in type position
@@ -2372,7 +2373,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
             debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
 
             let parent_def_id = def_id
-                .and_then(|def_id| tcx.hir().as_local_hir_id(def_id))
+                .and_then(|def_id| {
+                    def_id.as_local().map(|def_id| tcx.hir().as_local_hir_id(def_id).unwrap())
+                })
                 .map(|hir_id| tcx.hir().get_parent_did(hir_id).to_def_id());
 
             debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
@@ -2666,7 +2669,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
                 assert_eq!(opt_self_ty, None);
                 self.prohibit_generics(path.segments);
 
-                let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+                let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
                 let item_id = tcx.hir().get_parent_node(hir_id);
                 let item_def_id = tcx.hir().local_def_id(item_id);
                 let generics = tcx.generics_of(item_def_id);
diff --git a/src/librustc_typeck/check/coercion.rs b/src/librustc_typeck/check/coercion.rs
index 6fc5039f16d..9da3dd0408a 100644
--- a/src/librustc_typeck/check/coercion.rs
+++ b/src/librustc_typeck/check/coercion.rs
@@ -1393,7 +1393,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
                 let ty = AstConv::ast_ty_to_ty(fcx, ty);
                 // Get the `impl Trait`'s `DefId`.
                 if let ty::Opaque(def_id, _) = ty.kind {
-                    let hir_id = fcx.tcx.hir().as_local_hir_id(def_id).unwrap();
+                    let hir_id = fcx.tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
                     // Get the `impl Trait`'s `Item` so that we can get its trait bounds and
                     // get the `Trait`'s `DefId`.
                     if let hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds, .. }) =
diff --git a/src/librustc_typeck/check/compare_method.rs b/src/librustc_typeck/check/compare_method.rs
index 82c8a5543eb..dbdb26afaec 100644
--- a/src/librustc_typeck/check/compare_method.rs
+++ b/src/librustc_typeck/check/compare_method.rs
@@ -76,7 +76,7 @@ fn compare_predicate_entailment<'tcx>(
     // This node-id should be used for the `body_id` field on each
     // `ObligationCause` (and the `FnCtxt`). This is what
     // `regionck_item` expects.
-    let impl_m_hir_id = tcx.hir().as_local_hir_id(impl_m.def_id).unwrap();
+    let impl_m_hir_id = tcx.hir().as_local_hir_id(impl_m.def_id.expect_local()).unwrap();
 
     let cause = ObligationCause {
         span: impl_m_span,
@@ -399,7 +399,7 @@ fn extract_spans_for_error_reporting<'a, 'tcx>(
     trait_sig: ty::FnSig<'tcx>,
 ) -> (Span, Option<Span>) {
     let tcx = infcx.tcx;
-    let impl_m_hir_id = tcx.hir().as_local_hir_id(impl_m.def_id).unwrap();
+    let impl_m_hir_id = tcx.hir().as_local_hir_id(impl_m.def_id.expect_local()).unwrap();
     let (impl_m_output, impl_m_iter) = match tcx.hir().expect_impl_item(impl_m_hir_id).kind {
         ImplItemKind::Fn(ref impl_m_sig, _) => {
             (&impl_m_sig.decl.output, impl_m_sig.decl.inputs.iter())
@@ -409,7 +409,9 @@ fn extract_spans_for_error_reporting<'a, 'tcx>(
 
     match *terr {
         TypeError::Mutability => {
-            if let Some(trait_m_hir_id) = tcx.hir().as_local_hir_id(trait_m.def_id) {
+            if let Some(trait_m_hir_id) =
+                trait_m.def_id.as_local().map(|def_id| tcx.hir().as_local_hir_id(def_id).unwrap())
+            {
                 let trait_m_iter = match tcx.hir().expect_trait_item(trait_m_hir_id).kind {
                     TraitItemKind::Fn(ref trait_m_sig, _) => trait_m_sig.decl.inputs.iter(),
                     _ => bug!("{:?} is not a TraitItemKind::Fn", trait_m),
@@ -436,7 +438,9 @@ fn extract_spans_for_error_reporting<'a, 'tcx>(
             }
         }
         TypeError::Sorts(ExpectedFound { .. }) => {
-            if let Some(trait_m_hir_id) = tcx.hir().as_local_hir_id(trait_m.def_id) {
+            if let Some(trait_m_hir_id) =
+                trait_m.def_id.as_local().map(|def_id| tcx.hir().as_local_hir_id(def_id).unwrap())
+            {
                 let (trait_m_output, trait_m_iter) =
                     match tcx.hir().expect_trait_item(trait_m_hir_id).kind {
                         TraitItemKind::Fn(ref trait_m_sig, _) => {
@@ -587,33 +591,34 @@ fn compare_number_of_generics<'tcx>(
         if impl_count != trait_count {
             err_occurred = true;
 
-            let (trait_spans, impl_trait_spans) =
-                if let Some(trait_hir_id) = tcx.hir().as_local_hir_id(trait_.def_id) {
-                    let trait_item = tcx.hir().expect_trait_item(trait_hir_id);
-                    if trait_item.generics.params.is_empty() {
-                        (Some(vec![trait_item.generics.span]), vec![])
-                    } else {
-                        let arg_spans: Vec<Span> =
-                            trait_item.generics.params.iter().map(|p| p.span).collect();
-                        let impl_trait_spans: Vec<Span> = trait_item
-                            .generics
-                            .params
-                            .iter()
-                            .filter_map(|p| match p.kind {
-                                GenericParamKind::Type {
-                                    synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
-                                    ..
-                                } => Some(p.span),
-                                _ => None,
-                            })
-                            .collect();
-                        (Some(arg_spans), impl_trait_spans)
-                    }
+            let (trait_spans, impl_trait_spans) = if let Some(trait_hir_id) =
+                trait_.def_id.as_local().map(|def_id| tcx.hir().as_local_hir_id(def_id).unwrap())
+            {
+                let trait_item = tcx.hir().expect_trait_item(trait_hir_id);
+                if trait_item.generics.params.is_empty() {
+                    (Some(vec![trait_item.generics.span]), vec![])
                 } else {
-                    (trait_span.map(|s| vec![s]), vec![])
-                };
+                    let arg_spans: Vec<Span> =
+                        trait_item.generics.params.iter().map(|p| p.span).collect();
+                    let impl_trait_spans: Vec<Span> = trait_item
+                        .generics
+                        .params
+                        .iter()
+                        .filter_map(|p| match p.kind {
+                            GenericParamKind::Type {
+                                synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
+                                ..
+                            } => Some(p.span),
+                            _ => None,
+                        })
+                        .collect();
+                    (Some(arg_spans), impl_trait_spans)
+                }
+            } else {
+                (trait_span.map(|s| vec![s]), vec![])
+            };
 
-            let impl_hir_id = tcx.hir().as_local_hir_id(impl_.def_id).unwrap();
+            let impl_hir_id = tcx.hir().as_local_hir_id(impl_.def_id.expect_local()).unwrap();
             let impl_item = tcx.hir().expect_impl_item(impl_hir_id);
             let impl_item_impl_trait_spans: Vec<Span> = impl_item
                 .generics
@@ -704,8 +709,8 @@ fn compare_number_of_method_arguments<'tcx>(
     let trait_number_args = trait_m_fty.inputs().skip_binder().len();
     let impl_number_args = impl_m_fty.inputs().skip_binder().len();
     if trait_number_args != impl_number_args {
-        let trait_m_hir_id = tcx.hir().as_local_hir_id(trait_m.def_id);
-        let trait_span = if let Some(trait_id) = trait_m_hir_id {
+        let trait_span = if let Some(def_id) = trait_m.def_id.as_local() {
+            let trait_id = tcx.hir().as_local_hir_id(def_id).unwrap();
             match tcx.hir().expect_trait_item(trait_id).kind {
                 TraitItemKind::Fn(ref trait_m_sig, _) => {
                     let pos = if trait_number_args > 0 { trait_number_args - 1 } else { 0 };
@@ -728,7 +733,7 @@ fn compare_number_of_method_arguments<'tcx>(
         } else {
             trait_item_span
         };
-        let impl_m_hir_id = tcx.hir().as_local_hir_id(impl_m.def_id).unwrap();
+        let impl_m_hir_id = tcx.hir().as_local_hir_id(impl_m.def_id.expect_local()).unwrap();
         let impl_span = match tcx.hir().expect_impl_item(impl_m_hir_id).kind {
             ImplItemKind::Fn(ref impl_m_sig, _) => {
                 let pos = if impl_number_args > 0 { impl_number_args - 1 } else { 0 };
@@ -810,7 +815,7 @@ fn compare_synthetic_generics<'tcx>(
         impl_m_type_params.zip(trait_m_type_params)
     {
         if impl_synthetic != trait_synthetic {
-            let impl_hir_id = tcx.hir().as_local_hir_id(impl_def_id).unwrap();
+            let impl_hir_id = tcx.hir().as_local_hir_id(impl_def_id.expect_local()).unwrap();
             let impl_span = tcx.hir().span(impl_hir_id);
             let trait_span = tcx.def_span(trait_def_id);
             let mut err = struct_span_err!(
@@ -831,10 +836,10 @@ fn compare_synthetic_generics<'tcx>(
                         // FIXME: this is obviously suboptimal since the name can already be used
                         // as another generic argument
                         let new_name = tcx.sess.source_map().span_to_snippet(trait_span).ok()?;
-                        let trait_m = tcx.hir().as_local_hir_id(trait_m.def_id)?;
+                        let trait_m = tcx.hir().as_local_hir_id(trait_m.def_id.as_local()?)?;
                         let trait_m = tcx.hir().trait_item(hir::TraitItemId { hir_id: trait_m });
 
-                        let impl_m = tcx.hir().as_local_hir_id(impl_m.def_id)?;
+                        let impl_m = tcx.hir().as_local_hir_id(impl_m.def_id.as_local()?)?;
                         let impl_m = tcx.hir().impl_item(hir::ImplItemId { hir_id: impl_m });
 
                         // in case there are no generics, take the spot between the function name
@@ -868,7 +873,7 @@ fn compare_synthetic_generics<'tcx>(
                 (None, Some(hir::SyntheticTyParamKind::ImplTrait)) => {
                     err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
                     (|| {
-                        let impl_m = tcx.hir().as_local_hir_id(impl_m.def_id)?;
+                        let impl_m = tcx.hir().as_local_hir_id(impl_m.def_id.as_local()?)?;
                         let impl_m = tcx.hir().impl_item(hir::ImplItemId { hir_id: impl_m });
                         let input_tys = match impl_m.kind {
                             hir::ImplItemKind::Fn(ref sig, _) => sig.decl.inputs,
@@ -961,7 +966,7 @@ crate fn compare_const_impl<'tcx>(
 
         // Create a parameter environment that represents the implementation's
         // method.
-        let impl_c_hir_id = tcx.hir().as_local_hir_id(impl_c.def_id).unwrap();
+        let impl_c_hir_id = tcx.hir().as_local_hir_id(impl_c.def_id.expect_local()).unwrap();
 
         // Compute placeholder form of impl and trait const tys.
         let impl_ty = tcx.type_of(impl_c.def_id);
@@ -1005,7 +1010,8 @@ crate fn compare_const_impl<'tcx>(
                 trait_c.ident
             );
 
-            let trait_c_hir_id = tcx.hir().as_local_hir_id(trait_c.def_id);
+            let trait_c_hir_id =
+                trait_c.def_id.as_local().map(|def_id| tcx.hir().as_local_hir_id(def_id).unwrap());
             let trait_c_span = trait_c_hir_id.map(|trait_c_hir_id| {
                 // Add a label to the Span containing just the type of the const
                 match tcx.hir().expect_trait_item(trait_c_hir_id).kind {
@@ -1093,7 +1099,7 @@ fn compare_type_predicate_entailment(
     // This `HirId` should be used for the `body_id` field on each
     // `ObligationCause` (and the `FnCtxt`). This is what
     // `regionck_item` expects.
-    let impl_ty_hir_id = tcx.hir().as_local_hir_id(impl_ty.def_id).unwrap();
+    let impl_ty_hir_id = tcx.hir().as_local_hir_id(impl_ty.def_id.expect_local()).unwrap();
     let cause = ObligationCause {
         span: impl_ty_span,
         body_id: impl_ty_hir_id,
diff --git a/src/librustc_typeck/check/dropck.rs b/src/librustc_typeck/check/dropck.rs
index 72220d93d92..40efbd6f95c 100644
--- a/src/librustc_typeck/check/dropck.rs
+++ b/src/librustc_typeck/check/dropck.rs
@@ -1,6 +1,6 @@
 use crate::check::regionck::RegionCtxt;
 use crate::hir;
-use crate::hir::def_id::DefId;
+use crate::hir::def_id::{DefId, LocalDefId};
 use rustc_errors::{struct_span_err, ErrorReported};
 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
 use rustc_infer::infer::{InferOk, RegionckMode, TyCtxtInferExt};
@@ -39,7 +39,7 @@ pub fn check_drop_impl(tcx: TyCtxt<'_>, drop_impl_did: DefId) -> Result<(), Erro
         ty::Adt(adt_def, self_to_impl_substs) => {
             ensure_drop_params_and_item_params_correspond(
                 tcx,
-                drop_impl_did,
+                drop_impl_did.expect_local(),
                 dtor_self_type,
                 adt_def.did,
             )?;
@@ -47,7 +47,7 @@ pub fn check_drop_impl(tcx: TyCtxt<'_>, drop_impl_did: DefId) -> Result<(), Erro
             ensure_drop_predicates_are_implied_by_item_defn(
                 tcx,
                 dtor_predicates,
-                adt_def.did,
+                adt_def.did.expect_local(),
                 self_to_impl_substs,
             )
         }
@@ -67,7 +67,7 @@ pub fn check_drop_impl(tcx: TyCtxt<'_>, drop_impl_did: DefId) -> Result<(), Erro
 
 fn ensure_drop_params_and_item_params_correspond<'tcx>(
     tcx: TyCtxt<'tcx>,
-    drop_impl_did: DefId,
+    drop_impl_did: LocalDefId,
     drop_impl_ty: Ty<'tcx>,
     self_type_did: DefId,
 ) -> Result<(), ErrorReported> {
@@ -83,7 +83,8 @@ fn ensure_drop_params_and_item_params_correspond<'tcx>(
         let named_type = tcx.type_of(self_type_did);
 
         let drop_impl_span = tcx.def_span(drop_impl_did);
-        let fresh_impl_substs = infcx.fresh_substs_for_item(drop_impl_span, drop_impl_did);
+        let fresh_impl_substs =
+            infcx.fresh_substs_for_item(drop_impl_span, drop_impl_did.to_def_id());
         let fresh_impl_self_ty = drop_impl_ty.subst(tcx, fresh_impl_substs);
 
         let cause = &ObligationCause::misc(drop_impl_span, drop_impl_hir_id);
@@ -135,7 +136,7 @@ fn ensure_drop_params_and_item_params_correspond<'tcx>(
         let outlives_env = OutlivesEnvironment::new(ty::ParamEnv::empty());
 
         infcx.resolve_regions_and_report_errors(
-            drop_impl_did,
+            drop_impl_did.to_def_id(),
             &region_scope_tree,
             &outlives_env,
             RegionckMode::default(),
@@ -149,7 +150,7 @@ fn ensure_drop_params_and_item_params_correspond<'tcx>(
 fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>(
     tcx: TyCtxt<'tcx>,
     dtor_predicates: ty::GenericPredicates<'tcx>,
-    self_type_did: DefId,
+    self_type_did: LocalDefId,
     self_to_impl_substs: SubstsRef<'tcx>,
 ) -> Result<(), ErrorReported> {
     let mut result = Ok(());
@@ -243,8 +244,10 @@ fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>(
 
         if !assumptions_in_impl_context.iter().any(predicate_matches_closure) {
             let item_span = tcx.hir().span(self_type_hir_id);
-            let self_descr =
-                tcx.def_kind(self_type_did).map(|kind| kind.descr(self_type_did)).unwrap_or("type");
+            let self_descr = tcx
+                .def_kind(self_type_did)
+                .map(|kind| kind.descr(self_type_did.to_def_id()))
+                .unwrap_or("type");
             struct_span_err!(
                 tcx.sess,
                 *predicate_sp,
diff --git a/src/librustc_typeck/check/expr.rs b/src/librustc_typeck/check/expr.rs
index dbda735aa99..353ab250cf0 100644
--- a/src/librustc_typeck/check/expr.rs
+++ b/src/librustc_typeck/check/expr.rs
@@ -1625,8 +1625,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
             return;
         }
         let param_def_id = generic_param.def_id;
-        let param_hir_id = match self.tcx.hir().as_local_hir_id(param_def_id) {
-            Some(x) => x,
+        let param_hir_id = match param_def_id.as_local() {
+            Some(x) => self.tcx.hir().as_local_hir_id(x).unwrap(),
             None => return,
         };
         let param_span = self.tcx.hir().span(param_hir_id);
diff --git a/src/librustc_typeck/check/method/suggest.rs b/src/librustc_typeck/check/method/suggest.rs
index 45b384e2656..37cf5180cf8 100644
--- a/src/librustc_typeck/check/method/suggest.rs
+++ b/src/librustc_typeck/check/method/suggest.rs
@@ -579,11 +579,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
                                 (&self_ty.kind, parent_pred)
                             {
                                 if let ty::Adt(def, _) = p.skip_binder().trait_ref.self_ty().kind {
-                                    let node = self
-                                        .tcx
-                                        .hir()
-                                        .as_local_hir_id(def.did)
-                                        .map(|id| self.tcx.hir().get(id));
+                                    let node = def.did.as_local().map(|def_id| {
+                                        self.tcx
+                                            .hir()
+                                            .get(self.tcx.hir().as_local_hir_id(def_id).unwrap())
+                                    });
                                     if let Some(hir::Node::Item(hir::Item { kind, .. })) = node {
                                         if let Some(g) = kind.generics() {
                                             let key = match &g.where_clause.predicates[..] {
@@ -857,7 +857,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
         candidates: Vec<DefId>,
     ) {
         let module_did = self.tcx.parent_module(self.body_id);
-        let module_id = self.tcx.hir().as_local_hir_id(module_did.to_def_id()).unwrap();
+        let module_id = self.tcx.hir().as_local_hir_id(module_did).unwrap();
         let krate = self.tcx.hir().krate();
         let (span, found_use) = UsePlacementFinder::check(self.tcx, krate, module_id);
         if let Some(span) = span {
@@ -950,62 +950,64 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
                 // implementing a trait would be legal but is rejected
                 // here).
                 !unsatisfied_predicates.iter().any(|(p, _)| match p {
-                    // Hide traits if they are present in predicates as they can be fixed without
-                    // having to implement them.
-                    ty::Predicate::Trait(t, _) => t.def_id() != info.def_id,
-                    ty::Predicate::Projection(p) => p.item_def_id() != info.def_id,
-                    _ => true,
-                }) && (type_is_local || info.def_id.is_local())
-                    && self
-                        .associated_item(info.def_id, item_name, Namespace::ValueNS)
-                        .filter(|item| {
-                            if let ty::AssocKind::Fn = item.kind {
-                                let id = self.tcx.hir().as_local_hir_id(item.def_id);
-                                if let Some(hir::Node::TraitItem(hir::TraitItem {
-                                    kind: hir::TraitItemKind::Fn(fn_sig, method),
-                                    ..
-                                })) = id.map(|id| self.tcx.hir().get(id))
-                                {
-                                    let self_first_arg = match method {
-                                        hir::TraitFn::Required([ident, ..]) => {
-                                            ident.name == kw::SelfLower
-                                        }
-                                        hir::TraitFn::Provided(body_id) => {
-                                            match &self.tcx.hir().body(*body_id).params[..] {
-                                                [hir::Param {
-                                                    pat:
-                                                        hir::Pat {
-                                                            kind:
-                                                                hir::PatKind::Binding(
-                                                                    _,
-                                                                    _,
-                                                                    ident,
-                                                                    ..,
-                                                                ),
-                                                            ..
-                                                        },
-                                                    ..
-                                                }, ..] => ident.name == kw::SelfLower,
-                                                _ => false,
-                                            }
-                                        }
-                                        _ => false,
-                                    };
-
-                                    if !fn_sig.decl.implicit_self.has_implicit_self()
-                                        && self_first_arg
+                        // Hide traits if they are present in predicates as they can be fixed without
+                        // having to implement them.
+                        ty::Predicate::Trait(t, _) => t.def_id() != info.def_id,
+                        ty::Predicate::Projection(p) => p.item_def_id() != info.def_id,
+                        _ => true,
+                    }) && (type_is_local || info.def_id.is_local())
+                        && self
+                            .associated_item(info.def_id, item_name, Namespace::ValueNS)
+                            .filter(|item| {
+                                if let ty::AssocKind::Fn = item.kind {
+                                    let id = item.def_id.as_local().map(|def_id| {
+                                        self.tcx.hir().as_local_hir_id(def_id).unwrap()
+                                    });
+                                    if let Some(hir::Node::TraitItem(hir::TraitItem {
+                                        kind: hir::TraitItemKind::Fn(fn_sig, method),
+                                        ..
+                                    })) = id.map(|id| self.tcx.hir().get(id))
                                     {
-                                        if let Some(ty) = fn_sig.decl.inputs.get(0) {
-                                            arbitrary_rcvr.push(ty.span);
+                                        let self_first_arg = match method {
+                                            hir::TraitFn::Required([ident, ..]) => {
+                                                ident.name == kw::SelfLower
+                                            }
+                                            hir::TraitFn::Provided(body_id) => {
+                                                match &self.tcx.hir().body(*body_id).params[..] {
+                                                    [hir::Param {
+                                                        pat:
+                                                            hir::Pat {
+                                                                kind:
+                                                                    hir::PatKind::Binding(
+                                                                        _,
+                                                                        _,
+                                                                        ident,
+                                                                        ..,
+                                                                    ),
+                                                                ..
+                                                            },
+                                                        ..
+                                                    }, ..] => ident.name == kw::SelfLower,
+                                                    _ => false,
+                                                }
+                                            }
+                                            _ => false,
+                                        };
+
+                                        if !fn_sig.decl.implicit_self.has_implicit_self()
+                                            && self_first_arg
+                                        {
+                                            if let Some(ty) = fn_sig.decl.inputs.get(0) {
+                                                arbitrary_rcvr.push(ty.span);
+                                            }
+                                            return false;
                                         }
-                                        return false;
                                     }
                                 }
-                            }
-                            // We only want to suggest public or local traits (#45781).
-                            item.vis == ty::Visibility::Public || info.def_id.is_local()
-                        })
-                        .is_some()
+                                // We only want to suggest public or local traits (#45781).
+                                item.vis == ty::Visibility::Public || info.def_id.is_local()
+                            })
+                            .is_some()
             })
             .collect::<Vec<_>>();
         for span in &arbitrary_rcvr {
@@ -1052,7 +1054,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
                     let generics = self.tcx.generics_of(table_owner.to_def_id());
                     let type_param = generics.type_param(param, self.tcx);
                     let hir = &self.tcx.hir();
-                    if let Some(id) = hir.as_local_hir_id(type_param.def_id) {
+                    if let Some(id) = type_param
+                        .def_id
+                        .as_local()
+                        .map(|def_id| hir.as_local_hir_id(def_id).unwrap())
+                    {
                         // Get the `hir::Param` to verify whether it already has any bounds.
                         // We do this to avoid suggesting code that ends up as `T: FooBar`,
                         // instead we suggest `T: Foo + Bar` in that case.
diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs
index 1a5862cd5c8..e318eec3e1c 100644
--- a/src/librustc_typeck/check/mod.rs
+++ b/src/librustc_typeck/check/mod.rs
@@ -750,20 +750,20 @@ fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: DefId) {
 fn typeck_item_bodies(tcx: TyCtxt<'_>, crate_num: CrateNum) {
     debug_assert!(crate_num == LOCAL_CRATE);
     tcx.par_body_owners(|body_owner_def_id| {
-        tcx.ensure().typeck_tables_of(body_owner_def_id.to_def_id());
+        tcx.ensure().typeck_tables_of(body_owner_def_id);
     });
 }
 
 fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: DefId) {
-    wfcheck::check_item_well_formed(tcx, def_id);
+    wfcheck::check_item_well_formed(tcx, def_id.expect_local());
 }
 
 fn check_trait_item_well_formed(tcx: TyCtxt<'_>, def_id: DefId) {
-    wfcheck::check_trait_item(tcx, def_id);
+    wfcheck::check_trait_item(tcx, def_id.expect_local());
 }
 
 fn check_impl_item_well_formed(tcx: TyCtxt<'_>, def_id: DefId) {
-    wfcheck::check_impl_item(tcx, def_id);
+    wfcheck::check_impl_item(tcx, def_id.expect_local());
 }
 
 pub fn provide(providers: &mut Providers<'_>) {
@@ -977,7 +977,7 @@ fn diagnostic_only_typeck_tables_of<'tcx>(
 ) -> &ty::TypeckTables<'tcx> {
     assert!(def_id.is_local());
     let fallback = move || {
-        let span = tcx.hir().span(tcx.hir().as_local_hir_id(def_id).unwrap());
+        let span = tcx.hir().span(tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap());
         tcx.sess.delay_span_bug(span, "diagnostic only typeck table used");
         tcx.types.err
     };
@@ -996,7 +996,7 @@ fn typeck_tables_of_with_fallback<'tcx>(
         return tcx.typeck_tables_of(outer_def_id);
     }
 
-    let id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    let id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
     let span = tcx.hir().span(id);
 
     // Figure out what primary body this item has.
@@ -1333,7 +1333,7 @@ fn check_fn<'a, 'tcx>(
     }
 
     let outer_def_id = tcx.closure_base_def_id(hir.local_def_id(fn_id).to_def_id());
-    let outer_hir_id = hir.as_local_hir_id(outer_def_id).unwrap();
+    let outer_hir_id = hir.as_local_hir_id(outer_def_id.expect_local()).unwrap();
     GatherLocalsVisitor { fcx: &fcx, parent_id: outer_hir_id }.visit_body(body);
 
     // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
@@ -1448,7 +1448,7 @@ fn check_fn<'a, 'tcx>(
     // Check that the main return type implements the termination trait.
     if let Some(term_id) = tcx.lang_items().termination() {
         if let Some((def_id, EntryFnType::Main)) = tcx.entry_fn(LOCAL_CRATE) {
-            let main_id = hir.as_local_hir_id(def_id).unwrap();
+            let main_id = hir.as_local_hir_id(def_id.expect_local()).unwrap();
             if main_id == fn_id {
                 let substs = tcx.mk_substs_trait(declared_ret_ty, &[]);
                 let trait_ref = ty::TraitRef::new(term_id, substs);
@@ -1626,9 +1626,7 @@ fn check_opaque<'tcx>(
 /// Checks that an opaque type does not use `Self` or `T::Foo` projections that would result
 /// in "inheriting lifetimes".
 fn check_opaque_for_inheriting_lifetimes(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) {
-    let item = tcx.hir().expect_item(
-        tcx.hir().as_local_hir_id(def_id.to_def_id()).expect("opaque type is not local"),
-    );
+    let item = tcx.hir().expect_item(tcx.hir().as_local_hir_id(def_id).unwrap());
     debug!(
         "check_opaque_for_inheriting_lifetimes: def_id={:?} span={:?} item={:?}",
         def_id, span, item
@@ -2462,7 +2460,7 @@ fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: &ty::AdtDef) {
                 );
 
                 let hir = tcx.hir();
-                if let Some(hir_id) = hir.as_local_hir_id(def_spans[0].0) {
+                if let Some(hir_id) = hir.as_local_hir_id(def_spans[0].0.expect_local()) {
                     if let Node::Item(Item { ident, .. }) = hir.get(hir_id) {
                         err.span_note(
                             tcx.def_span(def_spans[0].0),
@@ -2474,7 +2472,7 @@ fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: &ty::AdtDef) {
                 if def_spans.len() > 2 {
                     let mut first = true;
                     for (adt_def, span) in def_spans.iter().skip(1).rev() {
-                        if let Some(hir_id) = hir.as_local_hir_id(*adt_def) {
+                        if let Some(hir_id) = hir.as_local_hir_id(adt_def.expect_local()) {
                             if let Node::Item(Item { ident, .. }) = hir.get(hir_id) {
                                 err.span_note(
                                     *span,
@@ -2698,7 +2696,7 @@ pub fn check_enum<'tcx>(
         // Check for duplicate discriminant values
         if let Some(i) = disr_vals.iter().position(|&x| x.val == discr.val) {
             let variant_did = def.variants[VariantIdx::new(i)].def_id;
-            let variant_i_hir_id = tcx.hir().as_local_hir_id(variant_did).unwrap();
+            let variant_i_hir_id = tcx.hir().as_local_hir_id(variant_did.expect_local()).unwrap();
             let variant_i = tcx.hir().expect_variant(variant_i_hir_id);
             let i_span = match variant_i.disr_expr {
                 Some(ref expr) => tcx.hir().span(expr.hir_id),
@@ -2759,7 +2757,7 @@ impl<'a, 'tcx> AstConv<'tcx> for FnCtxt<'a, 'tcx> {
 
     fn get_type_parameter_bounds(&self, _: Span, def_id: DefId) -> ty::GenericPredicates<'tcx> {
         let tcx = self.tcx;
-        let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+        let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
         let item_id = tcx.hir().ty_param_owner(hir_id);
         let item_def_id = tcx.hir().local_def_id(item_id);
         let generics = tcx.generics_of(item_def_id);
@@ -4974,7 +4972,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
                 }
                 Some(Node::Ctor(hir::VariantData::Tuple(fields, _))) => {
                     sugg_call = fields.iter().map(|_| "_").collect::<Vec<_>>().join(", ");
-                    match hir.as_local_hir_id(def_id).and_then(|hir_id| hir.def_kind(hir_id)) {
+                    match def_id
+                        .as_local()
+                        .map(|def_id| hir.as_local_hir_id(def_id).unwrap())
+                        .and_then(|hir_id| hir.def_kind(hir_id))
+                    {
                         Some(hir::def::DefKind::Ctor(hir::def::CtorOf::Variant, _)) => {
                             msg = "instantiate this tuple variant";
                         }
diff --git a/src/librustc_typeck/check/wfcheck.rs b/src/librustc_typeck/check/wfcheck.rs
index 574e5a4f8f1..b3c1b5b23e6 100644
--- a/src/librustc_typeck/check/wfcheck.rs
+++ b/src/librustc_typeck/check/wfcheck.rs
@@ -70,14 +70,14 @@ impl<'tcx> CheckWfFcxBuilder<'tcx> {
 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
 /// the types first.
-pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: DefId) {
+pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: LocalDefId) {
     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
     let item = tcx.hir().expect_item(hir_id);
 
     debug!(
         "check_item_well_formed(it.hir_id={:?}, it.name={})",
         item.hir_id,
-        tcx.def_path_str(def_id)
+        tcx.def_path_str(def_id.to_def_id())
     );
 
     match item.kind {
@@ -183,7 +183,7 @@ pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: DefId) {
     }
 }
 
-pub fn check_trait_item(tcx: TyCtxt<'_>, def_id: DefId) {
+pub fn check_trait_item(tcx: TyCtxt<'_>, def_id: LocalDefId) {
     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
     let trait_item = tcx.hir().expect_trait_item(hir_id);
 
@@ -257,7 +257,7 @@ fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem
     }
 }
 
-pub fn check_impl_item(tcx: TyCtxt<'_>, def_id: DefId) {
+pub fn check_impl_item(tcx: TyCtxt<'_>, def_id: LocalDefId) {
     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
     let impl_item = tcx.hir().expect_impl_item(hir_id);
 
@@ -789,7 +789,7 @@ fn check_where_clauses<'tcx, 'fcx>(
     let mut predicates = predicates.instantiate_identity(fcx.tcx);
 
     if let Some((return_ty, span)) = return_ty {
-        let opaque_types = check_opaque_types(tcx, fcx, def_id, span, return_ty);
+        let opaque_types = check_opaque_types(tcx, fcx, def_id.expect_local(), span, return_ty);
         for _ in 0..opaque_types.len() {
             predicates.spans.push(span);
         }
@@ -862,7 +862,7 @@ fn check_fn_or_method<'fcx, 'tcx>(
 fn check_opaque_types<'fcx, 'tcx>(
     tcx: TyCtxt<'tcx>,
     fcx: &FnCtxt<'fcx, 'tcx>,
-    fn_def_id: DefId,
+    fn_def_id: LocalDefId,
     span: Span,
     ty: Ty<'tcx>,
 ) -> Vec<ty::Predicate<'tcx>> {
@@ -878,7 +878,7 @@ fn check_opaque_types<'fcx, 'tcx>(
                 // FIXME(eddyb) is  `generics.parent.is_none()` correct? It seems
                 // potentially risky wrt associated types in `impl`s.
                 if generics.parent.is_none() && def_id.is_local() {
-                    let opaque_hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+                    let opaque_hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
                     if may_define_opaque_type(tcx, fn_def_id, opaque_hir_id) {
                         trace!("check_opaque_types: may define, generics={:#?}", generics);
                         let mut seen_params: FxHashMap<_, Vec<_>> = FxHashMap::default();
diff --git a/src/librustc_typeck/check/writeback.rs b/src/librustc_typeck/check/writeback.rs
index 83f5ba18ad7..f03438af920 100644
--- a/src/librustc_typeck/check/writeback.rs
+++ b/src/librustc_typeck/check/writeback.rs
@@ -427,7 +427,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
 
     fn visit_opaque_types(&mut self, span: Span) {
         for (&def_id, opaque_defn) in self.fcx.opaque_types.borrow().iter() {
-            let hir_id = self.tcx().hir().as_local_hir_id(def_id).unwrap();
+            let hir_id = self.tcx().hir().as_local_hir_id(def_id.expect_local()).unwrap();
             let instantiated_ty = self.resolve(&opaque_defn.concrete_ty, &hir_id);
 
             debug_assert!(!instantiated_ty.has_escaping_bound_vars());
diff --git a/src/librustc_typeck/check_unused.rs b/src/librustc_typeck/check_unused.rs
index bb2e077ceb0..0c6fc8f32aa 100644
--- a/src/librustc_typeck/check_unused.rs
+++ b/src/librustc_typeck/check_unused.rs
@@ -89,7 +89,7 @@ fn unused_crates_lint(tcx: TyCtxt<'_>) {
             // Note that if we carry through to the `extern_mod_stmt_cnum` query
             // below it'll cause a panic because `def_id` is actually bogus at this
             // point in time otherwise.
-            if let Some(id) = tcx.hir().as_local_hir_id(def_id) {
+            if let Some(id) = tcx.hir().as_local_hir_id(def_id.expect_local()) {
                 if tcx.hir().find(id).is_none() {
                     return false;
                 }
@@ -115,7 +115,7 @@ fn unused_crates_lint(tcx: TyCtxt<'_>) {
     });
 
     for extern_crate in &crates_to_lint {
-        let id = tcx.hir().as_local_hir_id(extern_crate.def_id).unwrap();
+        let id = tcx.hir().as_local_hir_id(extern_crate.def_id.expect_local()).unwrap();
         let item = tcx.hir().expect_item(id);
 
         // If the crate is fully unused, we suggest removing it altogether.
diff --git a/src/librustc_typeck/coherence/builtin.rs b/src/librustc_typeck/coherence/builtin.rs
index 7cfb7fa712c..c0613ffdf2e 100644
--- a/src/librustc_typeck/coherence/builtin.rs
+++ b/src/librustc_typeck/coherence/builtin.rs
@@ -53,8 +53,7 @@ fn visit_implementation_of_drop(tcx: TyCtxt<'_>, impl_did: LocalDefId) {
         return;
     }
 
-    let impl_hir_id =
-        tcx.hir().as_local_hir_id(impl_did.to_def_id()).expect("foreign Drop impl on non-ADT");
+    let impl_hir_id = tcx.hir().as_local_hir_id(impl_did).expect("foreign Drop impl on non-ADT");
     let sp = match tcx.hir().expect_item(impl_hir_id).kind {
         ItemKind::Impl { self_ty, .. } => self_ty.span,
         _ => bug!("expected Drop impl item"),
@@ -73,7 +72,7 @@ fn visit_implementation_of_drop(tcx: TyCtxt<'_>, impl_did: LocalDefId) {
 fn visit_implementation_of_copy(tcx: TyCtxt<'_>, impl_did: LocalDefId) {
     debug!("visit_implementation_of_copy: impl_did={:?}", impl_did);
 
-    let impl_hir_id = if let Some(n) = tcx.hir().as_local_hir_id(impl_did.to_def_id()) {
+    let impl_hir_id = if let Some(n) = tcx.hir().as_local_hir_id(impl_did) {
         n
     } else {
         debug!("visit_implementation_of_copy(): impl not in this crate");
@@ -153,7 +152,7 @@ fn visit_implementation_of_dispatch_from_dyn(tcx: TyCtxt<'_>, impl_did: LocalDef
 
     let dispatch_from_dyn_trait = tcx.lang_items().dispatch_from_dyn_trait().unwrap();
 
-    let impl_hir_id = tcx.hir().as_local_hir_id(impl_did.to_def_id()).unwrap();
+    let impl_hir_id = tcx.hir().as_local_hir_id(impl_did).unwrap();
     let span = tcx.hir().span(impl_hir_id);
 
     let source = tcx.type_of(impl_did);
@@ -327,9 +326,7 @@ pub fn coerce_unsized_info(tcx: TyCtxt<'tcx>, impl_did: DefId) -> CoerceUnsizedI
     });
 
     // this provider should only get invoked for local def-ids
-    let impl_hir_id = tcx.hir().as_local_hir_id(impl_did).unwrap_or_else(|| {
-        bug!("coerce_unsized_info: invoked for non-local def-id {:?}", impl_did)
-    });
+    let impl_hir_id = tcx.hir().as_local_hir_id(impl_did.expect_local()).unwrap();
 
     let source = tcx.type_of(impl_did);
     let trait_ref = tcx.impl_trait_ref(impl_did).unwrap();
diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs
index 936ef0299cc..d3bb43f5eac 100644
--- a/src/librustc_typeck/collect.rs
+++ b/src/librustc_typeck/collect.rs
@@ -269,10 +269,7 @@ impl ItemCtxt<'tcx> {
     }
 
     pub fn hir_id(&self) -> hir::HirId {
-        self.tcx
-            .hir()
-            .as_local_hir_id(self.item_def_id)
-            .expect("Non-local call to local provider is_const_fn")
+        self.tcx.hir().as_local_hir_id(self.item_def_id.expect_local()).unwrap()
     }
 
     pub fn node(&self) -> hir::Node<'tcx> {
@@ -489,7 +486,7 @@ fn type_param_predicates(
     // written inline like `<T: Foo>` or in a where-clause like
     // `where T: Foo`.
 
-    let param_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    let param_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
     let param_owner = tcx.hir().ty_param_owner(param_id);
     let param_owner_def_id = tcx.hir().local_def_id(param_owner);
     let generics = tcx.generics_of(param_owner_def_id);
@@ -511,7 +508,7 @@ fn type_param_predicates(
         .unwrap_or_default();
     let mut extend = None;
 
-    let item_hir_id = tcx.hir().as_local_hir_id(item_def_id).unwrap();
+    let item_hir_id = tcx.hir().as_local_hir_id(item_def_id.expect_local()).unwrap();
     let ast_generics = match tcx.hir().get(item_hir_id) {
         Node::TraitItem(item) => &item.generics,
 
@@ -814,13 +811,10 @@ fn convert_variant(
     discr: ty::VariantDiscr,
     def: &hir::VariantData<'_>,
     adt_kind: ty::AdtKind,
-    parent_did: DefId,
+    parent_did: LocalDefId,
 ) -> ty::VariantDef {
     let mut seen_fields: FxHashMap<ast::Ident, Span> = Default::default();
-    let hir_id = tcx
-        .hir()
-        .as_local_hir_id(variant_did.map(LocalDefId::to_def_id).unwrap_or(parent_did))
-        .unwrap();
+    let hir_id = tcx.hir().as_local_hir_id(variant_did.unwrap_or(parent_did)).unwrap();
     let fields = def
         .fields()
         .iter()
@@ -862,7 +856,7 @@ fn convert_variant(
         fields,
         CtorKind::from_hir(def),
         adt_kind,
-        parent_did,
+        parent_did.to_def_id(),
         recovered,
     )
 }
@@ -870,13 +864,14 @@ fn convert_variant(
 fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::AdtDef {
     use rustc_hir::*;
 
+    let def_id = def_id.expect_local();
     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
     let item = match tcx.hir().get(hir_id) {
         Node::Item(item) => item,
         _ => bug!(),
     };
 
-    let repr = ReprOptions::new(tcx, def_id);
+    let repr = ReprOptions::new(tcx, def_id.to_def_id());
     let (kind, variants) = match item.kind {
         ItemKind::Enum(ref def, _) => {
             let mut distance_from_explicit = 0;
@@ -949,7 +944,7 @@ fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::AdtDef {
         }
         _ => bug!(),
     };
-    tcx.alloc_adt_def(def_id, kind, variants, repr)
+    tcx.alloc_adt_def(def_id.to_def_id(), kind, variants, repr)
 }
 
 /// Ensures that the super-predicates of the trait with a `DefId`
@@ -957,7 +952,7 @@ fn adt_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::AdtDef {
 /// the transitive super-predicates are converted.
 fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredicates<'_> {
     debug!("super_predicates(trait_def_id={:?})", trait_def_id);
-    let trait_hir_id = tcx.hir().as_local_hir_id(trait_def_id).unwrap();
+    let trait_hir_id = tcx.hir().as_local_hir_id(trait_def_id.expect_local()).unwrap();
 
     let item = match tcx.hir().get(trait_hir_id) {
         Node::Item(item) => item,
@@ -1008,7 +1003,7 @@ fn super_predicates_of(tcx: TyCtxt<'_>, trait_def_id: DefId) -> ty::GenericPredi
 }
 
 fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::TraitDef {
-    let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
     let item = tcx.hir().expect_item(hir_id);
 
     let (is_auto, unsafety) = match item.kind {
@@ -1166,7 +1161,7 @@ fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option<S
 fn generics_of(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::Generics {
     use rustc_hir::*;
 
-    let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
 
     let node = tcx.hir().get(hir_id);
     let parent_def_id = match node {
@@ -1464,7 +1459,7 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
     use rustc_hir::Node::*;
     use rustc_hir::*;
 
-    let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
 
     let icx = ItemCtxt::new(tcx, def_id);
 
@@ -1562,7 +1557,7 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> {
 fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
     let icx = ItemCtxt::new(tcx, def_id);
 
-    let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
     match tcx.hir().expect_item(hir_id).kind {
         hir::ItemKind::Impl { ref of_trait, .. } => of_trait.as_ref().map(|ast_trait_ref| {
             let selfty = tcx.type_of(def_id);
@@ -1573,7 +1568,7 @@ fn impl_trait_ref(tcx: TyCtxt<'_>, def_id: DefId) -> Option<ty::TraitRef<'_>> {
 }
 
 fn impl_polarity(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ImplPolarity {
-    let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
     let is_rustc_reservation = tcx.has_attr(def_id, sym::rustc_reservation_impl);
     let item = tcx.hir().expect_item(hir_id);
     match &item.kind {
@@ -1707,7 +1702,7 @@ fn explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicat
         }
     }
 
-    let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
     let node = tcx.hir().get(hir_id);
 
     let mut is_trait = None;
@@ -2562,7 +2557,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, id: DefId) -> CodegenFnAttrs {
     if codegen_fn_attrs.flags.intersects(CodegenFnAttrFlags::NO_SANITIZE_ANY) {
         if codegen_fn_attrs.inline == InlineAttr::Always {
             if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
-                let hir_id = tcx.hir().as_local_hir_id(id).unwrap();
+                let hir_id = tcx.hir().as_local_hir_id(id.expect_local()).unwrap();
                 tcx.struct_span_lint_hir(
                     lint::builtin::INLINE_NO_SANITIZE,
                     hir_id,
diff --git a/src/librustc_typeck/collect/type_of.rs b/src/librustc_typeck/collect/type_of.rs
index 5d05cfe74a1..4ff836855dd 100644
--- a/src/librustc_typeck/collect/type_of.rs
+++ b/src/librustc_typeck/collect/type_of.rs
@@ -2,7 +2,7 @@ use rustc_data_structures::fx::FxHashSet;
 use rustc_errors::{struct_span_err, Applicability, ErrorReported, StashKey};
 use rustc_hir as hir;
 use rustc_hir::def::{DefKind, Res};
-use rustc_hir::def_id::DefId;
+use rustc_hir::def_id::{DefId, LocalDefId};
 use rustc_hir::intravisit;
 use rustc_hir::intravisit::Visitor;
 use rustc_hir::Node;
@@ -21,7 +21,7 @@ use super::{bad_placeholder_type, is_suggestable_infer_ty};
 pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
     use rustc_hir::*;
 
-    let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()).unwrap();
 
     let icx = ItemCtxt::new(tcx, def_id);
 
@@ -63,7 +63,7 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
                     report_assoc_ty_on_inherent_impl(tcx, item.span);
                 }
 
-                find_opaque_ty_constraints(tcx, def_id)
+                find_opaque_ty_constraints(tcx, def_id.expect_local())
             }
             ImplItemKind::TyAlias(ref ty) => {
                 if tcx.impl_trait_ref(tcx.hir().get_parent_did(hir_id).to_def_id()).is_none() {
@@ -96,7 +96,7 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
                     tcx.mk_adt(def, substs)
                 }
                 ItemKind::OpaqueTy(OpaqueTy { impl_trait_fn: None, .. }) => {
-                    find_opaque_ty_constraints(tcx, def_id)
+                    find_opaque_ty_constraints(tcx, def_id.expect_local())
                 }
                 // Opaque types desugared from `impl Trait`.
                 ItemKind::OpaqueTy(OpaqueTy { impl_trait_fn: Some(owner), origin, .. }) => {
@@ -364,7 +364,7 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
     }
 }
 
-fn find_opaque_ty_constraints(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
+fn find_opaque_ty_constraints(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Ty<'_> {
     use rustc_hir::{Expr, ImplItem, Item, TraitItem};
 
     debug!("find_opaque_ty_constraints({:?})", def_id);
@@ -516,7 +516,7 @@ fn find_opaque_ty_constraints(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
 
     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
     let scope = tcx.hir().get_defining_scope(hir_id);
-    let mut locator = ConstraintLocator { def_id, tcx, found: None };
+    let mut locator = ConstraintLocator { def_id: def_id.to_def_id(), tcx, found: None };
 
     debug!("find_opaque_ty_constraints: scope={:?}", scope);
 
diff --git a/src/librustc_typeck/impl_wf_check/min_specialization.rs b/src/librustc_typeck/impl_wf_check/min_specialization.rs
index ebfb3684eb0..f419f052b81 100644
--- a/src/librustc_typeck/impl_wf_check/min_specialization.rs
+++ b/src/librustc_typeck/impl_wf_check/min_specialization.rs
@@ -69,7 +69,7 @@ use crate::constrained_generic_params as cgp;
 
 use rustc_data_structures::fx::FxHashSet;
 use rustc_hir as hir;
-use rustc_hir::def_id::DefId;
+use rustc_hir::def_id::{DefId, LocalDefId};
 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
 use rustc_infer::infer::{InferCtxt, RegionckMode, TyCtxtInferExt};
 use rustc_infer::traits::specialization_graph::Node;
@@ -130,7 +130,14 @@ fn check_always_applicable(
         check_static_lifetimes(tcx, &parent_substs, span);
         check_duplicate_params(tcx, impl1_substs, &parent_substs, span);
 
-        check_predicates(infcx, impl1_def_id, impl1_substs, impl2_node, impl2_substs, span);
+        check_predicates(
+            infcx,
+            impl1_def_id.expect_local(),
+            impl1_substs,
+            impl2_node,
+            impl2_substs,
+            span,
+        );
     }
 }
 
@@ -287,7 +294,7 @@ fn check_static_lifetimes<'tcx>(
 ///   including the `Self`-type.
 fn check_predicates<'tcx>(
     infcx: &InferCtxt<'_, 'tcx>,
-    impl1_def_id: DefId,
+    impl1_def_id: LocalDefId,
     impl1_substs: SubstsRef<'tcx>,
     impl2_node: Node,
     impl2_substs: SubstsRef<'tcx>,
diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs
index 04e037c83ad..0c922ff17ac 100644
--- a/src/librustc_typeck/lib.rs
+++ b/src/librustc_typeck/lib.rs
@@ -91,7 +91,7 @@ mod variance;
 
 use rustc_errors::{struct_span_err, ErrorReported};
 use rustc_hir as hir;
-use rustc_hir::def_id::{DefId, LOCAL_CRATE};
+use rustc_hir::def_id::{LocalDefId, LOCAL_CRATE};
 use rustc_hir::Node;
 use rustc_infer::infer::{InferOk, TyCtxtInferExt};
 use rustc_infer::traits::TraitEngineExt as _;
@@ -152,7 +152,7 @@ fn require_same_types<'tcx>(
     })
 }
 
-fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) {
+fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: LocalDefId) {
     let main_id = tcx.hir().as_local_hir_id(main_def_id).unwrap();
     let main_span = tcx.def_span(main_def_id);
     let main_t = tcx.type_of(main_def_id);
@@ -231,7 +231,7 @@ fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) {
     }
 }
 
-fn check_start_fn_ty(tcx: TyCtxt<'_>, start_def_id: DefId) {
+fn check_start_fn_ty(tcx: TyCtxt<'_>, start_def_id: LocalDefId) {
     let start_id = tcx.hir().as_local_hir_id(start_def_id).unwrap();
     let start_span = tcx.def_span(start_def_id);
     let start_t = tcx.type_of(start_def_id);
@@ -303,8 +303,8 @@ fn check_start_fn_ty(tcx: TyCtxt<'_>, start_def_id: DefId) {
 
 fn check_for_entry_fn(tcx: TyCtxt<'_>) {
     match tcx.entry_fn(LOCAL_CRATE) {
-        Some((def_id, EntryFnType::Main)) => check_main_fn_ty(tcx, def_id),
-        Some((def_id, EntryFnType::Start)) => check_start_fn_ty(tcx, def_id),
+        Some((def_id, EntryFnType::Main)) => check_main_fn_ty(tcx, def_id.expect_local()),
+        Some((def_id, EntryFnType::Start)) => check_start_fn_ty(tcx, def_id.expect_local()),
         _ => {}
     }
 }
diff --git a/src/librustc_typeck/outlives/implicit_infer.rs b/src/librustc_typeck/outlives/implicit_infer.rs
index 6a9cbc544f8..3c579538e64 100644
--- a/src/librustc_typeck/outlives/implicit_infer.rs
+++ b/src/librustc_typeck/outlives/implicit_infer.rs
@@ -53,7 +53,7 @@ pub struct InferVisitor<'cx, 'tcx> {
 
 impl<'cx, 'tcx> ItemLikeVisitor<'tcx> for InferVisitor<'cx, 'tcx> {
     fn visit_item(&mut self, item: &hir::Item<'_>) {
-        let item_did = self.tcx.hir().local_def_id(item.hir_id).to_def_id();
+        let item_did = self.tcx.hir().local_def_id(item.hir_id);
 
         debug!("InferVisitor::visit_item(item={:?})", item_did);
 
@@ -66,7 +66,7 @@ impl<'cx, 'tcx> ItemLikeVisitor<'tcx> for InferVisitor<'cx, 'tcx> {
         let mut item_required_predicates = RequiredPredicates::default();
         match item.kind {
             hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) => {
-                let adt_def = self.tcx.adt_def(item_did);
+                let adt_def = self.tcx.adt_def(item_did.to_def_id());
 
                 // Iterate over all fields in item_did
                 for field_def in adt_def.all_fields() {
@@ -99,10 +99,10 @@ impl<'cx, 'tcx> ItemLikeVisitor<'tcx> for InferVisitor<'cx, 'tcx> {
         // we walk the crates again and re-calculate predicates for all
         // items.
         let item_predicates_len: usize =
-            self.global_inferred_outlives.get(&item_did).map(|p| p.len()).unwrap_or(0);
+            self.global_inferred_outlives.get(&item_did.to_def_id()).map(|p| p.len()).unwrap_or(0);
         if item_required_predicates.len() > item_predicates_len {
             *self.predicates_added = true;
-            self.global_inferred_outlives.insert(item_did, item_required_predicates);
+            self.global_inferred_outlives.insert(item_did.to_def_id(), item_required_predicates);
         }
     }
 
diff --git a/src/librustc_typeck/outlives/mod.rs b/src/librustc_typeck/outlives/mod.rs
index 2d9b39a7f61..71fcd9ddd6b 100644
--- a/src/librustc_typeck/outlives/mod.rs
+++ b/src/librustc_typeck/outlives/mod.rs
@@ -18,7 +18,7 @@ pub fn provide(providers: &mut Providers<'_>) {
 }
 
 fn inferred_outlives_of(tcx: TyCtxt<'_>, item_def_id: DefId) -> &[(ty::Predicate<'_>, Span)] {
-    let id = tcx.hir().as_local_hir_id(item_def_id).expect("expected local def-id");
+    let id = tcx.hir().as_local_hir_id(item_def_id.expect_local()).unwrap();
 
     match tcx.hir().get(id) {
         Node::Item(item) => match item.kind {
diff --git a/src/librustc_typeck/variance/constraints.rs b/src/librustc_typeck/variance/constraints.rs
index 83be3e2c878..5b0ccc5169e 100644
--- a/src/librustc_typeck/variance/constraints.rs
+++ b/src/librustc_typeck/variance/constraints.rs
@@ -3,7 +3,7 @@
 //! The second pass over the AST determines the set of constraints.
 //! We walk the set of items and, for each member, generate new constraints.
 
-use hir::def_id::DefId;
+use hir::def_id::{DefId, LocalDefId};
 use rustc_hir as hir;
 use rustc_hir::itemlikevisit::ItemLikeVisitor;
 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef};
@@ -121,16 +121,16 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> {
     fn visit_node_helper(&mut self, id: hir::HirId) {
         let tcx = self.terms_cx.tcx;
         let def_id = tcx.hir().local_def_id(id);
-        self.build_constraints_for_item(def_id.to_def_id());
+        self.build_constraints_for_item(def_id);
     }
 
     fn tcx(&self) -> TyCtxt<'tcx> {
         self.terms_cx.tcx
     }
 
-    fn build_constraints_for_item(&mut self, def_id: DefId) {
+    fn build_constraints_for_item(&mut self, def_id: LocalDefId) {
         let tcx = self.tcx();
-        debug!("build_constraints_for_item({})", tcx.def_path_str(def_id));
+        debug!("build_constraints_for_item({})", tcx.def_path_str(def_id.to_def_id()));
 
         // Skip items with no generics - there's nothing to infer in them.
         if tcx.generics_of(def_id).count() == 0 {
@@ -377,7 +377,9 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> {
             return;
         }
 
-        let (local, remote) = if let Some(id) = self.tcx().hir().as_local_hir_id(def_id) {
+        let (local, remote) = if let Some(id) =
+            def_id.as_local().map(|def_id| self.tcx().hir().as_local_hir_id(def_id).unwrap())
+        {
             (Some(self.terms_cx.inferred_starts[&id]), None)
         } else {
             (None, Some(self.tcx().variances_of(def_id)))
diff --git a/src/librustc_typeck/variance/mod.rs b/src/librustc_typeck/variance/mod.rs
index 47652b7b696..f9e32c2a6b0 100644
--- a/src/librustc_typeck/variance/mod.rs
+++ b/src/librustc_typeck/variance/mod.rs
@@ -38,7 +38,7 @@ fn crate_variances(tcx: TyCtxt<'_>, crate_num: CrateNum) -> &CrateVariancesMap<'
 }
 
 fn variances_of(tcx: TyCtxt<'_>, item_def_id: DefId) -> &[ty::Variance] {
-    let id = tcx.hir().as_local_hir_id(item_def_id).expect("expected local def-id");
+    let id = tcx.hir().as_local_hir_id(item_def_id.expect_local()).unwrap();
     let unsupported = || {
         // Variance not relevant.
         span_bug!(tcx.hir().span(id), "asked to compute variance for wrong kind of item")
diff --git a/src/librustc_typeck/variance/terms.rs b/src/librustc_typeck/variance/terms.rs
index e3ea0bf20e3..c6cdac5d0cc 100644
--- a/src/librustc_typeck/variance/terms.rs
+++ b/src/librustc_typeck/variance/terms.rs
@@ -94,7 +94,9 @@ fn lang_items(tcx: TyCtxt<'_>) -> Vec<(hir::HirId, Vec<ty::Variance>)> {
     all.into_iter() // iterating over (Option<DefId>, Variance)
         .filter(|&(ref d, _)| d.is_some())
         .map(|(d, v)| (d.unwrap(), v)) // (DefId, Variance)
-        .filter_map(|(d, v)| tcx.hir().as_local_hir_id(d).map(|n| (n, v))) // (HirId, Variance)
+        .filter_map(|(d, v)| {
+            d.as_local().map(|d| tcx.hir().as_local_hir_id(d).unwrap()).map(|n| (n, v))
+        }) // (HirId, Variance)
         .collect()
 }
 
diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs
index e9af0ee5c23..fc50a0ac225 100644
--- a/src/librustdoc/clean/inline.rs
+++ b/src/librustdoc/clean/inline.rs
@@ -340,14 +340,15 @@ pub fn build_impl(
         }
     }
 
-    let for_ = if let Some(hir_id) = tcx.hir().as_local_hir_id(did) {
-        match tcx.hir().expect_item(hir_id).kind {
-            hir::ItemKind::Impl { self_ty, .. } => self_ty.clean(cx),
-            _ => panic!("did given to build_impl was not an impl"),
-        }
-    } else {
-        tcx.type_of(did).clean(cx)
-    };
+    let for_ =
+        if let Some(hir_id) = did.as_local().map(|did| tcx.hir().as_local_hir_id(did).unwrap()) {
+            match tcx.hir().expect_item(hir_id).kind {
+                hir::ItemKind::Impl { self_ty, .. } => self_ty.clean(cx),
+                _ => panic!("did given to build_impl was not an impl"),
+            }
+        } else {
+            tcx.type_of(did).clean(cx)
+        };
 
     // Only inline impl if the implementing type is
     // reachable in rustdoc generated documentation
@@ -360,7 +361,9 @@ pub fn build_impl(
     }
 
     let predicates = tcx.explicit_predicates_of(did);
-    let (trait_items, generics) = if let Some(hir_id) = tcx.hir().as_local_hir_id(did) {
+    let (trait_items, generics) = if let Some(hir_id) =
+        did.as_local().map(|did| tcx.hir().as_local_hir_id(did).unwrap())
+    {
         match tcx.hir().expect_item(hir_id).kind {
             hir::ItemKind::Impl { ref generics, ref items, .. } => (
                 items.iter().map(|item| tcx.hir().impl_item(item.id).clean(cx)).collect::<Vec<_>>(),
@@ -486,7 +489,7 @@ fn build_module(cx: &DocContext<'_>, did: DefId, visited: &mut FxHashSet<DefId>)
 }
 
 pub fn print_inlined_const(cx: &DocContext<'_>, did: DefId) -> String {
-    if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(did) {
+    if let Some(hir_id) = did.as_local().map(|did| cx.tcx.hir().as_local_hir_id(did).unwrap()) {
         rustc_hir_pretty::id_to_string(&cx.tcx.hir(), hir_id)
     } else {
         cx.tcx.rendered_const(did)
@@ -498,11 +501,9 @@ fn build_const(cx: &DocContext<'_>, did: DefId) -> clean::Constant {
         type_: cx.tcx.type_of(did).clean(cx),
         expr: print_inlined_const(cx, did),
         value: clean::utils::print_evaluated_const(cx, did),
-        is_literal: cx
-            .tcx
-            .hir()
-            .as_local_hir_id(did)
-            .map_or(false, |hir_id| clean::utils::is_literal_expr(cx, hir_id)),
+        is_literal: did.as_local().map_or(false, |did| {
+            clean::utils::is_literal_expr(cx, cx.tcx.hir().as_local_hir_id(did).unwrap())
+        }),
     }
 }
 
diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs
index f7e61a723da..751f3b868fd 100644
--- a/src/librustdoc/clean/mod.rs
+++ b/src/librustdoc/clean/mod.rs
@@ -976,12 +976,7 @@ where
 impl<'tcx> Clean<FnDecl> for (DefId, ty::PolyFnSig<'tcx>) {
     fn clean(&self, cx: &DocContext<'_>) -> FnDecl {
         let (did, sig) = *self;
-        let mut names = if cx.tcx.hir().as_local_hir_id(did).is_some() {
-            &[]
-        } else {
-            cx.tcx.fn_arg_names(did)
-        }
-        .iter();
+        let mut names = if did.is_local() { &[] } else { cx.tcx.fn_arg_names(did) }.iter();
 
         FnDecl {
             output: Return(sig.skip_binder().output().clean(cx)),
@@ -1384,7 +1379,10 @@ impl Clean<Type> for hir::Ty<'_> {
                 let mut alias = None;
                 if let Res::Def(DefKind::TyAlias, def_id) = path.res {
                     // Substitute private type aliases
-                    if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(def_id) {
+                    if let Some(hir_id) = def_id
+                        .as_local()
+                        .map(|def_id| cx.tcx.hir().as_local_hir_id(def_id).unwrap())
+                    {
                         if !cx.renderinfo.borrow().access_levels.is_exported(def_id) {
                             alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
                         }
diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs
index 24817170e36..ebb1838a83b 100644
--- a/src/librustdoc/clean/utils.rs
+++ b/src/librustdoc/clean/utils.rs
@@ -473,7 +473,9 @@ pub fn name_from_pat(p: &hir::Pat) -> String {
 pub fn print_const(cx: &DocContext<'_>, n: &'tcx ty::Const<'_>) -> String {
     match n.val {
         ty::ConstKind::Unevaluated(def_id, _, promoted) => {
-            let mut s = if let Some(hir_id) = cx.tcx.hir().as_local_hir_id(def_id) {
+            let mut s = if let Some(hir_id) =
+                def_id.as_local().map(|def_id| cx.tcx.hir().as_local_hir_id(def_id).unwrap())
+            {
                 print_const_expr(cx, cx.tcx.hir().body_owned_by(hir_id))
             } else {
                 inline::print_inlined_const(cx, def_id)
diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs
index f26f6d3eff9..cc5bb335bae 100644
--- a/src/librustdoc/core.rs
+++ b/src/librustdoc/core.rs
@@ -144,7 +144,7 @@ impl<'tcx> DocContext<'tcx> {
         if self.all_fake_def_ids.borrow().contains(&def_id) {
             None
         } else {
-            self.tcx.hir().as_local_hir_id(def_id)
+            def_id.as_local().map(|def_id| self.tcx.hir().as_local_hir_id(def_id).unwrap())
         }
     }
 
diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs
index 8bfd42ac56a..675cc918490 100644
--- a/src/librustdoc/passes/collect_intra_doc_links.rs
+++ b/src/librustdoc/passes/collect_intra_doc_links.rs
@@ -335,7 +335,11 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
 impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> {
     fn fold_item(&mut self, mut item: Item) -> Option<Item> {
         let item_hir_id = if item.is_mod() {
-            if let Some(id) = self.cx.tcx.hir().as_local_hir_id(item.def_id) {
+            if let Some(id) = item
+                .def_id
+                .as_local()
+                .map(|def_id| self.cx.tcx.hir().as_local_hir_id(def_id).unwrap())
+            {
                 Some(id)
             } else {
                 debug!("attempting to fold on a non-local item: {:?}", item);
diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs
index fa2a08479aa..6b9f3acf9e8 100644
--- a/src/librustdoc/visit_ast.rs
+++ b/src/librustdoc/visit_ast.rs
@@ -331,8 +331,8 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
             return false;
         }
 
-        let res_hir_id = match tcx.hir().as_local_hir_id(res_did) {
-            Some(n) => n,
+        let res_hir_id = match res_did.as_local() {
+            Some(n) => tcx.hir().as_local_hir_id(n).unwrap(),
             None => return false,
         };