Rollup merge of #58288 - taiki-e:rustc-workspace-hack-2018, r=alexcrichton

rustc-workspace-hack => 2018

Transitions `rustc-workspace-hack` to Rust 2018; cc #58099

r? @alexcrichton
diff --git a/Cargo.lock b/Cargo.lock
index 4cea89e..a36df24 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1,3 +1,5 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
 [[package]]
 name = "adler32"
 version = "1.0.3"
@@ -1503,7 +1505,7 @@
 
 [[package]]
 name = "minifier"
-version = "0.0.26"
+version = "0.0.28"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 dependencies = [
  "macro-utils 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -2992,7 +2994,7 @@
 name = "rustdoc"
 version = "0.0.0"
 dependencies = [
- "minifier 0.0.26 (registry+https://github.com/rust-lang/crates.io-index)",
+ "minifier 0.0.28 (registry+https://github.com/rust-lang/crates.io-index)",
  "parking_lot 0.6.4 (registry+https://github.com/rust-lang/crates.io-index)",
  "pulldown-cmark 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
  "tempfile 3.0.5 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -4066,7 +4068,7 @@
 "checksum memchr 2.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0a3eb002f0535929f1199681417029ebea04aadc0c7a4224b46be99c7f5d6a16"
 "checksum memmap 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e2ffa2c986de11a9df78620c01eeaaf27d94d3ff02bf81bfcca953102dd0c6ff"
 "checksum memoffset 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0f9dc261e2b62d7a622bf416ea3c5245cdd5d9a7fcc428c0d06804dfce1775b3"
-"checksum minifier 0.0.26 (registry+https://github.com/rust-lang/crates.io-index)" = "f299df45afd73332044ea9f717c816a84fc90c8b631409abf339ba93642a7985"
+"checksum minifier 0.0.28 (registry+https://github.com/rust-lang/crates.io-index)" = "3a2898502751dcc9d66b6fff57f3cf63cc91605e83e1a33515396f5027f8e4ca"
 "checksum miniz-sys 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)" = "0300eafb20369952951699b68243ab4334f4b10a88f411c221d444b36c40e649"
 "checksum miniz_oxide 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5ad30a47319c16cde58d0314f5d98202a80c9083b5f61178457403dfb14e509c"
 "checksum miniz_oxide_c_api 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "28edaef377517fd9fe3e085c37d892ce7acd1fbeab9239c5a36eec352d8a8b7e"
diff --git a/src/bootstrap/builder.rs b/src/bootstrap/builder.rs
index b0d15e6..f512e1d 100644
--- a/src/bootstrap/builder.rs
+++ b/src/bootstrap/builder.rs
@@ -400,6 +400,7 @@
                 test::TheBook,
                 test::UnstableBook,
                 test::RustcBook,
+                test::EmbeddedBook,
                 test::Rustfmt,
                 test::Miri,
                 test::Clippy,
@@ -1018,8 +1019,7 @@
 
         cargo.env("RUSTC_VERBOSE", self.verbosity.to_string());
 
-        // in std, we want to avoid denying warnings for stage 0 as that makes cfg's painful.
-        if self.config.deny_warnings && !(mode == Mode::Std && stage == 0) {
+        if self.config.deny_warnings {
             cargo.env("RUSTC_DENY_WARNINGS", "1");
         }
 
diff --git a/src/bootstrap/test.rs b/src/bootstrap/test.rs
index 1a46ebf..bb00f6f 100644
--- a/src/bootstrap/test.rs
+++ b/src/bootstrap/test.rs
@@ -1383,6 +1383,7 @@
     RustdocBook, "src/doc/rustdoc", "rustdoc", default=true;
     RustcBook, "src/doc/rustc", "rustc", default=true;
     RustByExample, "src/doc/rust-by-example", "rust-by-example", default=false;
+    EmbeddedBook, "src/doc/embedded-book", "embedded-book", default=false;
     TheBook, "src/doc/book", "book", default=false;
     UnstableBook, "src/doc/unstable-book", "unstable-book", default=true;
 );
diff --git a/src/build_helper/Cargo.toml b/src/build_helper/Cargo.toml
index 01d704f..04c7820 100644
--- a/src/build_helper/Cargo.toml
+++ b/src/build_helper/Cargo.toml
@@ -2,6 +2,7 @@
 name = "build_helper"
 version = "0.1.0"
 authors = ["The Rust Project Developers"]
+edition = "2018"
 
 [lib]
 name = "build_helper"
diff --git a/src/build_helper/lib.rs b/src/build_helper/lib.rs
index c66c5c9..93aa917 100644
--- a/src/build_helper/lib.rs
+++ b/src/build_helper/lib.rs
@@ -1,3 +1,5 @@
+#![deny(rust_2018_idioms)]
+
 use std::fs::File;
 use std::path::{Path, PathBuf};
 use std::process::{Command, Stdio};
diff --git a/src/doc/embedded-book b/src/doc/embedded-book
index d663113..bd2778f 160000
--- a/src/doc/embedded-book
+++ b/src/doc/embedded-book
@@ -1 +1 @@
-Subproject commit d663113d1d9fbd35f1145c29f6080a6350b7f419
+Subproject commit bd2778f304989ee52be8201504d6ec621dd60ca9
diff --git a/src/doc/rustdoc/src/unstable-features.md b/src/doc/rustdoc/src/unstable-features.md
index d3eb8cb..3463cdb 100644
--- a/src/doc/rustdoc/src/unstable-features.md
+++ b/src/doc/rustdoc/src/unstable-features.md
@@ -1,9 +1,8 @@
 # Unstable features
 
 Rustdoc is under active development, and like the Rust compiler, some features are only available
-on the nightly releases. Some of these are new and need some more testing before they're able to get
-released to the world at large, and some of them are tied to features in the Rust compiler that are
-themselves unstable. Several features here require a matching `#![feature(...)]` attribute to
+on nightly releases. Some of these features are new and need some more testing before they're able to be
+released to the world at large, and some of them are tied to features in the Rust compiler that are unstable. Several features here require a matching `#![feature(...)]` attribute to
 enable, and thus are more fully documented in the [Unstable Book]. Those sections will link over
 there as necessary.
 
@@ -428,4 +427,4 @@
 
 This flag allows you to keep doctest executables around after they're compiled or run.
 Usually, rustdoc will immediately discard a compiled doctest after it's been tested, but
-with this option, you can keep those binaries around for farther testing.
\ No newline at end of file
+with this option, you can keep those binaries around for farther testing.
diff --git a/src/liballoc/lib.rs b/src/liballoc/lib.rs
index 80097a1..189ba84 100644
--- a/src/liballoc/lib.rs
+++ b/src/liballoc/lib.rs
@@ -55,9 +55,7 @@
             reason = "this library is unlikely to be stabilized in its current \
                       form or name",
             issue = "27783")]
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/",
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
        issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
        test(no_crate_inject, attr(allow(unused_variables), deny(warnings))))]
 #![no_std]
diff --git a/src/liballoc/tests/arc.rs b/src/liballoc/tests/arc.rs
index 2759b1b..7c5a892 100644
--- a/src/liballoc/tests/arc.rs
+++ b/src/liballoc/tests/arc.rs
@@ -1,3 +1,5 @@
+#![cfg(not(miri))]
+
 use std::any::Any;
 use std::sync::{Arc, Weak};
 use std::cell::RefCell;
diff --git a/src/liballoc/tests/binary_heap.rs b/src/liballoc/tests/binary_heap.rs
index 94ae432..c1a1c5d 100644
--- a/src/liballoc/tests/binary_heap.rs
+++ b/src/liballoc/tests/binary_heap.rs
@@ -282,6 +282,7 @@
 //
 // Destructors must be called exactly once per element.
 #[test]
+#[cfg(not(miri))]
 fn panic_safe() {
     static DROP_COUNTER: AtomicUsize = AtomicUsize::new(0);
 
diff --git a/src/liballoc/tests/btree/mod.rs b/src/liballoc/tests/btree/mod.rs
index 4c704d0..653b3f5 100644
--- a/src/liballoc/tests/btree/mod.rs
+++ b/src/liballoc/tests/btree/mod.rs
@@ -1,3 +1,5 @@
+#![cfg(not(miri))]
+
 mod map;
 mod set;
 
diff --git a/src/liballoc/tests/heap.rs b/src/liballoc/tests/heap.rs
index 24eea1d..809d2bc 100644
--- a/src/liballoc/tests/heap.rs
+++ b/src/liballoc/tests/heap.rs
@@ -1,3 +1,5 @@
+#![cfg(not(miri))]
+
 use std::alloc::{Global, Alloc, Layout, System};
 
 /// https://github.com/rust-lang/rust/issues/45955
diff --git a/src/liballoc/tests/rc.rs b/src/liballoc/tests/rc.rs
index 18f82e8..1be01d1 100644
--- a/src/liballoc/tests/rc.rs
+++ b/src/liballoc/tests/rc.rs
@@ -1,3 +1,5 @@
+#![cfg(not(miri))]
+
 use std::any::Any;
 use std::rc::{Rc, Weak};
 use std::cell::RefCell;
diff --git a/src/liballoc/tests/slice.rs b/src/liballoc/tests/slice.rs
index 334466d..2a9fdfa 100644
--- a/src/liballoc/tests/slice.rs
+++ b/src/liballoc/tests/slice.rs
@@ -1,3 +1,5 @@
+#![cfg(not(miri))]
+
 use std::cell::Cell;
 use std::cmp::Ordering::{self, Equal, Greater, Less};
 use std::mem;
diff --git a/src/liballoc/tests/str.rs b/src/liballoc/tests/str.rs
index 1bc1bd8..f4e6bc9 100644
--- a/src/liballoc/tests/str.rs
+++ b/src/liballoc/tests/str.rs
@@ -31,6 +31,7 @@
 }
 
 #[test]
+#[cfg(not(miri))]
 fn test_collect() {
     let empty = "";
     let s: String = empty.chars().collect();
@@ -118,6 +119,7 @@
 #[test]
 fn test_concat_for_different_lengths() {
     let empty: &[&str] = &[];
+    #[cfg(not(miri))]
     test_concat!("", empty);
     test_concat!("a", ["a"]);
     test_concat!("ab", ["a", "b"]);
@@ -146,6 +148,7 @@
 #[test]
 fn test_join_for_different_lengths() {
     let empty: &[&str] = &[];
+    #[cfg(not(miri))]
     test_join!("", empty, "-");
     test_join!("a", ["a"], "-");
     test_join!("a-b", ["a", "b"], "-");
@@ -159,6 +162,7 @@
     assert_eq!("~~~~~".len(), 15);
 
     let empty: &[&str] = &[];
+    #[cfg(not(miri))]
     test_join!("", empty, "~~~~~");
     test_join!("a", ["a"], "~~~~~");
     test_join!("a~~~~~b", ["a", "b"], "~~~~~");
@@ -166,6 +170,7 @@
 }
 
 #[test]
+#[cfg(not(miri))]
 fn test_unsafe_slice() {
     assert_eq!("ab", unsafe {"abc".get_unchecked(0..2)});
     assert_eq!("bc", unsafe {"abc".get_unchecked(1..3)});
@@ -238,6 +243,7 @@
 #[test]
 fn test_replace() {
     let a = "a";
+    #[cfg(not(miri))]
     assert_eq!("".replace(a, "b"), "");
     assert_eq!("a".replace(a, "b"), "b");
     assert_eq!("ab".replace(a, "b"), "bb");
@@ -297,6 +303,7 @@
 // The current implementation of SliceIndex fails to handle methods
 // orthogonally from range types; therefore, it is worth testing
 // all of the indexing operations on each input.
+#[cfg(not(miri))]
 mod slice_index {
     // Test a slicing operation **that should succeed,**
     // testing it on all of the indexing methods.
@@ -679,6 +686,7 @@
 
 #[test]
 #[should_panic]
+#[cfg(not(miri))]
 fn test_str_slice_rangetoinclusive_notok() {
     let s = "abcαβγ";
     &s[..=3];
@@ -694,6 +702,7 @@
 
 #[test]
 #[should_panic]
+#[cfg(not(miri))]
 fn test_str_slicemut_rangetoinclusive_notok() {
     let mut s = "abcαβγ".to_owned();
     let s: &mut str = &mut s;
@@ -883,6 +892,7 @@
 
 #[test]
 #[should_panic]
+#[cfg(not(miri))]
 fn test_as_bytes_fail() {
     // Don't double free. (I'm not sure if this exercises the
     // original problem code path anymore.)
@@ -972,6 +982,7 @@
 
 #[test]
 #[should_panic]
+#[cfg(not(miri))]
 fn test_split_at_boundscheck() {
     let s = "ศไทย中华Việt Nam";
     s.split_at(1);
@@ -1066,6 +1077,7 @@
 }
 
 #[test]
+#[cfg(not(miri))]
 fn test_chars_decoding() {
     let mut bytes = [0; 4];
     for c in (0..0x110000).filter_map(std::char::from_u32) {
@@ -1077,6 +1089,7 @@
 }
 
 #[test]
+#[cfg(not(miri))]
 fn test_chars_rev_decoding() {
     let mut bytes = [0; 4];
     for c in (0..0x110000).filter_map(std::char::from_u32) {
@@ -1306,6 +1319,7 @@
 }
 
 #[test]
+#[cfg(not(miri))]
 fn test_str_default() {
     use std::default::Default;
 
@@ -1365,6 +1379,7 @@
     assert_eq!("not even a boolean".parse::<bool>().ok(), None);
 }
 
+#[cfg(not(miri))]
 fn check_contains_all_substrings(s: &str) {
     assert!(s.contains(""));
     for i in 0..s.len() {
@@ -1375,6 +1390,7 @@
 }
 
 #[test]
+#[cfg(not(miri))]
 fn strslice_issue_16589() {
     assert!("bananas".contains("nana"));
 
@@ -1384,6 +1400,7 @@
 }
 
 #[test]
+#[cfg(not(miri))]
 fn strslice_issue_16878() {
     assert!(!"1234567ah012345678901ah".contains("hah"));
     assert!(!"00abc01234567890123456789abc".contains("bcabc"));
@@ -1391,6 +1408,7 @@
 
 
 #[test]
+#[cfg(not(miri))]
 fn test_strslice_contains() {
     let x = "There are moments, Jeeves, when one asks oneself, 'Do trousers matter?'";
     check_contains_all_substrings(x);
@@ -1528,6 +1546,7 @@
 
 #[test]
 fn to_lowercase() {
+    #[cfg(not(miri))]
     assert_eq!("".to_lowercase(), "");
     assert_eq!("AÉDžaé ".to_lowercase(), "aédžaé ");
 
@@ -1561,6 +1580,7 @@
 
 #[test]
 fn to_uppercase() {
+    #[cfg(not(miri))]
     assert_eq!("".to_uppercase(), "");
     assert_eq!("aéDžßfiᾀ".to_uppercase(), "AÉDŽSSFIἈΙ");
 }
@@ -1592,6 +1612,7 @@
 }
 
 #[test]
+#[cfg(not(miri))]
 fn test_repeat() {
     assert_eq!("".repeat(3), "");
     assert_eq!("abc".repeat(0), "");
diff --git a/src/liballoc/tests/string.rs b/src/liballoc/tests/string.rs
index e5ce51a..e6ca54c 100644
--- a/src/liballoc/tests/string.rs
+++ b/src/liballoc/tests/string.rs
@@ -1,3 +1,5 @@
+#![cfg(not(miri))]
+
 use std::borrow::Cow;
 use std::collections::CollectionAllocErr::*;
 use std::mem::size_of;
diff --git a/src/liballoc/tests/vec.rs b/src/liballoc/tests/vec.rs
index 89f2e0a..545332b 100644
--- a/src/liballoc/tests/vec.rs
+++ b/src/liballoc/tests/vec.rs
@@ -1,3 +1,5 @@
+#![cfg(not(miri))]
+
 use std::borrow::Cow;
 use std::mem::size_of;
 use std::{usize, isize};
diff --git a/src/liballoc/tests/vec_deque.rs b/src/liballoc/tests/vec_deque.rs
index aa49bdb..b47e7c8 100644
--- a/src/liballoc/tests/vec_deque.rs
+++ b/src/liballoc/tests/vec_deque.rs
@@ -108,6 +108,7 @@
 
 #[test]
 #[should_panic]
+#[cfg(not(miri))]
 fn test_index_out_of_bounds() {
     let mut deq = VecDeque::new();
     for i in 1..4 {
@@ -906,20 +907,24 @@
     // normal append
     a.append(&mut b);
     assert_eq!(a.iter().cloned().collect::<Vec<_>>(), [1, 2, 3, 4, 5, 6]);
+    #[cfg(not(miri))]
     assert_eq!(b.iter().cloned().collect::<Vec<_>>(), []);
 
     // append nothing to something
     a.append(&mut b);
     assert_eq!(a.iter().cloned().collect::<Vec<_>>(), [1, 2, 3, 4, 5, 6]);
+    #[cfg(not(miri))]
     assert_eq!(b.iter().cloned().collect::<Vec<_>>(), []);
 
     // append something to nothing
     b.append(&mut a);
     assert_eq!(b.iter().cloned().collect::<Vec<_>>(), [1, 2, 3, 4, 5, 6]);
+    #[cfg(not(miri))]
     assert_eq!(a.iter().cloned().collect::<Vec<_>>(), []);
 }
 
 #[test]
+#[cfg(not(miri))]
 fn test_append_permutations() {
     fn construct_vec_deque(
         push_back: usize,
@@ -1120,6 +1125,7 @@
 }
 
 #[test]
+#[cfg(not(miri))]
 fn test_try_reserve() {
 
     // These are the interesting cases:
@@ -1221,6 +1227,7 @@
 }
 
 #[test]
+#[cfg(not(miri))]
 fn test_try_reserve_exact() {
 
     // This is exactly the same as test_try_reserve with the method changed.
diff --git a/src/libarena/Cargo.toml b/src/libarena/Cargo.toml
index e2af67d..82fc64b 100644
--- a/src/libarena/Cargo.toml
+++ b/src/libarena/Cargo.toml
@@ -2,6 +2,7 @@
 authors = ["The Rust Project Developers"]
 name = "arena"
 version = "0.0.0"
+edition = "2018"
 
 [lib]
 name = "arena"
@@ -9,4 +10,4 @@
 crate-type = ["dylib"]
 
 [dependencies]
-rustc_data_structures = { path = "../librustc_data_structures" }
\ No newline at end of file
+rustc_data_structures = { path = "../librustc_data_structures" }
diff --git a/src/libarena/lib.rs b/src/libarena/lib.rs
index 9f9ded5..8ae046c 100644
--- a/src/libarena/lib.rs
+++ b/src/libarena/lib.rs
@@ -8,22 +8,20 @@
 //! This crate implements `TypedArena`, a simple arena that can only hold
 //! objects of a single type.
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/",
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
        test(no_crate_inject, attr(deny(warnings))))]
 
+#![deny(rust_2018_idioms)]
+
 #![feature(alloc)]
 #![feature(core_intrinsics)]
 #![feature(dropck_eyepatch)]
-#![feature(nll)]
 #![feature(raw_vec_internals)]
 #![cfg_attr(test, feature(test))]
 
 #![allow(deprecated)]
 
 extern crate alloc;
-extern crate rustc_data_structures;
 
 use rustc_data_structures::sync::MTLock;
 
@@ -478,7 +476,7 @@
 #[cfg(test)]
 mod tests {
     extern crate test;
-    use self::test::Bencher;
+    use test::Bencher;
     use super::TypedArena;
     use std::cell::Cell;
 
@@ -513,15 +511,15 @@
 
         impl<'a> Wrap<'a> {
             fn alloc_inner<F: Fn() -> Inner>(&self, f: F) -> &Inner {
-                let r: &EI = self.0.alloc(EI::I(f()));
+                let r: &EI<'_> = self.0.alloc(EI::I(f()));
                 if let &EI::I(ref i) = r {
                     i
                 } else {
                     panic!("mismatch");
                 }
             }
-            fn alloc_outer<F: Fn() -> Outer<'a>>(&self, f: F) -> &Outer {
-                let r: &EI = self.0.alloc(EI::O(f()));
+            fn alloc_outer<F: Fn() -> Outer<'a>>(&self, f: F) -> &Outer<'_> {
+                let r: &EI<'_> = self.0.alloc(EI::O(f()));
                 if let &EI::O(ref o) = r {
                     o
                 } else {
@@ -611,7 +609,7 @@
         count: &'a Cell<u32>,
     }
 
-    impl<'a> Drop for DropCounter<'a> {
+    impl Drop for DropCounter<'_> {
         fn drop(&mut self) {
             self.count.set(self.count.get() + 1);
         }
@@ -621,7 +619,7 @@
     fn test_typed_arena_drop_count() {
         let counter = Cell::new(0);
         {
-            let arena: TypedArena<DropCounter> = TypedArena::default();
+            let arena: TypedArena<DropCounter<'_>> = TypedArena::default();
             for _ in 0..100 {
                 // Allocate something with drop glue to make sure it doesn't leak.
                 arena.alloc(DropCounter { count: &counter });
@@ -633,7 +631,7 @@
     #[test]
     fn test_typed_arena_drop_on_clear() {
         let counter = Cell::new(0);
-        let mut arena: TypedArena<DropCounter> = TypedArena::default();
+        let mut arena: TypedArena<DropCounter<'_>> = TypedArena::default();
         for i in 0..10 {
             for _ in 0..100 {
                 // Allocate something with drop glue to make sure it doesn't leak.
diff --git a/src/libcore/convert.rs b/src/libcore/convert.rs
index 203be54..d4a1d15 100644
--- a/src/libcore/convert.rs
+++ b/src/libcore/convert.rs
@@ -17,7 +17,10 @@
 //! [`TryFrom<T>`][`TryFrom`] rather than [`Into<U>`][`Into`] or [`TryInto<U>`][`TryInto`],
 //! as [`From`] and [`TryFrom`] provide greater flexibility and offer
 //! equivalent [`Into`] or [`TryInto`] implementations for free, thanks to a
-//! blanket implementation in the standard library.
+//! blanket implementation in the standard library.  However, there are some cases
+//! where this is not possible, such as creating conversions into a type defined
+//! outside your library, so implementing [`Into`] instead of [`From`] is
+//! sometimes necessary.
 //!
 //! # Generic Implementations
 //!
diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs
index 7180a81..8b728c9 100644
--- a/src/libcore/lib.rs
+++ b/src/libcore/lib.rs
@@ -24,7 +24,7 @@
 //!   often generated by LLVM. Additionally, this library can make explicit
 //!   calls to these functions. Their signatures are the same as found in C.
 //!   These functions are often provided by the system libc, but can also be
-//!   provided by the [rlibc crate](https://crates.io/crates/rlibc).
+//!   provided by the [compiler-builtins crate](https://crates.io/crates/compiler_builtins).
 //!
 //! * `rust_begin_panic` - This function takes four arguments, a
 //!   `fmt::Arguments`, a `&'static str`, and two `u32`'s. These four arguments
@@ -51,9 +51,7 @@
 #![cfg(not(test))]
 
 #![stable(feature = "core", since = "1.6.0")]
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/",
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
        html_playground_url = "https://play.rust-lang.org/",
        issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
        test(no_crate_inject, attr(deny(warnings))),
diff --git a/src/libcore/macros.rs b/src/libcore/macros.rs
index 12b7adb..664490c 100644
--- a/src/libcore/macros.rs
+++ b/src/libcore/macros.rs
@@ -555,12 +555,12 @@
 #[macro_export]
 #[unstable(feature = "maybe_uninit", issue = "53491")]
 macro_rules! uninitialized_array {
-    // This `into_inner` is safe because an array of `MaybeUninit` does not
+    // This `into_initialized` is safe because an array of `MaybeUninit` does not
     // require initialization.
     // FIXME(#49147): Could be replaced by an array initializer, once those can
     // be any const expression.
     ($t:ty; $size:expr) => (unsafe {
-        MaybeUninit::<[MaybeUninit<$t>; $size]>::uninitialized().into_inner()
+        MaybeUninit::<[MaybeUninit<$t>; $size]>::uninitialized().into_initialized()
     });
 }
 
diff --git a/src/libcore/mem.rs b/src/libcore/mem.rs
index 8b6d9d8..2f86e13 100644
--- a/src/libcore/mem.rs
+++ b/src/libcore/mem.rs
@@ -15,6 +15,7 @@
 use ops::{Deref, DerefMut};
 
 #[stable(feature = "rust1", since = "1.0.0")]
+#[doc(inline)]
 pub use intrinsics::transmute;
 
 /// Takes ownership and "forgets" about the value **without running its destructor**.
@@ -1034,7 +1035,42 @@
     }
 }
 
-/// A newtype to construct uninitialized instances of `T`
+/// A newtype to construct uninitialized instances of `T`.
+///
+/// The compiler, in general, assumes that variables are properly initialized
+/// at their respective type.  For example, a variable of reference type must
+/// be aligned and non-NULL.  This is an invariant that must *always* be upheld,
+/// even in unsafe code.  As a consequence, 0-initializing a variable of reference
+/// type causes instantaneous undefined behavior, no matter whether that reference
+/// ever gets used to access memory:
+/// ```rust,no_run
+/// use std::mem;
+///
+/// let x: &i32 = unsafe { mem::zeroed() }; // undefined behavior!
+/// ```
+/// This is exploited by the compiler for various optimizations, such as eliding
+/// run-time checks and optimizing `enum` layout.
+///
+/// Not initializing memory at all (instead of 0-initializing it) causes the same
+/// issue: after all, the initial value of the variable might just happen to be
+/// one that violates the invariant.
+///
+/// `MaybeUninit` serves to enable unsafe code to deal with uninitialized data:
+/// it is a signal to the compiler indicating that the data here might *not*
+/// be initialized:
+/// ```rust
+/// #![feature(maybe_uninit)]
+/// use std::mem::MaybeUninit;
+///
+/// // Create an explicitly uninitialized reference.
+/// let mut x = MaybeUninit::<&i32>::uninitialized();
+/// // Set it to a valid value.
+/// x.set(&0);
+/// // Extract the initialized data -- this is only allowed *after* properly
+/// // initializing `x`!
+/// let x = unsafe { x.into_initialized() };
+/// ```
+/// The compiler then knows to not optimize this code.
 #[allow(missing_debug_implementations)]
 #[unstable(feature = "maybe_uninit", issue = "53491")]
 // NOTE after stabilizing `MaybeUninit` proceed to deprecate `mem::{uninitialized,zeroed}`
@@ -1083,11 +1119,14 @@
     }
 
     /// Set the value of the `MaybeUninit`. This overwrites any previous value without dropping it.
+    /// For your convenience, this also returns a mutable reference to the (now
+    /// safely initialized) content of `self`.
     #[unstable(feature = "maybe_uninit", issue = "53491")]
     #[inline(always)]
-    pub fn set(&mut self, val: T) {
+    pub fn set(&mut self, val: T) -> &mut T {
         unsafe {
             self.value = ManuallyDrop::new(val);
+            self.get_mut()
         }
     }
 
@@ -1101,11 +1140,19 @@
     /// state, otherwise this will immediately cause undefined behavior.
     #[unstable(feature = "maybe_uninit", issue = "53491")]
     #[inline(always)]
-    pub unsafe fn into_inner(self) -> T {
+    pub unsafe fn into_initialized(self) -> T {
         intrinsics::panic_if_uninhabited::<T>();
         ManuallyDrop::into_inner(self.value)
     }
 
+    /// Deprecated alternative to `into_initialized`.  Will never get stabilized.
+    /// Exists only to transition stdsimd to `into_initialized`.
+    #[inline(always)]
+    #[allow(unused)]
+    pub(crate) unsafe fn into_inner(self) -> T {
+        self.into_initialized()
+    }
+
     /// Get a reference to the contained value.
     ///
     /// # Unsafety
@@ -1133,16 +1180,16 @@
         &mut *self.value
     }
 
-    /// Get a pointer to the contained value. Reading from this pointer will be undefined
-    /// behavior unless the `MaybeUninit` is initialized.
+    /// Get a pointer to the contained value. Reading from this pointer or turning it
+    /// into a reference will be undefined behavior unless the `MaybeUninit` is initialized.
     #[unstable(feature = "maybe_uninit", issue = "53491")]
     #[inline(always)]
     pub fn as_ptr(&self) -> *const T {
         unsafe { &*self.value as *const T }
     }
 
-    /// Get a mutable pointer to the contained value. Reading from this pointer will be undefined
-    /// behavior unless the `MaybeUninit` is initialized.
+    /// Get a mutable pointer to the contained value. Reading from this pointer or turning it
+    /// into a reference will be undefined behavior unless the `MaybeUninit` is initialized.
     #[unstable(feature = "maybe_uninit", issue = "53491")]
     #[inline(always)]
     pub fn as_mut_ptr(&mut self) -> *mut T {
diff --git a/src/libcore/ops/function.rs b/src/libcore/ops/function.rs
index 3a1d765..c69f5fd 100644
--- a/src/libcore/ops/function.rs
+++ b/src/libcore/ops/function.rs
@@ -62,7 +62,7 @@
     label="expected an `Fn<{Args}>` closure, found `{Self}`",
 )]
 #[fundamental] // so that regex can rely that `&str: !FnMut`
-#[must_use]
+#[must_use = "closures are lazy and do nothing unless called"]
 pub trait Fn<Args> : FnMut<Args> {
     /// Performs the call operation.
     #[unstable(feature = "fn_traits", issue = "29625")]
@@ -141,7 +141,7 @@
     label="expected an `FnMut<{Args}>` closure, found `{Self}`",
 )]
 #[fundamental] // so that regex can rely that `&str: !FnMut`
-#[must_use]
+#[must_use = "closures are lazy and do nothing unless called"]
 pub trait FnMut<Args> : FnOnce<Args> {
     /// Performs the call operation.
     #[unstable(feature = "fn_traits", issue = "29625")]
@@ -220,7 +220,7 @@
     label="expected an `FnOnce<{Args}>` closure, found `{Self}`",
 )]
 #[fundamental] // so that regex can rely that `&str: !FnMut`
-#[must_use]
+#[must_use = "closures are lazy and do nothing unless called"]
 pub trait FnOnce<Args> {
     /// The returned type after the call operator is used.
     #[stable(feature = "fn_once_output", since = "1.12.0")]
diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs
index 02eef07..537aa92 100644
--- a/src/libcore/ptr.rs
+++ b/src/libcore/ptr.rs
@@ -573,7 +573,7 @@
 pub unsafe fn read<T>(src: *const T) -> T {
     let mut tmp = MaybeUninit::<T>::uninitialized();
     copy_nonoverlapping(src, tmp.as_mut_ptr(), 1);
-    tmp.into_inner()
+    tmp.into_initialized()
 }
 
 /// Reads the value from `src` without moving it. This leaves the
@@ -642,7 +642,7 @@
     copy_nonoverlapping(src as *const u8,
                         tmp.as_mut_ptr() as *mut u8,
                         mem::size_of::<T>());
-    tmp.into_inner()
+    tmp.into_initialized()
 }
 
 /// Overwrites a memory location with the given value without reading or
diff --git a/src/libcore/tests/cell.rs b/src/libcore/tests/cell.rs
index 56f295d..73bdaab 100644
--- a/src/libcore/tests/cell.rs
+++ b/src/libcore/tests/cell.rs
@@ -1,3 +1,5 @@
+#![cfg(not(miri))]
+
 use core::cell::*;
 use core::default::Default;
 use std::mem::drop;
diff --git a/src/libcore/tests/fmt/mod.rs b/src/libcore/tests/fmt/mod.rs
index d86e21c..b10b63f 100644
--- a/src/libcore/tests/fmt/mod.rs
+++ b/src/libcore/tests/fmt/mod.rs
@@ -1,3 +1,5 @@
+#![cfg(not(miri))]
+
 mod builders;
 mod float;
 mod num;
diff --git a/src/libcore/tests/hash/mod.rs b/src/libcore/tests/hash/mod.rs
index 135f4df..bf3039a 100644
--- a/src/libcore/tests/hash/mod.rs
+++ b/src/libcore/tests/hash/mod.rs
@@ -1,3 +1,5 @@
+#![cfg(not(miri))]
+
 mod sip;
 
 use std::hash::{Hash, Hasher};
diff --git a/src/libcore/tests/iter.rs b/src/libcore/tests/iter.rs
index 0fa9974..9b4c78f 100644
--- a/src/libcore/tests/iter.rs
+++ b/src/libcore/tests/iter.rs
@@ -190,6 +190,7 @@
 }
 
 #[test]
+#[cfg(not(miri))]
 fn test_iterator_step_by_nth() {
     let mut it = (0..16).step_by(5);
     assert_eq!(it.nth(0), Some(0));
@@ -208,6 +209,7 @@
 }
 
 #[test]
+#[cfg(not(miri))]
 fn test_iterator_step_by_nth_overflow() {
     #[cfg(target_pointer_width = "8")]
     type Bigger = u16;
@@ -253,12 +255,14 @@
 
 #[test]
 #[should_panic]
+#[cfg(not(miri))]
 fn test_iterator_step_by_zero() {
     let mut it = (0..).step_by(0);
     it.next();
 }
 
 #[test]
+#[cfg(not(miri))]
 fn test_iterator_step_by_size_hint() {
     struct StubSizeHint(usize, Option<usize>);
     impl Iterator for StubSizeHint {
@@ -1413,6 +1417,7 @@
 
 #[test]
 #[should_panic]
+#[cfg(not(miri))]
 fn test_rposition_panic() {
     let v: [(Box<_>, Box<_>); 4] =
         [(box 0, box 0), (box 0, box 0),
@@ -1652,6 +1657,7 @@
 }
 
 #[test]
+#[cfg(not(miri))]
 fn test_range_step() {
     #![allow(deprecated)]
 
@@ -1675,6 +1681,7 @@
 }
 
 #[test]
+#[cfg(not(miri))]
 fn test_step_by_skip() {
     assert_eq!((0..640).step_by(128).skip(1).collect::<Vec<_>>(), [128, 256, 384, 512]);
     assert_eq!((0..=50).step_by(10).nth(3), Some(30));
@@ -1682,6 +1689,7 @@
 }
 
 #[test]
+#[cfg(not(miri))]
 fn test_range_inclusive_step() {
     assert_eq!((0..=50).step_by(10).collect::<Vec<_>>(), [0, 10, 20, 30, 40, 50]);
     assert_eq!((0..=5).step_by(1).collect::<Vec<_>>(), [0, 1, 2, 3, 4, 5]);
diff --git a/src/libcore/tests/num/mod.rs b/src/libcore/tests/num/mod.rs
index a17c094..ab638e0 100644
--- a/src/libcore/tests/num/mod.rs
+++ b/src/libcore/tests/num/mod.rs
@@ -1,3 +1,5 @@
+#![cfg(not(miri))]
+
 use core::convert::{TryFrom, TryInto};
 use core::cmp::PartialEq;
 use core::fmt::Debug;
diff --git a/src/libcore/tests/option.rs b/src/libcore/tests/option.rs
index b059b13..1ba886c 100644
--- a/src/libcore/tests/option.rs
+++ b/src/libcore/tests/option.rs
@@ -69,6 +69,7 @@
 }
 
 #[test] #[should_panic]
+#[cfg(not(miri))]
 fn test_option_too_much_dance() {
     struct A;
     let mut y = Some(A);
@@ -129,6 +130,7 @@
 
 #[test]
 #[should_panic]
+#[cfg(not(miri))]
 fn test_unwrap_panic1() {
     let x: Option<isize> = None;
     x.unwrap();
@@ -136,6 +138,7 @@
 
 #[test]
 #[should_panic]
+#[cfg(not(miri))]
 fn test_unwrap_panic2() {
     let x: Option<String> = None;
     x.unwrap();
diff --git a/src/libcore/tests/ptr.rs b/src/libcore/tests/ptr.rs
index 65c1a3e..5784559 100644
--- a/src/libcore/tests/ptr.rs
+++ b/src/libcore/tests/ptr.rs
@@ -1,3 +1,5 @@
+#![cfg(not(miri))]
+
 use core::ptr::*;
 use core::cell::RefCell;
 
diff --git a/src/libcore/tests/result.rs b/src/libcore/tests/result.rs
index 1fab075..7bfd396 100644
--- a/src/libcore/tests/result.rs
+++ b/src/libcore/tests/result.rs
@@ -117,6 +117,7 @@
 
 #[test]
 #[should_panic]
+#[cfg(not(miri))]
 pub fn test_unwrap_or_else_panic() {
     fn handler(msg: &'static str) -> isize {
         if msg == "I got this." {
@@ -138,6 +139,7 @@
 }
 #[test]
 #[should_panic(expected="Got expected error: \"All good\"")]
+#[cfg(not(miri))]
 pub fn test_expect_err() {
     let err: Result<isize, &'static str> = Err("All good");
     err.expect("Got expected error");
@@ -151,6 +153,7 @@
 }
 #[test]
 #[should_panic(expected="Got expected ok: \"All good\"")]
+#[cfg(not(miri))]
 pub fn test_expect_err_ok() {
     let err: Result<&'static str, isize> = Ok("All good");
     err.expect_err("Got expected ok");
diff --git a/src/libcore/tests/slice.rs b/src/libcore/tests/slice.rs
index e210e83..04d646e 100644
--- a/src/libcore/tests/slice.rs
+++ b/src/libcore/tests/slice.rs
@@ -782,6 +782,7 @@
     //  to be used in `should_panic`)
     #[test]
     #[should_panic(expected = "out of range")]
+    #[cfg(not(miri))]
     fn assert_range_eq_can_fail_by_panic() {
         assert_range_eq!([0, 1, 2], 0..5, [0, 1, 2]);
     }
@@ -791,6 +792,7 @@
     //  to be used in `should_panic`)
     #[test]
     #[should_panic(expected = "==")]
+    #[cfg(not(miri))]
     fn assert_range_eq_can_fail_by_inequality() {
         assert_range_eq!([0, 1, 2], 0..2, [0, 1, 2]);
     }
@@ -840,6 +842,7 @@
 
                 #[test]
                 #[should_panic(expected = $expect_msg)]
+                #[cfg(not(miri))]
                 fn index_fail() {
                     let v = $data;
                     let v: &[_] = &v;
@@ -848,6 +851,7 @@
 
                 #[test]
                 #[should_panic(expected = $expect_msg)]
+                #[cfg(not(miri))]
                 fn index_mut_fail() {
                     let mut v = $data;
                     let v: &mut [_] = &mut v;
@@ -1011,6 +1015,7 @@
 
 #[test]
 #[cfg(not(target_arch = "wasm32"))]
+#[cfg(not(miri))]
 fn sort_unstable() {
     use core::cmp::Ordering::{Equal, Greater, Less};
     use core::slice::heapsort;
@@ -1166,6 +1171,7 @@
 }
 
 #[test]
+#[cfg(not(miri))]
 fn test_align_to_simple() {
     let bytes = [1u8, 2, 3, 4, 5, 6, 7];
     let (prefix, aligned, suffix) = unsafe { bytes.align_to::<u16>() };
@@ -1181,6 +1187,7 @@
 }
 
 #[test]
+#[cfg(not(miri))]
 fn test_align_to_zst() {
     let bytes = [1, 2, 3, 4, 5, 6, 7];
     let (prefix, aligned, suffix) = unsafe { bytes.align_to::<()>() };
@@ -1189,6 +1196,7 @@
 }
 
 #[test]
+#[cfg(not(miri))]
 fn test_align_to_non_trivial() {
     #[repr(align(8))] struct U64(u64, u64);
     #[repr(align(8))] struct U64U64U32(u64, u64, u32);
@@ -1200,6 +1208,7 @@
 }
 
 #[test]
+#[cfg(not(miri))]
 fn test_align_to_empty_mid() {
     use core::mem;
 
@@ -1297,6 +1306,7 @@
 
 #[test]
 #[should_panic(expected = "src is out of bounds")]
+#[cfg(not(miri))]
 fn test_copy_within_panics_src_too_long() {
     let mut bytes = *b"Hello, World!";
     // The length is only 13, so 14 is out of bounds.
@@ -1305,6 +1315,7 @@
 
 #[test]
 #[should_panic(expected = "dest is out of bounds")]
+#[cfg(not(miri))]
 fn test_copy_within_panics_dest_too_long() {
     let mut bytes = *b"Hello, World!";
     // The length is only 13, so a slice of length 4 starting at index 10 is out of bounds.
@@ -1312,6 +1323,7 @@
 }
 #[test]
 #[should_panic(expected = "src end is before src start")]
+#[cfg(not(miri))]
 fn test_copy_within_panics_src_inverted() {
     let mut bytes = *b"Hello, World!";
     // 2 is greater than 1, so this range is invalid.
diff --git a/src/libcore/tests/time.rs b/src/libcore/tests/time.rs
index 6efd225..d39bd06 100644
--- a/src/libcore/tests/time.rs
+++ b/src/libcore/tests/time.rs
@@ -1,3 +1,5 @@
+#![cfg(not(miri))]
+
 use core::time::Duration;
 
 #[test]
diff --git a/src/libfmt_macros/lib.rs b/src/libfmt_macros/lib.rs
index 7bfe237..ea67c01 100644
--- a/src/libfmt_macros/lib.rs
+++ b/src/libfmt_macros/lib.rs
@@ -4,9 +4,7 @@
 //! Parsing does not happen at runtime: structures of `std::fmt::rt` are
 //! generated instead.
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/",
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
        html_playground_url = "https://play.rust-lang.org/",
        test(attr(deny(warnings))))]
 
diff --git a/src/libgraphviz/lib.rs b/src/libgraphviz/lib.rs
index f05f6e6..8ce0f75 100644
--- a/src/libgraphviz/lib.rs
+++ b/src/libgraphviz/lib.rs
@@ -271,9 +271,7 @@
 //!
 //! * [DOT language](http://www.graphviz.org/doc/info/lang.html)
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/",
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
        test(attr(allow(unused_variables), deny(warnings))))]
 
 #![deny(rust_2018_idioms)]
diff --git a/src/libpanic_abort/lib.rs b/src/libpanic_abort/lib.rs
index daa1998..7c6f36e 100644
--- a/src/libpanic_abort/lib.rs
+++ b/src/libpanic_abort/lib.rs
@@ -5,9 +5,7 @@
 
 #![no_std]
 #![unstable(feature = "panic_abort", issue = "32837")]
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/",
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
        issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/")]
 #![panic_runtime]
 
diff --git a/src/libpanic_unwind/lib.rs b/src/libpanic_unwind/lib.rs
index 98f1747..fa7a091 100644
--- a/src/libpanic_unwind/lib.rs
+++ b/src/libpanic_unwind/lib.rs
@@ -14,9 +14,7 @@
 
 #![no_std]
 #![unstable(feature = "panic_unwind", issue = "32837")]
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/",
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
        issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/")]
 
 #![feature(allocator_api)]
diff --git a/src/libproc_macro/lib.rs b/src/libproc_macro/lib.rs
index bb6f5e2..2cdc5a4 100644
--- a/src/libproc_macro/lib.rs
+++ b/src/libproc_macro/lib.rs
@@ -9,9 +9,7 @@
 
 #![stable(feature = "proc_macro_lib", since = "1.15.0")]
 #![deny(missing_docs)]
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/",
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
        html_playground_url = "https://play.rust-lang.org/",
        issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
        test(no_crate_inject, attr(deny(warnings))),
diff --git a/src/librustc/dep_graph/graph.rs b/src/librustc/dep_graph/graph.rs
index 663c408..e8c1cd3 100644
--- a/src/librustc/dep_graph/graph.rs
+++ b/src/librustc/dep_graph/graph.rs
@@ -79,6 +79,16 @@
     loaded_from_cache: Lock<FxHashMap<DepNodeIndex, bool>>,
 }
 
+pub fn hash_result<R>(hcx: &mut StableHashingContext<'_>, result: &R) -> Option<Fingerprint>
+where
+    R: for<'a> HashStable<StableHashingContext<'a>>,
+{
+    let mut stable_hasher = StableHasher::new();
+    result.hash_stable(hcx, &mut stable_hasher);
+
+    Some(stable_hasher.finish())
+}
+
 impl DepGraph {
 
     pub fn new(prev_graph: PreviousDepGraph,
@@ -178,14 +188,16 @@
     ///   `arg` parameter.
     ///
     /// [rustc guide]: https://rust-lang.github.io/rustc-guide/incremental-compilation.html
-    pub fn with_task<'gcx, C, A, R>(&self,
-                                   key: DepNode,
-                                   cx: C,
-                                   arg: A,
-                                   task: fn(C, A) -> R)
-                                   -> (R, DepNodeIndex)
-        where C: DepGraphSafe + StableHashingContextProvider<'gcx>,
-              R: HashStable<StableHashingContext<'gcx>>,
+    pub fn with_task<'a, C, A, R>(
+        &self,
+        key: DepNode,
+        cx: C,
+        arg: A,
+        task: fn(C, A) -> R,
+        hash_result: impl FnOnce(&mut StableHashingContext<'_>, &R) -> Option<Fingerprint>,
+    ) -> (R, DepNodeIndex)
+    where
+        C: DepGraphSafe + StableHashingContextProvider<'a>,
     {
         self.with_task_impl(key, cx, arg, false, task,
             |_key| Some(TaskDeps {
@@ -196,17 +208,18 @@
             }),
             |data, key, fingerprint, task| {
                 data.borrow_mut().complete_task(key, task.unwrap(), fingerprint)
-            })
+            },
+            hash_result)
     }
 
     /// Creates a new dep-graph input with value `input`
-    pub fn input_task<'gcx, C, R>(&self,
+    pub fn input_task<'a, C, R>(&self,
                                    key: DepNode,
                                    cx: C,
                                    input: R)
                                    -> (R, DepNodeIndex)
-        where C: DepGraphSafe + StableHashingContextProvider<'gcx>,
-              R: HashStable<StableHashingContext<'gcx>>,
+        where C: DepGraphSafe + StableHashingContextProvider<'a>,
+              R: for<'b> HashStable<StableHashingContext<'b>>,
     {
         fn identity_fn<C, A>(_: C, arg: A) -> A {
             arg
@@ -216,10 +229,11 @@
             |_| None,
             |data, key, fingerprint, _| {
                 data.borrow_mut().alloc_node(key, SmallVec::new(), fingerprint)
-            })
+            },
+            hash_result::<R>)
     }
 
-    fn with_task_impl<'gcx, C, A, R>(
+    fn with_task_impl<'a, C, A, R>(
         &self,
         key: DepNode,
         cx: C,
@@ -230,11 +244,11 @@
         finish_task_and_alloc_depnode: fn(&Lock<CurrentDepGraph>,
                                           DepNode,
                                           Fingerprint,
-                                          Option<TaskDeps>) -> DepNodeIndex
+                                          Option<TaskDeps>) -> DepNodeIndex,
+        hash_result: impl FnOnce(&mut StableHashingContext<'_>, &R) -> Option<Fingerprint>,
     ) -> (R, DepNodeIndex)
     where
-        C: DepGraphSafe + StableHashingContextProvider<'gcx>,
-        R: HashStable<StableHashingContext<'gcx>>,
+        C: DepGraphSafe + StableHashingContextProvider<'a>,
     {
         if let Some(ref data) = self.data {
             let task_deps = create_task(key).map(|deps| Lock::new(deps));
@@ -269,15 +283,12 @@
                 profq_msg(hcx.sess(), ProfileQueriesMsg::TaskEnd)
             };
 
-            let mut stable_hasher = StableHasher::new();
-            result.hash_stable(&mut hcx, &mut stable_hasher);
-
-            let current_fingerprint = stable_hasher.finish();
+            let current_fingerprint = hash_result(&mut hcx, &result);
 
             let dep_node_index = finish_task_and_alloc_depnode(
                 &data.current,
                 key,
-                current_fingerprint,
+                current_fingerprint.unwrap_or(Fingerprint::ZERO),
                 task_deps.map(|lock| lock.into_inner()),
             );
 
@@ -285,15 +296,20 @@
             if let Some(prev_index) = data.previous.node_to_index_opt(&key) {
                 let prev_fingerprint = data.previous.fingerprint_by_index(prev_index);
 
-                let color = if current_fingerprint == prev_fingerprint {
-                    DepNodeColor::Green(dep_node_index)
+                let color = if let Some(current_fingerprint) = current_fingerprint {
+                    if current_fingerprint == prev_fingerprint {
+                        DepNodeColor::Green(dep_node_index)
+                    } else {
+                        DepNodeColor::Red
+                    }
                 } else {
+                    // Mark the node as Red if we can't hash the result
                     DepNodeColor::Red
                 };
 
                 debug_assert!(data.colors.get(prev_index).is_none(),
-                              "DepGraph::with_task() - Duplicate DepNodeColor \
-                               insertion for {:?}", key);
+                            "DepGraph::with_task() - Duplicate DepNodeColor \
+                            insertion for {:?}", key);
 
                 data.colors.insert(prev_index, color);
             }
@@ -342,14 +358,16 @@
 
     /// Execute something within an "eval-always" task which is a task
     // that runs whenever anything changes.
-    pub fn with_eval_always_task<'gcx, C, A, R>(&self,
-                                   key: DepNode,
-                                   cx: C,
-                                   arg: A,
-                                   task: fn(C, A) -> R)
-                                   -> (R, DepNodeIndex)
-        where C: DepGraphSafe + StableHashingContextProvider<'gcx>,
-              R: HashStable<StableHashingContext<'gcx>>,
+    pub fn with_eval_always_task<'a, C, A, R>(
+        &self,
+        key: DepNode,
+        cx: C,
+        arg: A,
+        task: fn(C, A) -> R,
+        hash_result: impl FnOnce(&mut StableHashingContext<'_>, &R) -> Option<Fingerprint>,
+    ) -> (R, DepNodeIndex)
+    where
+        C: DepGraphSafe + StableHashingContextProvider<'a>,
     {
         self.with_task_impl(key, cx, arg, false, task,
             |_| None,
@@ -359,7 +377,8 @@
                     &DepNode::new_no_params(DepKind::Krate)
                 ];
                 current.alloc_node(key, smallvec![krate_idx], fingerprint)
-            })
+            },
+            hash_result)
     }
 
     #[inline]
diff --git a/src/librustc/dep_graph/mod.rs b/src/librustc/dep_graph/mod.rs
index 022caab..b84d2ad 100644
--- a/src/librustc/dep_graph/mod.rs
+++ b/src/librustc/dep_graph/mod.rs
@@ -10,7 +10,7 @@
 
 pub use self::dep_tracking_map::{DepTrackingMap, DepTrackingMapConfig};
 pub use self::dep_node::{DepNode, DepKind, DepConstructor, WorkProductId, label_strs};
-pub use self::graph::{DepGraph, WorkProduct, DepNodeIndex, DepNodeColor, TaskDeps};
+pub use self::graph::{DepGraph, WorkProduct, DepNodeIndex, DepNodeColor, TaskDeps, hash_result};
 pub use self::graph::WorkProductFileKind;
 pub use self::prev::PreviousDepGraph;
 pub use self::query::DepGraphQuery;
diff --git a/src/librustc/hir/def.rs b/src/librustc/hir/def.rs
index 6566c60..15efa76 100644
--- a/src/librustc/hir/def.rs
+++ b/src/librustc/hir/def.rs
@@ -52,6 +52,7 @@
     AssociatedExistential(DefId),
     PrimTy(hir::PrimTy),
     TyParam(DefId),
+    ConstParam(DefId),
     SelfTy(Option<DefId> /* trait */, Option<DefId> /* impl */),
     ToolMod, // e.g., `rustfmt` in `#[rustfmt::skip]`
 
@@ -265,7 +266,8 @@
             Def::Fn(id) | Def::Mod(id) | Def::Static(id, _) |
             Def::Variant(id) | Def::VariantCtor(id, ..) | Def::Enum(id) |
             Def::TyAlias(id) | Def::TraitAlias(id) |
-            Def::AssociatedTy(id) | Def::TyParam(id) | Def::Struct(id) | Def::StructCtor(id, ..) |
+            Def::AssociatedTy(id) | Def::TyParam(id) | Def::ConstParam(id) | Def::Struct(id) |
+            Def::StructCtor(id, ..) |
             Def::Union(id) | Def::Trait(id) | Def::Method(id) | Def::Const(id) |
             Def::AssociatedConst(id) | Def::Macro(id, ..) |
             Def::Existential(id) | Def::AssociatedExistential(id) | Def::ForeignTy(id) => {
@@ -322,6 +324,7 @@
             Def::Const(..) => "constant",
             Def::AssociatedConst(..) => "associated constant",
             Def::TyParam(..) => "type parameter",
+            Def::ConstParam(..) => "const parameter",
             Def::PrimTy(..) => "builtin type",
             Def::Local(..) => "local variable",
             Def::Upvar(..) => "closure capture",
diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs
index d0fd5bd..3de41b1 100644
--- a/src/librustc/hir/lowering.rs
+++ b/src/librustc/hir/lowering.rs
@@ -1157,6 +1157,15 @@
         match arg {
             ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(&lt)),
             ast::GenericArg::Type(ty) => GenericArg::Type(self.lower_ty_direct(&ty, itctx)),
+            ast::GenericArg::Const(ct) => {
+                // FIXME(const_generics): const generics are not yet defined in the HIR.
+                self.sess.struct_span_err(
+                    ct.value.span,
+                    "const generics in any position are currently unsupported",
+                ).emit();
+                self.sess.abort_if_errors();
+                bug!();
+            }
         }
     }
 
@@ -2441,7 +2450,7 @@
             |this| this.lower_param_bounds(&param.bounds, itctx.reborrow()),
         );
 
-        match param.kind {
+        let (name, kind) = match param.kind {
             GenericParamKind::Lifetime => {
                 let was_collecting_in_band = self.is_collecting_in_band_lifetimes;
                 self.is_collecting_in_band_lifetimes = false;
@@ -2457,22 +2466,14 @@
                         | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()),
                     hir::LifetimeName::Error => ParamName::Error,
                 };
-                let param = hir::GenericParam {
-                    id: lt.id,
-                    hir_id: lt.hir_id,
-                    name: param_name,
-                    span: lt.span,
-                    pure_wrt_drop: attr::contains_name(&param.attrs, "may_dangle"),
-                    attrs: self.lower_attrs(&param.attrs),
-                    bounds,
-                    kind: hir::GenericParamKind::Lifetime {
-                        kind: hir::LifetimeParamKind::Explicit,
-                    }
+
+                let kind = hir::GenericParamKind::Lifetime {
+                    kind: hir::LifetimeParamKind::Explicit
                 };
 
                 self.is_collecting_in_band_lifetimes = was_collecting_in_band;
 
-                param
+                (param_name, kind)
             }
             GenericParamKind::Type { ref default, .. } => {
                 // Don't expose `Self` (recovered "keyword used as ident" parse error).
@@ -2491,27 +2492,41 @@
                                    .chain(params)
                                    .collect();
                 }
-                let LoweredNodeId { node_id, hir_id } = self.lower_node_id(param.id);
 
-                hir::GenericParam {
-                    id: node_id,
-                    hir_id,
-                    name: hir::ParamName::Plain(ident),
-                    pure_wrt_drop: attr::contains_name(&param.attrs, "may_dangle"),
-                    attrs: self.lower_attrs(&param.attrs),
-                    bounds,
-                    span: ident.span,
-                    kind: hir::GenericParamKind::Type {
-                        default: default.as_ref().map(|x| {
-                            self.lower_ty(x, ImplTraitContext::disallowed())
-                        }),
-                        synthetic: param.attrs.iter()
-                                              .filter(|attr| attr.check_name("rustc_synthetic"))
-                                              .map(|_| hir::SyntheticTyParamKind::ImplTrait)
-                                              .next(),
-                    }
-                }
+                let kind = hir::GenericParamKind::Type {
+                    default: default.as_ref().map(|x| {
+                        self.lower_ty(x, ImplTraitContext::disallowed())
+                    }),
+                    synthetic: param.attrs.iter()
+                                          .filter(|attr| attr.check_name("rustc_synthetic"))
+                                          .map(|_| hir::SyntheticTyParamKind::ImplTrait)
+                                          .next(),
+                };
+
+                (hir::ParamName::Plain(ident), kind)
             }
+            GenericParamKind::Const { .. } => {
+                // FIXME(const_generics): const generics are not yet defined in the HIR.
+                self.sess.struct_span_err(
+                    param.ident.span,
+                    "const generics in any position are currently unsupported",
+                ).emit();
+                self.sess.abort_if_errors();
+                bug!();
+            }
+        };
+
+        let LoweredNodeId { node_id, hir_id } = self.lower_node_id(param.id);
+
+        hir::GenericParam {
+            id: node_id,
+            hir_id,
+            name,
+            span: param.ident.span,
+            pure_wrt_drop: attr::contains_name(&param.attrs, "may_dangle"),
+            attrs: self.lower_attrs(&param.attrs),
+            bounds,
+            kind,
         }
     }
 
diff --git a/src/librustc/hir/map/collector.rs b/src/librustc/hir/map/collector.rs
index f84bb77..37552f1 100644
--- a/src/librustc/hir/map/collector.rs
+++ b/src/librustc/hir/map/collector.rs
@@ -48,14 +48,14 @@
     hir_body_nodes: Vec<(DefPathHash, Fingerprint)>,
 }
 
-fn input_dep_node_and_hash<'a, I>(
+fn input_dep_node_and_hash<I>(
     dep_graph: &DepGraph,
-    hcx: &mut StableHashingContext<'a>,
+    hcx: &mut StableHashingContext<'_>,
     dep_node: DepNode,
     input: I,
 ) -> (DepNodeIndex, Fingerprint)
 where
-    I: HashStable<StableHashingContext<'a>>,
+    I: for<'a> HashStable<StableHashingContext<'a>>,
 {
     let dep_node_index = dep_graph.input_task(dep_node, &mut *hcx, &input).1;
 
@@ -70,15 +70,15 @@
     (dep_node_index, hash)
 }
 
-fn alloc_hir_dep_nodes<'a, I>(
+fn alloc_hir_dep_nodes<I>(
     dep_graph: &DepGraph,
-    hcx: &mut StableHashingContext<'a>,
+    hcx: &mut StableHashingContext<'_>,
     def_path_hash: DefPathHash,
     item_like: I,
     hir_body_nodes: &mut Vec<(DefPathHash, Fingerprint)>,
 ) -> (DepNodeIndex, DepNodeIndex)
 where
-    I: HashStable<StableHashingContext<'a>>,
+    I: for<'a> HashStable<StableHashingContext<'a>>,
 {
     let sig = dep_graph.input_task(
         def_path_hash.to_dep_node(DepKind::Hir),
@@ -286,7 +286,7 @@
         self.parent_node = parent_node;
     }
 
-    fn with_dep_node_owner<T: HashStable<StableHashingContext<'a>>,
+    fn with_dep_node_owner<T: for<'b> HashStable<StableHashingContext<'b>>,
                            F: FnOnce(&mut Self)>(&mut self,
                                                  dep_node_owner: DefIndex,
                                                  item_like: &T,
diff --git a/src/librustc/hir/map/def_collector.rs b/src/librustc/hir/map/def_collector.rs
index 7101706..02fb503 100644
--- a/src/librustc/hir/map/def_collector.rs
+++ b/src/librustc/hir/map/def_collector.rs
@@ -218,6 +218,7 @@
         let def_path_data = match param.kind {
             GenericParamKind::Lifetime { .. } => DefPathData::LifetimeParam(name),
             GenericParamKind::Type { .. } => DefPathData::TypeParam(name),
+            GenericParamKind::Const { .. } => DefPathData::ConstParam(name),
         };
         self.create_def(param.id, def_path_data, REGULAR_SPACE, param.ident.span);
 
diff --git a/src/librustc/hir/map/definitions.rs b/src/librustc/hir/map/definitions.rs
index a8193e1..84e9cde 100644
--- a/src/librustc/hir/map/definitions.rs
+++ b/src/librustc/hir/map/definitions.rs
@@ -356,10 +356,12 @@
     /// A closure expression
     ClosureExpr,
     // Subportions of items
-    /// A type parameter (generic parameter)
+    /// A type (generic) parameter
     TypeParam(InternedString),
-    /// A lifetime definition
+    /// A lifetime (generic) parameter
     LifetimeParam(InternedString),
+    /// A const (generic) parameter
+    ConstParam(InternedString),
     /// A variant of a enum
     EnumVariant(InternedString),
     /// A struct field
@@ -641,6 +643,7 @@
             MacroDef(name) |
             TypeParam(name) |
             LifetimeParam(name) |
+            ConstParam(name) |
             EnumVariant(name) |
             Field(name) |
             GlobalMetaData(name) => Some(name),
@@ -669,6 +672,7 @@
             MacroDef(name) |
             TypeParam(name) |
             LifetimeParam(name) |
+            ConstParam(name) |
             EnumVariant(name) |
             Field(name) |
             GlobalMetaData(name) => {
diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs
index 91fc126..2bf8218 100644
--- a/src/librustc/hir/map/mod.rs
+++ b/src/librustc/hir/map/mod.rs
@@ -371,8 +371,12 @@
                 let def_id = self.local_def_id(variant.node.data.id());
                 Some(Def::Variant(def_id))
             }
-            Node::Field(_) |
+            Node::StructCtor(variant) => {
+                let def_id = self.local_def_id(variant.id());
+                Some(Def::StructCtor(def_id, def::CtorKind::from_hir(variant)))
+            }
             Node::AnonConst(_) |
+            Node::Field(_) |
             Node::Expr(_) |
             Node::Stmt(_) |
             Node::PathSegment(_) |
@@ -380,7 +384,6 @@
             Node::TraitRef(_) |
             Node::Pat(_) |
             Node::Binding(_) |
-            Node::StructCtor(_) |
             Node::Lifetime(_) |
             Node::Visibility(_) |
             Node::Block(_) |
@@ -931,7 +934,9 @@
         }
     }
 
-    pub fn expect_variant_data(&self, id: NodeId) -> &'hir VariantData {
+    pub fn expect_variant_data(&self, id: HirId) -> &'hir VariantData {
+        let id = self.hir_to_node_id(id); // FIXME(@ljedrz): remove when possible
+
         match self.find(id) {
             Some(Node::Item(i)) => {
                 match i.node {
@@ -946,7 +951,9 @@
         }
     }
 
-    pub fn expect_variant(&self, id: NodeId) -> &'hir Variant {
+    pub fn expect_variant(&self, id: HirId) -> &'hir Variant {
+        let id = self.hir_to_node_id(id); // FIXME(@ljedrz): remove when possible
+
         match self.find(id) {
             Some(Node::Variant(variant)) => variant,
             _ => bug!("expected variant, found {}", self.node_to_string(id)),
diff --git a/src/librustc/ich/impls_hir.rs b/src/librustc/ich/impls_hir.rs
index 2b35942..712fd36 100644
--- a/src/librustc/ich/impls_hir.rs
+++ b/src/librustc/ich/impls_hir.rs
@@ -1046,6 +1046,7 @@
     AssociatedExistential(def_id),
     PrimTy(prim_ty),
     TyParam(def_id),
+    ConstParam(def_id),
     SelfTy(trait_def_id, impl_def_id),
     ForeignTy(def_id),
     Fn(def_id),
diff --git a/src/librustc/infer/error_reporting/mod.rs b/src/librustc/infer/error_reporting/mod.rs
index 8510533..1c23438 100644
--- a/src/librustc/infer/error_reporting/mod.rs
+++ b/src/librustc/infer/error_reporting/mod.rs
@@ -56,7 +56,6 @@
 use crate::hir::Node;
 use crate::middle::region;
 use std::{cmp, fmt};
-use syntax::ast::DUMMY_NODE_ID;
 use syntax_pos::{Pos, Span};
 use crate::traits::{ObligationCause, ObligationCauseCode};
 use crate::ty::error::TypeError;
@@ -182,8 +181,8 @@
         let cm = self.sess.source_map();
 
         let scope = region.free_region_binding_scope(self);
-        let node = self.hir().as_local_node_id(scope).unwrap_or(DUMMY_NODE_ID);
-        let tag = match self.hir().find(node) {
+        let node = self.hir().as_local_hir_id(scope).unwrap_or(hir::DUMMY_HIR_ID);
+        let tag = match self.hir().find_by_hir_id(node) {
             Some(Node::Block(_)) | Some(Node::Expr(_)) => "body",
             Some(Node::Item(it)) => Self::item_scope_tag(&it),
             Some(Node::TraitItem(it)) => Self::trait_item_scope_tag(&it),
@@ -192,7 +191,7 @@
         };
         let (prefix, span) = match *region {
             ty::ReEarlyBound(ref br) => {
-                let mut sp = cm.def_span(self.hir().span(node));
+                let mut sp = cm.def_span(self.hir().span_by_hir_id(node));
                 if let Some(param) = self.hir()
                     .get_generics(scope)
                     .and_then(|generics| generics.get_named(&br.name))
@@ -205,7 +204,7 @@
                 bound_region: ty::BoundRegion::BrNamed(_, ref name),
                 ..
             }) => {
-                let mut sp = cm.def_span(self.hir().span(node));
+                let mut sp = cm.def_span(self.hir().span_by_hir_id(node));
                 if let Some(param) = self.hir()
                     .get_generics(scope)
                     .and_then(|generics| generics.get_named(&name))
@@ -217,15 +216,15 @@
             ty::ReFree(ref fr) => match fr.bound_region {
                 ty::BrAnon(idx) => (
                     format!("the anonymous lifetime #{} defined on", idx + 1),
-                    self.hir().span(node),
+                    self.hir().span_by_hir_id(node),
                 ),
                 ty::BrFresh(_) => (
                     "an anonymous lifetime defined on".to_owned(),
-                    self.hir().span(node),
+                    self.hir().span_by_hir_id(node),
                 ),
                 _ => (
                     format!("the lifetime {} as defined on", fr.bound_region),
-                    cm.def_span(self.hir().span(node)),
+                    cm.def_span(self.hir().span_by_hir_id(node)),
                 ),
             },
             _ => bug!(),
@@ -1451,8 +1450,7 @@
                 format!(" for lifetime parameter `{}` in coherence check", name)
             }
             infer::UpvarRegion(ref upvar_id, _) => {
-                let var_node_id = self.tcx.hir().hir_to_node_id(upvar_id.var_path.hir_id);
-                let var_name = self.tcx.hir().name(var_node_id);
+                let var_name = self.tcx.hir().name_by_hir_id(upvar_id.var_path.hir_id);
                 format!(" for capture of `{}` by closure", var_name)
             }
             infer::NLL(..) => bug!("NLL variable found in lexical phase"),
diff --git a/src/librustc/infer/error_reporting/note.rs b/src/librustc/infer/error_reporting/note.rs
index efd7f3c..6c481e8 100644
--- a/src/librustc/infer/error_reporting/note.rs
+++ b/src/librustc/infer/error_reporting/note.rs
@@ -31,8 +31,7 @@
                               "...so that reference does not outlive borrowed content");
             }
             infer::ReborrowUpvar(span, ref upvar_id) => {
-                let var_node_id = self.tcx.hir().hir_to_node_id(upvar_id.var_path.hir_id);
-                let var_name = self.tcx.hir().name(var_node_id);
+                let var_name = self.tcx.hir().name_by_hir_id(upvar_id.var_path.hir_id);
                 err.span_note(span,
                               &format!("...so that closure can access `{}`", var_name));
             }
@@ -164,8 +163,7 @@
                 err
             }
             infer::ReborrowUpvar(span, ref upvar_id) => {
-                let var_node_id = self.tcx.hir().hir_to_node_id(upvar_id.var_path.hir_id);
-                let var_name = self.tcx.hir().name(var_node_id);
+                let var_name = self.tcx.hir().name_by_hir_id(upvar_id.var_path.hir_id);
                 let mut err = struct_span_err!(self.tcx.sess,
                                                span,
                                                E0313,
diff --git a/src/librustc/lib.rs b/src/librustc/lib.rs
index d195135..be14755 100644
--- a/src/librustc/lib.rs
+++ b/src/librustc/lib.rs
@@ -26,9 +26,7 @@
 //!
 //! This API is completely unstable and subject to change.
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 
 #![deny(rust_2018_idioms)]
 #![allow(explicit_outlives_requirements)]
diff --git a/src/librustc/lint/builtin.rs b/src/librustc/lint/builtin.rs
index 6ae7448..cb31441 100644
--- a/src/librustc/lint/builtin.rs
+++ b/src/librustc/lint/builtin.rs
@@ -352,6 +352,12 @@
     "outlives requirements can be inferred"
 }
 
+declare_lint! {
+    pub DUPLICATE_MATCHER_BINDING_NAME,
+    Warn,
+    "duplicate macro matcher binding name"
+}
+
 /// Some lints that are buffered from `libsyntax`. See `syntax::early_buffered_lints`.
 pub mod parser {
     declare_lint! {
@@ -467,6 +473,7 @@
     MacroExpandedMacroExportsAccessedByAbsolutePaths(Span),
     ElidedLifetimesInPaths(usize, Span, bool, Span, String),
     UnknownCrateTypes(Span, String, String),
+    UnusedImports(String, Vec<(Span, String)>),
 }
 
 impl BuiltinLintDiagnostics {
@@ -548,6 +555,15 @@
             BuiltinLintDiagnostics::UnknownCrateTypes(span, note, sugg) => {
                 db.span_suggestion(span, &note, sugg, Applicability::MaybeIncorrect);
             }
+            BuiltinLintDiagnostics::UnusedImports(message, replaces) => {
+                if !replaces.is_empty() {
+                    db.multipart_suggestion(
+                        &message,
+                        replaces,
+                        Applicability::MachineApplicable,
+                    );
+                }
+            }
         }
     }
 }
diff --git a/src/librustc/lint/mod.rs b/src/librustc/lint/mod.rs
index 4e6bf75..8952ae9 100644
--- a/src/librustc/lint/mod.rs
+++ b/src/librustc/lint/mod.rs
@@ -27,7 +27,7 @@
 use crate::hir::def_id::{CrateNum, LOCAL_CRATE};
 use crate::hir::intravisit;
 use crate::hir;
-use crate::lint::builtin::BuiltinLintDiagnostics;
+use crate::lint::builtin::{BuiltinLintDiagnostics, DUPLICATE_MATCHER_BINDING_NAME};
 use crate::lint::builtin::parser::{QUESTION_MARK_MACRO_SEP, ILL_FORMED_ATTRIBUTE_INPUT};
 use crate::session::{Session, DiagnosticMessageId};
 use std::{hash, ptr};
@@ -82,6 +82,7 @@
         match lint_id {
             BufferedEarlyLintId::QuestionMarkMacroSep => QUESTION_MARK_MACRO_SEP,
             BufferedEarlyLintId::IllFormedAttributeInput => ILL_FORMED_ATTRIBUTE_INPUT,
+            BufferedEarlyLintId::DuplicateMacroMatcherBindingName => DUPLICATE_MATCHER_BINDING_NAME,
         }
     }
 
diff --git a/src/librustc/middle/reachable.rs b/src/librustc/middle/reachable.rs
index 73ba47d..99d0c5e 100644
--- a/src/librustc/middle/reachable.rs
+++ b/src/librustc/middle/reachable.rs
@@ -177,8 +177,8 @@
                             // Check the impl. If the generics on the self
                             // type of the impl require inlining, this method
                             // does too.
-                            let impl_node_id = self.tcx.hir().as_local_node_id(impl_did).unwrap();
-                            match self.tcx.hir().expect_item(impl_node_id).node {
+                            let impl_hir_id = self.tcx.hir().as_local_hir_id(impl_did).unwrap();
+                            match self.tcx.hir().expect_item_by_hir_id(impl_hir_id).node {
                                 hir::ItemKind::Impl(..) => {
                                     let generics = self.tcx.generics_of(impl_did);
                                     generics.requires_monomorphization(self.tcx)
diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs
index f7cd241..f187928 100644
--- a/src/librustc/middle/resolve_lifetime.rs
+++ b/src/librustc/middle/resolve_lifetime.rs
@@ -1248,12 +1248,12 @@
                 } => {
                     // FIXME (#24278): non-hygienic comparison
                     if let Some(def) = lifetimes.get(&hir::ParamName::Plain(label.modern())) {
-                        let node_id = tcx.hir().as_local_node_id(def.id().unwrap()).unwrap();
+                        let hir_id = tcx.hir().as_local_hir_id(def.id().unwrap()).unwrap();
 
                         signal_shadowing_problem(
                             tcx,
                             label.name,
-                            original_lifetime(tcx.hir().span(node_id)),
+                            original_lifetime(tcx.hir().span_by_hir_id(hir_id)),
                             shadower_label(label.span),
                         );
                         return;
@@ -2593,12 +2593,12 @@
                     ref lifetimes, s, ..
                 } => {
                     if let Some(&def) = lifetimes.get(&param.name.modern()) {
-                        let node_id = self.tcx.hir().as_local_node_id(def.id().unwrap()).unwrap();
+                        let hir_id = self.tcx.hir().as_local_hir_id(def.id().unwrap()).unwrap();
 
                         signal_shadowing_problem(
                             self.tcx,
                             param.name.ident().name,
-                            original_lifetime(self.tcx.hir().span(node_id)),
+                            original_lifetime(self.tcx.hir().span_by_hir_id(hir_id)),
                             shadower_lifetime(&param),
                         );
                         return;
diff --git a/src/librustc/mir/interpret/mod.rs b/src/librustc/mir/interpret/mod.rs
index efd233f..bb25d1b 100644
--- a/src/librustc/mir/interpret/mod.rs
+++ b/src/librustc/mir/interpret/mod.rs
@@ -27,7 +27,7 @@
 use std::fmt;
 use crate::mir;
 use crate::hir::def_id::DefId;
-use crate::ty::{self, TyCtxt, Instance};
+use crate::ty::{self, TyCtxt, Instance, subst::UnpackedKind};
 use crate::ty::layout::{self, Size};
 use std::io;
 use crate::rustc_serialize::{Encoder, Decodable, Encodable};
@@ -318,14 +318,29 @@
         id
     }
 
-    /// Functions cannot be identified by pointers, as asm-equal functions can get deduplicated
-    /// by the linker and functions can be duplicated across crates.
-    /// We thus generate a new `AllocId` for every mention of a function. This means that
-    /// `main as fn() == main as fn()` is false, while `let x = main as fn(); x == x` is true.
     pub fn create_fn_alloc(&mut self, instance: Instance<'tcx>) -> AllocId {
-        let id = self.reserve();
-        self.id_to_kind.insert(id, AllocKind::Function(instance));
-        id
+        // Functions cannot be identified by pointers, as asm-equal functions can get deduplicated
+        // by the linker (we set the "unnamed_addr" attribute for LLVM) and functions can be
+        // duplicated across crates.
+        // We thus generate a new `AllocId` for every mention of a function. This means that
+        // `main as fn() == main as fn()` is false, while `let x = main as fn(); x == x` is true.
+        // However, formatting code relies on function identity (see #58320), so we only do
+        // this for generic functions.  Lifetime parameters are ignored.
+        let is_generic = instance.substs.into_iter().any(|kind| {
+            match kind.unpack() {
+                UnpackedKind::Lifetime(_) => false,
+                _ => true,
+            }
+        });
+        if is_generic {
+            // Get a fresh ID
+            let id = self.reserve();
+            self.id_to_kind.insert(id, AllocKind::Function(instance));
+            id
+        } else {
+            // Deduplicate
+            self.intern(AllocKind::Function(instance))
+        }
     }
 
     /// Returns `None` in case the `AllocId` is dangling. An `EvalContext` can still have a
diff --git a/src/librustc/mir/mod.rs b/src/librustc/mir/mod.rs
index 009997b..a0f16ae 100644
--- a/src/librustc/mir/mod.rs
+++ b/src/librustc/mir/mod.rs
@@ -2154,7 +2154,7 @@
             span,
             ty,
             user_ty: None,
-            literal: tcx.intern_lazy_const(
+            literal: tcx.mk_lazy_const(
                 ty::LazyConst::Evaluated(ty::Const::zero_sized(ty)),
             ),
         })
diff --git a/src/librustc/traits/error_reporting.rs b/src/librustc/traits/error_reporting.rs
index 79afc59..c17adaf 100644
--- a/src/librustc/traits/error_reporting.rs
+++ b/src/librustc/traits/error_reporting.rs
@@ -1035,7 +1035,8 @@
                  ).collect::<Vec<_>>())
             }
             Node::StructCtor(ref variant_data) => {
-                (self.tcx.sess.source_map().def_span(self.tcx.hir().span(variant_data.id())),
+                (self.tcx.sess.source_map().def_span(
+                    self.tcx.hir().span_by_hir_id(variant_data.hir_id())),
                  vec![ArgKind::empty(); variant_data.fields().len()])
             }
             _ => panic!("non-FnLike node found: {:?}", node),
diff --git a/src/librustc/traits/project.rs b/src/librustc/traits/project.rs
index 99107a1..562a29f 100644
--- a/src/librustc/traits/project.rs
+++ b/src/librustc/traits/project.rs
@@ -408,7 +408,7 @@
                         if let Ok(evaluated) = tcx.const_eval(param_env.and(cid)) {
                             let substs = tcx.lift_to_global(&substs).unwrap();
                             let evaluated = evaluated.subst(tcx, substs);
-                            return tcx.intern_lazy_const(ty::LazyConst::Evaluated(evaluated));
+                            return tcx.mk_lazy_const(ty::LazyConst::Evaluated(evaluated));
                         }
                     }
                 } else {
@@ -420,7 +420,7 @@
                                 promoted: None
                             };
                             if let Ok(evaluated) = tcx.const_eval(param_env.and(cid)) {
-                                return tcx.intern_lazy_const(ty::LazyConst::Evaluated(evaluated));
+                                return tcx.mk_lazy_const(ty::LazyConst::Evaluated(evaluated));
                             }
                         }
                     }
diff --git a/src/librustc/traits/query/normalize.rs b/src/librustc/traits/query/normalize.rs
index f477f16..bcd1119 100644
--- a/src/librustc/traits/query/normalize.rs
+++ b/src/librustc/traits/query/normalize.rs
@@ -203,7 +203,7 @@
                         if let Ok(evaluated) = tcx.const_eval(param_env.and(cid)) {
                             let substs = tcx.lift_to_global(&substs).unwrap();
                             let evaluated = evaluated.subst(tcx, substs);
-                            return tcx.intern_lazy_const(ty::LazyConst::Evaluated(evaluated));
+                            return tcx.mk_lazy_const(ty::LazyConst::Evaluated(evaluated));
                         }
                     }
                 } else {
@@ -215,7 +215,7 @@
                                 promoted: None,
                             };
                             if let Ok(evaluated) = tcx.const_eval(param_env.and(cid)) {
-                                return tcx.intern_lazy_const(ty::LazyConst::Evaluated(evaluated));
+                                return tcx.mk_lazy_const(ty::LazyConst::Evaluated(evaluated));
                             }
                         }
                     }
diff --git a/src/librustc/traits/util.rs b/src/librustc/traits/util.rs
index 67c919a..754cc94 100644
--- a/src/librustc/traits/util.rs
+++ b/src/librustc/traits/util.rs
@@ -525,9 +525,9 @@
     }
 
     pub fn impl_is_default(self, node_item_def_id: DefId) -> bool {
-        match self.hir().as_local_node_id(node_item_def_id) {
-            Some(node_id) => {
-                let item = self.hir().expect_item(node_id);
+        match self.hir().as_local_hir_id(node_item_def_id) {
+            Some(hir_id) => {
+                let item = self.hir().expect_item_by_hir_id(hir_id);
                 if let hir::ItemKind::Impl(_, _, defaultness, ..) = item.node {
                     defaultness.is_default()
                 } else {
diff --git a/src/librustc/ty/codec.rs b/src/librustc/ty/codec.rs
index c9775b10..e93de32 100644
--- a/src/librustc/ty/codec.rs
+++ b/src/librustc/ty/codec.rs
@@ -252,7 +252,7 @@
     where D: TyDecoder<'a, 'tcx>,
           'tcx: 'a,
 {
-    Ok(decoder.tcx().intern_lazy_const(Decodable::decode(decoder)?))
+    Ok(decoder.tcx().mk_lazy_const(Decodable::decode(decoder)?))
 }
 
 #[inline]
diff --git a/src/librustc/ty/context.rs b/src/librustc/ty/context.rs
index 140c772..11211c9 100644
--- a/src/librustc/ty/context.rs
+++ b/src/librustc/ty/context.rs
@@ -1,7 +1,7 @@
 //! type context book-keeping
 
 use crate::dep_graph::DepGraph;
-use crate::dep_graph::{DepNode, DepConstructor};
+use crate::dep_graph::{self, DepNode, DepConstructor};
 use crate::errors::DiagnosticBuilder;
 use crate::session::Session;
 use crate::session::config::{BorrowckMode, OutputFilenames};
@@ -127,6 +127,7 @@
     goal: InternedSet<'tcx, GoalKind<'tcx>>,
     goal_list: InternedSet<'tcx, List<Goal<'tcx>>>,
     projs: InternedSet<'tcx, List<ProjectionKind<'tcx>>>,
+    lazy_const: InternedSet<'tcx, LazyConst<'tcx>>,
 }
 
 impl<'gcx: 'tcx, 'tcx> CtxtInterners<'tcx> {
@@ -144,6 +145,7 @@
             goal: Default::default(),
             goal_list: Default::default(),
             projs: Default::default(),
+            lazy_const: Default::default(),
         }
     }
 
@@ -1096,10 +1098,7 @@
         self.global_arenas.adt_def.alloc(def)
     }
 
-    pub fn intern_const_alloc(
-        self,
-        alloc: Allocation,
-    ) -> &'gcx Allocation {
+    pub fn intern_const_alloc(self, alloc: Allocation) -> &'gcx Allocation {
         self.allocation_interner.borrow_mut().intern(alloc, |alloc| {
             self.global_arenas.const_allocs.alloc(alloc)
         })
@@ -1119,10 +1118,6 @@
         })
     }
 
-    pub fn intern_lazy_const(self, c: ty::LazyConst<'tcx>) -> &'tcx ty::LazyConst<'tcx> {
-        self.global_interners.arena.alloc(c)
-    }
-
     pub fn intern_layout(self, layout: LayoutDetails) -> &'gcx LayoutDetails {
         self.layout_interner.borrow_mut().intern(layout, |layout| {
             self.global_arenas.layout.alloc(layout)
@@ -1435,7 +1430,8 @@
             self.dep_graph.with_task(dep_node,
                                      self,
                                      crate_hash,
-                                     |_, x| x // No transformation needed
+                                     |_, x| x, // No transformation needed
+                                     dep_graph::hash_result,
             );
         }
     }
@@ -2271,6 +2267,12 @@
     }
 }
 
+impl<'tcx: 'lcx, 'lcx> Borrow<LazyConst<'lcx>> for Interned<'tcx, LazyConst<'tcx>> {
+    fn borrow<'a>(&'a self) -> &'a LazyConst<'lcx> {
+        &self.0
+    }
+}
+
 impl<'tcx: 'lcx, 'lcx> Borrow<[ExistentialPredicate<'lcx>]>
     for Interned<'tcx, List<ExistentialPredicate<'tcx>>> {
     fn borrow<'a>(&'a self) -> &'a [ExistentialPredicate<'lcx>] {
@@ -2377,7 +2379,8 @@
 
 direct_interners!('tcx,
     region: mk_region(|r: &RegionKind| r.keep_in_local_tcx()) -> RegionKind,
-    goal: mk_goal(|c: &GoalKind<'_>| keep_local(c)) -> GoalKind<'tcx>
+    goal: mk_goal(|c: &GoalKind<'_>| keep_local(c)) -> GoalKind<'tcx>,
+    lazy_const: mk_lazy_const(|c: &LazyConst<'_>| keep_local(&c)) -> LazyConst<'tcx>
 );
 
 macro_rules! slice_interners {
@@ -2562,7 +2565,7 @@
 
     #[inline]
     pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> {
-        self.mk_ty(Array(ty, self.intern_lazy_const(
+        self.mk_ty(Array(ty, self.mk_lazy_const(
             ty::LazyConst::Evaluated(ty::Const::from_usize(self.global_tcx(), n))
         )))
     }
diff --git a/src/librustc/ty/item_path.rs b/src/librustc/ty/item_path.rs
index f89e50d..3f49c1b 100644
--- a/src/librustc/ty/item_path.rs
+++ b/src/librustc/ty/item_path.rs
@@ -325,6 +325,7 @@
             data @ DefPathData::Module(..) |
             data @ DefPathData::TypeParam(..) |
             data @ DefPathData::LifetimeParam(..) |
+            data @ DefPathData::ConstParam(..) |
             data @ DefPathData::EnumVariant(..) |
             data @ DefPathData::Field(..) |
             data @ DefPathData::AnonConst |
@@ -461,8 +462,8 @@
         // only occur very early in the compiler pipeline.
         let parent_def_id = self.parent_def_id(impl_def_id).unwrap();
         self.push_item_path(buffer, parent_def_id, pushed_prelude_crate);
-        let node_id = self.hir().as_local_node_id(impl_def_id).unwrap();
-        let item = self.hir().expect_item(node_id);
+        let hir_id = self.hir().as_local_hir_id(impl_def_id).unwrap();
+        let item = self.hir().expect_item_by_hir_id(hir_id);
         let span_str = self.sess.source_map().span_to_string(item.span);
         buffer.push(&format!("<impl at {}>", span_str));
     }
diff --git a/src/librustc/ty/mod.rs b/src/librustc/ty/mod.rs
index 60e3ac6..1f08d93 100644
--- a/src/librustc/ty/mod.rs
+++ b/src/librustc/ty/mod.rs
@@ -2939,8 +2939,8 @@
 
     /// Get the attributes of a definition.
     pub fn get_attrs(self, did: DefId) -> Attributes<'gcx> {
-        if let Some(id) = self.hir().as_local_node_id(did) {
-            Attributes::Borrowed(self.hir().attrs(id))
+        if let Some(id) = self.hir().as_local_hir_id(did) {
+            Attributes::Borrowed(self.hir().attrs_by_hir_id(id))
         } else {
             Attributes::Owned(self.item_attrs(did))
         }
@@ -2991,8 +2991,8 @@
     /// 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() {
-            let node_id = self.hir().as_local_node_id(impl_did).unwrap();
-            Ok(self.hir().span(node_id))
+            let hir_id = self.hir().as_local_hir_id(impl_did).unwrap();
+            Ok(self.hir().span_by_hir_id(hir_id))
         } else {
             Err(self.crate_name(impl_did.krate))
         }
@@ -3110,8 +3110,8 @@
 fn associated_item_def_ids<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                      def_id: DefId)
                                      -> Lrc<Vec<DefId>> {
-    let id = tcx.hir().as_local_node_id(def_id).unwrap();
-    let item = tcx.hir().expect_item(id);
+    let id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    let item = tcx.hir().expect_item_by_hir_id(id);
     let vec: Vec<_> = match item.node {
         hir::ItemKind::Trait(.., ref trait_item_refs) => {
             trait_item_refs.iter()
diff --git a/src/librustc/ty/query/config.rs b/src/librustc/ty/query/config.rs
index 255e39e..a3ee92f 100644
--- a/src/librustc/ty/query/config.rs
+++ b/src/librustc/ty/query/config.rs
@@ -20,7 +20,7 @@
 use std::fmt::Debug;
 use syntax_pos::symbol::InternedString;
 use rustc_data_structures::sync::Lock;
-use rustc_data_structures::stable_hasher::HashStable;
+use rustc_data_structures::fingerprint::Fingerprint;
 use crate::ich::StableHashingContext;
 
 // Query configuration and description traits.
@@ -30,7 +30,7 @@
     const CATEGORY: ProfileCategory;
 
     type Key: Eq + Hash + Clone + Debug;
-    type Value: Clone + for<'a> HashStable<StableHashingContext<'a>>;
+    type Value: Clone;
 }
 
 pub(super) trait QueryAccessors<'tcx>: QueryConfig<'tcx> {
@@ -44,6 +44,11 @@
     // Don't use this method to compute query results, instead use the methods on TyCtxt
     fn compute(tcx: TyCtxt<'_, 'tcx, '_>, key: Self::Key) -> Self::Value;
 
+    fn hash_result(
+        hcx: &mut StableHashingContext<'_>,
+        result: &Self::Value
+    ) -> Option<Fingerprint>;
+
     fn handle_cycle_error(tcx: TyCtxt<'_, 'tcx, '_>) -> Self::Value;
 }
 
diff --git a/src/librustc/ty/query/mod.rs b/src/librustc/ty/query/mod.rs
index 20a700b..d002b99 100644
--- a/src/librustc/ty/query/mod.rs
+++ b/src/librustc/ty/query/mod.rs
@@ -1,4 +1,4 @@
-use crate::dep_graph::{DepConstructor, DepNode};
+use crate::dep_graph::{self, DepConstructor, DepNode};
 use crate::errors::DiagnosticBuilder;
 use crate::hir::def_id::{CrateNum, DefId, DefIndex};
 use crate::hir::def::{Def, Export};
@@ -49,6 +49,7 @@
 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
 use rustc_data_structures::stable_hasher::StableVec;
 use rustc_data_structures::sync::Lrc;
+use rustc_data_structures::fingerprint::Fingerprint;
 use rustc_target::spec::PanicStrategy;
 
 use std::borrow::Cow;
@@ -233,9 +234,9 @@
         /// ready for const evaluation.
         ///
         /// See the README for the `mir` module for details.
-        [] fn mir_const: MirConst(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
+        [no_hash] fn mir_const: MirConst(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
 
-        [] fn mir_validated: MirValidated(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
+        [no_hash] fn mir_validated: MirValidated(DefId) -> &'tcx Steal<mir::Mir<'tcx>>,
 
         /// MIR after our optimization passes have run. This is MIR that is ready
         /// for codegen. This is also the only query that can fetch non-local MIR, at present.
diff --git a/src/librustc/ty/query/plumbing.rs b/src/librustc/ty/query/plumbing.rs
index a26b21a..f63fbd7 100644
--- a/src/librustc/ty/query/plumbing.rs
+++ b/src/librustc/ty/query/plumbing.rs
@@ -113,7 +113,7 @@
             let mut lock = cache.borrow_mut();
             if let Some(value) = lock.results.get(key) {
                 profq_msg!(tcx, ProfileQueriesMsg::CacheHit);
-                tcx.sess.profiler(|p| p.record_query_hit(Q::CATEGORY));
+                tcx.sess.profiler(|p| p.record_query_hit(Q::NAME, Q::CATEGORY));
                 let result = Ok((value.value.clone(), value.index));
                 #[cfg(debug_assertions)]
                 {
@@ -375,7 +375,7 @@
 
         if dep_node.kind.is_anon() {
             profq_msg!(self, ProfileQueriesMsg::ProviderBegin);
-            self.sess.profiler(|p| p.start_activity(Q::CATEGORY));
+            self.sess.profiler(|p| p.start_query(Q::NAME, Q::CATEGORY));
 
             let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
                 job.start(self, diagnostics, |tcx| {
@@ -385,7 +385,7 @@
                 })
             });
 
-            self.sess.profiler(|p| p.end_activity(Q::CATEGORY));
+            self.sess.profiler(|p| p.end_query(Q::NAME, Q::CATEGORY));
             profq_msg!(self, ProfileQueriesMsg::ProviderEnd);
 
             self.dep_graph.read_index(dep_node_index);
@@ -452,14 +452,14 @@
 
         let result = if let Some(result) = result {
             profq_msg!(self, ProfileQueriesMsg::CacheHit);
-            self.sess.profiler(|p| p.record_query_hit(Q::CATEGORY));
+            self.sess.profiler(|p| p.record_query_hit(Q::NAME, Q::CATEGORY));
 
             result
         } else {
             // We could not load a result from the on-disk cache, so
             // recompute.
 
-            self.sess.profiler(|p| p.start_activity(Q::CATEGORY));
+            self.sess.profiler(|p| p.start_query(Q::NAME, Q::CATEGORY));
 
             // The diagnostics for this query have already been
             // promoted to the current session during
@@ -472,7 +472,7 @@
                 })
             });
 
-            self.sess.profiler(|p| p.end_activity(Q::CATEGORY));
+            self.sess.profiler(|p| p.end_query(Q::NAME, Q::CATEGORY));
             result
         };
 
@@ -499,7 +499,6 @@
         dep_node: &DepNode,
         dep_node_index: DepNodeIndex,
     ) {
-        use rustc_data_structures::stable_hasher::{StableHasher, HashStable};
         use crate::ich::Fingerprint;
 
         assert!(Some(self.dep_graph.fingerprint_of(dep_node_index)) ==
@@ -509,11 +508,8 @@
 
         debug!("BEGIN verify_ich({:?})", dep_node);
         let mut hcx = self.create_stable_hashing_context();
-        let mut hasher = StableHasher::new();
 
-        result.hash_stable(&mut hcx, &mut hasher);
-
-        let new_hash: Fingerprint = hasher.finish();
+        let new_hash = Q::hash_result(&mut hcx, result).unwrap_or(Fingerprint::ZERO);
         debug!("END verify_ich({:?})", dep_node);
 
         let old_hash = self.dep_graph.fingerprint_of(dep_node_index);
@@ -541,7 +537,7 @@
                 key, dep_node);
 
         profq_msg!(self, ProfileQueriesMsg::ProviderBegin);
-        self.sess.profiler(|p| p.start_activity(Q::CATEGORY));
+        self.sess.profiler(|p| p.start_query(Q::NAME, Q::CATEGORY));
 
         let ((result, dep_node_index), diagnostics) = with_diagnostics(|diagnostics| {
             job.start(self, diagnostics, |tcx| {
@@ -549,17 +545,19 @@
                     tcx.dep_graph.with_eval_always_task(dep_node,
                                                         tcx,
                                                         key,
-                                                        Q::compute)
+                                                        Q::compute,
+                                                        Q::hash_result)
                 } else {
                     tcx.dep_graph.with_task(dep_node,
                                             tcx,
                                             key,
-                                            Q::compute)
+                                            Q::compute,
+                                            Q::hash_result)
                 }
             })
         });
 
-        self.sess.profiler(|p| p.end_activity(Q::CATEGORY));
+        self.sess.profiler(|p| p.end_query(Q::NAME, Q::CATEGORY));
         profq_msg!(self, ProfileQueriesMsg::ProviderEnd);
 
         if unlikely!(self.sess.opts.debugging_opts.query_dep_graph) {
@@ -602,7 +600,7 @@
             let _ = self.get_query::<Q>(DUMMY_SP, key);
         } else {
             profq_msg!(self, ProfileQueriesMsg::CacheHit);
-            self.sess.profiler(|p| p.record_query_hit(Q::CATEGORY));
+            self.sess.profiler(|p| p.record_query_hit(Q::NAME, Q::CATEGORY));
         }
     }
 
@@ -679,6 +677,18 @@
     };
 }
 
+macro_rules! hash_result {
+    ([][$hcx:expr, $result:expr]) => {{
+        dep_graph::hash_result($hcx, &$result)
+    }};
+    ([no_hash$(, $modifiers:ident)*][$hcx:expr, $result:expr]) => {{
+        None
+    }};
+    ([$other:ident$(, $modifiers:ident)*][$($args:tt)*]) => {
+        hash_result!([$($modifiers),*][$($args)*])
+    };
+}
+
 macro_rules! define_queries {
     (<$tcx:tt> $($category:tt {
         $($(#[$attr:meta])* [$($modifiers:tt)*] fn $name:ident: $node:ident($K:ty) -> $V:ty,)*
@@ -729,6 +739,7 @@
                 sess.profiler(|p| {
                     $(
                         p.record_computed_queries(
+                            <queries::$name<'_> as QueryConfig<'_>>::NAME,
                             <queries::$name<'_> as QueryConfig<'_>>::CATEGORY,
                             self.$name.lock().results.len()
                         );
@@ -966,6 +977,13 @@
                 })
             }
 
+            fn hash_result(
+                _hcx: &mut StableHashingContext<'_>,
+                _result: &Self::Value
+            ) -> Option<Fingerprint> {
+                hash_result!([$($modifiers)*][_hcx, _result])
+            }
+
             fn handle_cycle_error(tcx: TyCtxt<'_, 'tcx, '_>) -> Self::Value {
                 handle_cycle_error!([$($modifiers)*][tcx])
             }
diff --git a/src/librustc/ty/structural_impls.rs b/src/librustc/ty/structural_impls.rs
index 62a4923..d09cfa8 100644
--- a/src/librustc/ty/structural_impls.rs
+++ b/src/librustc/ty/structural_impls.rs
@@ -1042,7 +1042,7 @@
                 ty::LazyConst::Unevaluated(*def_id, substs.fold_with(folder))
             }
         };
-        folder.tcx().intern_lazy_const(new)
+        folder.tcx().mk_lazy_const(new)
     }
 
     fn fold_with<'gcx: 'tcx, F: TypeFolder<'gcx, 'tcx>>(&self, folder: &mut F) -> Self {
diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs
index 2cd82d4..4945bf8 100644
--- a/src/librustc/util/ppaux.rs
+++ b/src/librustc/util/ppaux.rs
@@ -426,6 +426,7 @@
                     DefPathData::ClosureExpr |
                     DefPathData::TypeParam(_) |
                     DefPathData::LifetimeParam(_) |
+                    DefPathData::ConstParam(_) |
                     DefPathData::Field(_) |
                     DefPathData::StructCtor |
                     DefPathData::AnonConst |
@@ -801,7 +802,7 @@
     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(f, "UpvarId({:?};`{}`;{:?})",
                self.var_path.hir_id,
-               ty::tls::with(|tcx| tcx.hir().name(tcx.hir().hir_to_node_id(self.var_path.hir_id))),
+               ty::tls::with(|tcx| tcx.hir().name_by_hir_id(self.var_path.hir_id)),
                self.closure_expr_id)
     }
 }
diff --git a/src/librustc/util/profiling.rs b/src/librustc/util/profiling.rs
index 0e03946..f8fa01b 100644
--- a/src/librustc/util/profiling.rs
+++ b/src/librustc/util/profiling.rs
@@ -1,125 +1,13 @@
-use crate::session::config::Options;
-
+use std::collections::{BTreeMap, HashMap};
 use std::fs;
-use std::io::{self, StderrLock, Write};
+use std::io::{self, Write};
+use std::thread::ThreadId;
 use std::time::Instant;
 
-macro_rules! define_categories {
-    ($($name:ident,)*) => {
-        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
-        pub enum ProfileCategory {
-            $($name),*
-        }
+use crate::session::config::{Options, OptLevel};
 
-        #[allow(nonstandard_style)]
-        struct Categories<T> {
-            $($name: T),*
-        }
-
-        impl<T: Default> Categories<T> {
-            fn new() -> Categories<T> {
-                Categories {
-                    $($name: T::default()),*
-                }
-            }
-        }
-
-        impl<T> Categories<T> {
-            fn get(&self, category: ProfileCategory) -> &T {
-                match category {
-                    $(ProfileCategory::$name => &self.$name),*
-                }
-            }
-
-            fn set(&mut self, category: ProfileCategory, value: T) {
-                match category {
-                    $(ProfileCategory::$name => self.$name = value),*
-                }
-            }
-        }
-
-        struct CategoryData {
-            times: Categories<u64>,
-            query_counts: Categories<(u64, u64)>,
-        }
-
-        impl CategoryData {
-            fn new() -> CategoryData {
-                CategoryData {
-                    times: Categories::new(),
-                    query_counts: Categories::new(),
-                }
-            }
-
-            fn print(&self, lock: &mut StderrLock<'_>) {
-                writeln!(lock, "| Phase            | Time (ms)      \
-                                | Time (%) | Queries        | Hits (%)")
-                    .unwrap();
-                writeln!(lock, "| ---------------- | -------------- \
-                                | -------- | -------------- | --------")
-                    .unwrap();
-
-                let total_time = ($(self.times.$name + )* 0) as f32;
-
-                $(
-                    let (hits, computed) = self.query_counts.$name;
-                    let total = hits + computed;
-                    let (hits, total) = if total > 0 {
-                        (format!("{:.2}",
-                        (((hits as f32) / (total as f32)) * 100.0)), total.to_string())
-                    } else {
-                        (String::new(), String::new())
-                    };
-
-                    writeln!(
-                        lock,
-                        "| {0: <16} | {1: <14} | {2: <8.2} | {3: <14} | {4: <8}",
-                        stringify!($name),
-                        self.times.$name / 1_000_000,
-                        ((self.times.$name as f32) / total_time) * 100.0,
-                        total,
-                        hits,
-                    ).unwrap();
-                )*
-            }
-
-            fn json(&self) -> String {
-                let mut json = String::from("[");
-
-                $(
-                    let (hits, computed) = self.query_counts.$name;
-                    let total = hits + computed;
-
-                    //normalize hits to 0%
-                    let hit_percent =
-                        if total > 0 {
-                            ((hits as f32) / (total as f32)) * 100.0
-                        } else {
-                            0.0
-                        };
-
-                    json.push_str(&format!(
-                        "{{ \"category\": \"{}\", \"time_ms\": {},\
-                            \"query_count\": {}, \"query_hits\": {} }},",
-                        stringify!($name),
-                        self.times.$name / 1_000_000,
-                        total,
-                        format!("{:.2}", hit_percent)
-                    ));
-                )*
-
-                //remove the trailing ',' character
-                json.pop();
-
-                json.push(']');
-
-                json
-            }
-        }
-    }
-}
-
-define_categories! {
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd)]
+pub enum ProfileCategory {
     Parsing,
     Expansion,
     TypeChecking,
@@ -129,18 +17,151 @@
     Other,
 }
 
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum ProfilerEvent {
+    QueryStart { query_name: &'static str, category: ProfileCategory, time: Instant },
+    QueryEnd { query_name: &'static str, category: ProfileCategory, time: Instant },
+    GenericActivityStart { category: ProfileCategory, time: Instant },
+    GenericActivityEnd { category: ProfileCategory, time: Instant },
+    QueryCacheHit { query_name: &'static str, category: ProfileCategory },
+    QueryCount { query_name: &'static str, category: ProfileCategory, count: usize },
+}
+
+impl ProfilerEvent {
+    fn is_start_event(&self) -> bool {
+        use self::ProfilerEvent::*;
+
+        match self {
+            QueryStart { .. } | GenericActivityStart { .. } => true,
+            QueryEnd { .. } | GenericActivityEnd { .. } |
+            QueryCacheHit { .. } | QueryCount { .. } => false,
+        }
+    }
+}
+
 pub struct SelfProfiler {
-    timer_stack: Vec<ProfileCategory>,
-    data: CategoryData,
-    current_timer: Instant,
+    events: HashMap<ThreadId, Vec<ProfilerEvent>>,
+}
+
+struct CategoryResultData {
+    query_times: BTreeMap<&'static str, u64>,
+    query_cache_stats: BTreeMap<&'static str, (u64, u64)>, //(hits, total)
+}
+
+impl CategoryResultData {
+    fn new() -> CategoryResultData {
+        CategoryResultData {
+            query_times: BTreeMap::new(),
+            query_cache_stats: BTreeMap::new(),
+        }
+    }
+
+    fn total_time(&self) -> u64 {
+        let mut total = 0;
+        for (_, time) in &self.query_times {
+            total += time;
+        }
+
+        total
+    }
+
+    fn total_cache_data(&self) -> (u64, u64) {
+        let (mut hits, mut total) = (0, 0);
+
+        for (_, (h, t)) in &self.query_cache_stats {
+            hits += h;
+            total += t;
+        }
+
+        (hits, total)
+    }
+}
+
+impl Default for CategoryResultData {
+    fn default() -> CategoryResultData {
+        CategoryResultData::new()
+    }
+}
+
+struct CalculatedResults {
+    categories: BTreeMap<ProfileCategory, CategoryResultData>,
+    crate_name: Option<String>,
+    optimization_level: OptLevel,
+    incremental: bool,
+    verbose: bool,
+}
+
+impl CalculatedResults {
+    fn new() -> CalculatedResults {
+        CalculatedResults {
+            categories: BTreeMap::new(),
+            crate_name: None,
+            optimization_level: OptLevel::No,
+            incremental: false,
+            verbose: false,
+        }
+    }
+
+    fn consolidate(mut cr1: CalculatedResults, cr2: CalculatedResults) -> CalculatedResults {
+        for (category, data) in cr2.categories {
+            let cr1_data = cr1.categories.entry(category).or_default();
+
+            for (query, time) in data.query_times {
+                *cr1_data.query_times.entry(query).or_default() += time;
+            }
+
+            for (query, (hits, total)) in data.query_cache_stats {
+                let (h, t) = cr1_data.query_cache_stats.entry(query).or_insert((0, 0));
+                *h += hits;
+                *t += total;
+            }
+        }
+
+        cr1
+    }
+
+    fn total_time(&self) -> u64 {
+        let mut total = 0;
+
+        for (_, data) in &self.categories {
+            total += data.total_time();
+        }
+
+        total
+    }
+
+    fn with_options(mut self, opts: &Options) -> CalculatedResults {
+        self.crate_name = opts.crate_name.clone();
+        self.optimization_level = opts.optimize;
+        self.incremental = opts.incremental.is_some();
+        self.verbose = opts.debugging_opts.verbose;
+
+        self
+    }
+}
+
+fn time_between_ns(start: Instant, end: Instant) -> u64 {
+    if start < end {
+        let time = end - start;
+        (time.as_secs() * 1_000_000_000) + (time.subsec_nanos() as u64)
+    } else {
+        debug!("time_between_ns: ignorning instance of end < start");
+        0
+    }
+}
+
+fn calculate_percent(numerator: u64, denominator: u64) -> f32 {
+    if denominator > 0 {
+        ((numerator as f32) / (denominator as f32)) * 100.0
+    } else {
+        0.0
+    }
 }
 
 impl SelfProfiler {
     pub fn new() -> SelfProfiler {
         let mut profiler = SelfProfiler {
-            timer_stack: Vec::new(),
-            data: CategoryData::new(),
-            current_timer: Instant::now(),
+            events: HashMap::new(),
         };
 
         profiler.start_activity(ProfileCategory::Other);
@@ -148,104 +169,263 @@
         profiler
     }
 
+    #[inline]
     pub fn start_activity(&mut self, category: ProfileCategory) {
-        match self.timer_stack.last().cloned() {
-            None => {
-                self.current_timer = Instant::now();
-            },
-            Some(current_category) if current_category == category => {
-                //since the current category is the same as the new activity's category,
-                //we don't need to do anything with the timer, we just need to push it on the stack
-            }
-            Some(current_category) => {
-                let elapsed = self.stop_timer();
-
-                //record the current category's time
-                let new_time = self.data.times.get(current_category) + elapsed;
-                self.data.times.set(current_category, new_time);
-            }
-        }
-
-        //push the new category
-        self.timer_stack.push(category);
+        self.record(ProfilerEvent::GenericActivityStart {
+            category,
+            time: Instant::now(),
+        })
     }
 
-    pub fn record_computed_queries(&mut self, category: ProfileCategory, count: usize) {
-        let (hits, computed) = *self.data.query_counts.get(category);
-        self.data.query_counts.set(category, (hits, computed + count as u64));
-    }
-
-    pub fn record_query_hit(&mut self, category: ProfileCategory) {
-        let (hits, computed) = *self.data.query_counts.get(category);
-        self.data.query_counts.set(category, (hits + 1, computed));
-    }
-
+    #[inline]
     pub fn end_activity(&mut self, category: ProfileCategory) {
-        match self.timer_stack.pop() {
-            None => bug!("end_activity() was called but there was no running activity"),
-            Some(c) =>
-                assert!(
-                    c == category,
-                    "end_activity() was called but a different activity was running"),
-        }
+        self.record(ProfilerEvent::GenericActivityEnd {
+            category,
+            time: Instant::now(),
+        })
+    }
 
-        //check if the new running timer is in the same category as this one
-        //if it is, we don't need to do anything
-        if let Some(c) = self.timer_stack.last() {
-            if *c == category {
-                return;
+    #[inline]
+    pub fn record_computed_queries(
+        &mut self,
+        query_name: &'static str,
+        category: ProfileCategory,
+        count: usize)
+        {
+        self.record(ProfilerEvent::QueryCount {
+            query_name,
+            category,
+            count,
+        })
+    }
+
+    #[inline]
+    pub fn record_query_hit(&mut self, query_name: &'static str, category: ProfileCategory) {
+        self.record(ProfilerEvent::QueryCacheHit {
+            query_name,
+            category,
+        })
+    }
+
+    #[inline]
+    pub fn start_query(&mut self, query_name: &'static str, category: ProfileCategory) {
+        self.record(ProfilerEvent::QueryStart {
+            query_name,
+            category,
+            time: Instant::now(),
+        });
+    }
+
+    #[inline]
+    pub fn end_query(&mut self, query_name: &'static str, category: ProfileCategory) {
+        self.record(ProfilerEvent::QueryEnd {
+            query_name,
+            category,
+            time: Instant::now(),
+        })
+    }
+
+    #[inline]
+    fn record(&mut self, event: ProfilerEvent) {
+        let thread_id = std::thread::current().id();
+        let events = self.events.entry(thread_id).or_default();
+
+        events.push(event);
+    }
+
+    fn calculate_thread_results(events: &Vec<ProfilerEvent>) -> CalculatedResults {
+        use self::ProfilerEvent::*;
+
+        assert!(
+            events.last().map(|e| !e.is_start_event()).unwrap_or(true),
+            "there was an event running when calculate_reslts() was called"
+        );
+
+        let mut results = CalculatedResults::new();
+
+        //(event, child time to subtract)
+        let mut query_stack = Vec::new();
+
+        for event in events {
+            match event {
+                QueryStart { .. } | GenericActivityStart { .. } => {
+                    query_stack.push((event, 0));
+                },
+                QueryEnd { query_name, category, time: end_time } => {
+                    let previous_query = query_stack.pop();
+                    if let Some((QueryStart {
+                                    query_name: p_query_name,
+                                    time: start_time,
+                                    category: _ }, child_time_to_subtract)) = previous_query {
+                        assert_eq!(
+                            p_query_name,
+                            query_name,
+                            "Saw a query end but the previous query wasn't the corresponding start"
+                        );
+
+                        let time_ns = time_between_ns(*start_time, *end_time);
+                        let self_time_ns = time_ns - child_time_to_subtract;
+                        let result_data = results.categories.entry(*category).or_default();
+
+                        *result_data.query_times.entry(query_name).or_default() += self_time_ns;
+
+                        if let Some((_, child_time_to_subtract)) = query_stack.last_mut() {
+                            *child_time_to_subtract += time_ns;
+                        }
+                    } else {
+                        bug!("Saw a query end but the previous event wasn't a query start");
+                    }
+                }
+                GenericActivityEnd { category, time: end_time } => {
+                    let previous_event = query_stack.pop();
+                    if let Some((GenericActivityStart {
+                                    category: previous_category,
+                                    time: start_time }, child_time_to_subtract)) = previous_event {
+                        assert_eq!(
+                            previous_category,
+                            category,
+                            "Saw an end but the previous event wasn't the corresponding start"
+                        );
+
+                        let time_ns = time_between_ns(*start_time, *end_time);
+                        let self_time_ns = time_ns - child_time_to_subtract;
+                        let result_data = results.categories.entry(*category).or_default();
+
+                        *result_data.query_times
+                            .entry("{time spent not running queries}")
+                            .or_default() += self_time_ns;
+
+                        if let Some((_, child_time_to_subtract)) = query_stack.last_mut() {
+                            *child_time_to_subtract += time_ns;
+                        }
+                    } else {
+                        bug!("Saw an activity end but the previous event wasn't an activity start");
+                    }
+                },
+                QueryCacheHit { category, query_name } => {
+                    let result_data = results.categories.entry(*category).or_default();
+
+                    let (hits, total) =
+                        result_data.query_cache_stats.entry(query_name).or_insert((0, 0));
+                    *hits += 1;
+                    *total += 1;
+                },
+                QueryCount { category, query_name, count } => {
+                    let result_data = results.categories.entry(*category).or_default();
+
+                    let (_, totals) =
+                        result_data.query_cache_stats.entry(query_name).or_insert((0, 0));
+                    *totals += *count as u64;
+                },
             }
         }
 
-        //the new timer is different than the previous,
-        //so record the elapsed time and start a new timer
-        let elapsed = self.stop_timer();
-        let new_time = self.data.times.get(category) + elapsed;
-        self.data.times.set(category, new_time);
+        //normalize the times to ms
+        for (_, data) in &mut results.categories {
+            for (_, time) in &mut data.query_times {
+                *time = *time / 1_000_000;
+            }
+        }
+
+        results
     }
 
-    fn stop_timer(&mut self) -> u64 {
-        let elapsed = self.current_timer.elapsed();
-
-        self.current_timer = Instant::now();
-
-        (elapsed.as_secs() * 1_000_000_000) + (elapsed.subsec_nanos() as u64)
+    fn get_results(&self, opts: &Options) -> CalculatedResults {
+        self.events
+            .iter()
+            .map(|(_, r)| SelfProfiler::calculate_thread_results(r))
+            .fold(CalculatedResults::new(), CalculatedResults::consolidate)
+            .with_options(opts)
     }
 
     pub fn print_results(&mut self, opts: &Options) {
         self.end_activity(ProfileCategory::Other);
 
-        assert!(
-            self.timer_stack.is_empty(),
-            "there were timers running when print_results() was called");
+        let results = self.get_results(opts);
+
+        let total_time = results.total_time() as f32;
 
         let out = io::stderr();
         let mut lock = out.lock();
 
-        let crate_name =
-            opts.crate_name
-            .as_ref()
-            .map(|n| format!(" for {}", n))
-            .unwrap_or_default();
+        let crate_name = results.crate_name.map(|n| format!(" for {}", n)).unwrap_or_default();
 
         writeln!(lock, "Self profiling results{}:", crate_name).unwrap();
         writeln!(lock).unwrap();
 
-        self.data.print(&mut lock);
+        writeln!(lock, "| Phase                                     | Time (ms)      \
+                        | Time (%) | Queries        | Hits (%)")
+            .unwrap();
+        writeln!(lock, "| ----------------------------------------- | -------------- \
+                        | -------- | -------------- | --------")
+            .unwrap();
+
+        let mut categories: Vec<_> = results.categories.iter().collect();
+        categories.sort_by(|(_, data1), (_, data2)| data2.total_time().cmp(&data1.total_time()));
+
+        for (category, data) in categories {
+            let (category_hits, category_total) = data.total_cache_data();
+            let category_hit_percent = calculate_percent(category_hits, category_total);
+
+            writeln!(
+                lock,
+                "| {0: <41} | {1: >14} | {2: >8.2} | {3: >14} | {4: >8}",
+                format!("{:?}", category),
+                data.total_time(),
+                ((data.total_time() as f32) / total_time) * 100.0,
+                category_total,
+                format!("{:.2}", category_hit_percent),
+            ).unwrap();
+
+            //in verbose mode, show individual query data
+            if results.verbose {
+                //don't show queries that took less than 1ms
+                let mut times: Vec<_> = data.query_times.iter().filter(|(_, t)| **t > 0).collect();
+                times.sort_by(|(_, time1), (_, time2)| time2.cmp(time1));
+
+                for (query, time) in times {
+                    let (hits, total) = data.query_cache_stats.get(query).unwrap_or(&(0, 0));
+                    let hit_percent = calculate_percent(*hits, *total);
+
+                    writeln!(
+                        lock,
+                        "| - {0: <39} | {1: >14} | {2: >8.2} | {3: >14} | {4: >8}",
+                        query,
+                        time,
+                        ((*time as f32) / total_time) * 100.0,
+                        total,
+                        format!("{:.2}", hit_percent),
+                    ).unwrap();
+                }
+            }
+        }
 
         writeln!(lock).unwrap();
         writeln!(lock, "Optimization level: {:?}", opts.optimize).unwrap();
-
-        let incremental = if opts.incremental.is_some() { "on" } else { "off" };
-        writeln!(lock, "Incremental: {}", incremental).unwrap();
+        writeln!(lock, "Incremental: {}", if results.incremental { "on" } else { "off" }).unwrap();
     }
 
     pub fn save_results(&self, opts: &Options) {
-        let category_data = self.data.json();
+        let results = self.get_results(opts);
+
         let compilation_options =
             format!("{{ \"optimization_level\": \"{:?}\", \"incremental\": {} }}",
-                    opts.optimize,
-                    if opts.incremental.is_some() { "true" } else { "false" });
+                    results.optimization_level,
+                    if results.incremental { "true" } else { "false" });
+
+        let mut category_data = String::new();
+
+        for (category, data) in &results.categories {
+            let (hits, total) = data.total_cache_data();
+            let hit_percent = calculate_percent(hits, total);
+
+            category_data.push_str(&format!("{{ \"category\": \"{:?}\", \"time_ms\": {}, \
+                                                \"query_count\": {}, \"query_hits\": {} }}",
+                                            category,
+                                            data.total_time(),
+                                            total,
+                                            format!("{:.2}", hit_percent)));
+        }
 
         let json = format!("{{ \"category_data\": {}, \"compilation_options\": {} }}",
                         category_data,
diff --git a/src/librustc_allocator/Cargo.toml b/src/librustc_allocator/Cargo.toml
index 03d33f4..cf6c598 100644
--- a/src/librustc_allocator/Cargo.toml
+++ b/src/librustc_allocator/Cargo.toml
@@ -2,6 +2,7 @@
 authors = ["The Rust Project Developers"]
 name = "rustc_allocator"
 version = "0.0.0"
+edition = "2018"
 
 [lib]
 path = "lib.rs"
diff --git a/src/librustc_allocator/expand.rs b/src/librustc_allocator/expand.rs
index 1fb1794..d302e76 100644
--- a/src/librustc_allocator/expand.rs
+++ b/src/librustc_allocator/expand.rs
@@ -1,6 +1,6 @@
+use log::debug;
 use rustc::middle::allocator::AllocatorKind;
-use rustc_errors;
-use smallvec::SmallVec;
+use smallvec::{smallvec, SmallVec};
 use syntax::{
     ast::{
         self, Arg, Attribute, Crate, Expr, FnHeader, Generics, Ident, Item, ItemKind,
@@ -23,7 +23,7 @@
 };
 use syntax_pos::Span;
 
-use {AllocatorMethod, AllocatorTy, ALLOCATOR_METHODS};
+use crate::{AllocatorMethod, AllocatorTy, ALLOCATOR_METHODS};
 
 pub fn modify(
     sess: &ParseSess,
@@ -54,7 +54,7 @@
     in_submod: isize,
 }
 
-impl<'a> MutVisitor for ExpandAllocatorDirectives<'a> {
+impl MutVisitor for ExpandAllocatorDirectives<'_> {
     fn flat_map_item(&mut self, item: P<Item>) -> SmallVec<[P<Item>; 1]> {
         debug!("in submodule {}", self.in_submod);
 
@@ -168,7 +168,7 @@
     cx: ExtCtxt<'a>,
 }
 
-impl<'a> AllocFnFactory<'a> {
+impl AllocFnFactory<'_> {
     fn allocator_fn(&self, method: &AllocatorMethod) -> P<Item> {
         let mut abi_args = Vec::new();
         let mut i = 0;
diff --git a/src/librustc_allocator/lib.rs b/src/librustc_allocator/lib.rs
index 41c0be6..16b9ccf 100644
--- a/src/librustc_allocator/lib.rs
+++ b/src/librustc_allocator/lib.rs
@@ -1,15 +1,6 @@
-#![feature(nll)]
 #![feature(rustc_private)]
 
-#[macro_use] extern crate log;
-extern crate rustc;
-extern crate rustc_data_structures;
-extern crate rustc_errors;
-extern crate rustc_target;
-extern crate syntax;
-extern crate syntax_pos;
-#[macro_use]
-extern crate smallvec;
+#![deny(rust_2018_idioms)]
 
 pub mod expand;
 
diff --git a/src/librustc_apfloat/lib.rs b/src/librustc_apfloat/lib.rs
index 17311f0..f79d448 100644
--- a/src/librustc_apfloat/lib.rs
+++ b/src/librustc_apfloat/lib.rs
@@ -30,9 +30,7 @@
 //!
 //! This API is completely unstable and subject to change.
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-      html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-      html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 #![forbid(unsafe_code)]
 #![deny(rust_2018_idioms)]
 
diff --git a/src/librustc_borrowck/Cargo.toml b/src/librustc_borrowck/Cargo.toml
index 3368bbf..f293739 100644
--- a/src/librustc_borrowck/Cargo.toml
+++ b/src/librustc_borrowck/Cargo.toml
@@ -2,6 +2,7 @@
 authors = ["The Rust Project Developers"]
 name = "rustc_borrowck"
 version = "0.0.0"
+edition = "2018"
 
 [lib]
 name = "rustc_borrowck"
@@ -13,8 +14,10 @@
 log = "0.4"
 syntax = { path = "../libsyntax" }
 syntax_pos = { path = "../libsyntax_pos" }
-graphviz = { path = "../libgraphviz" }
+# for "clarity", rename the graphviz crate to dot; graphviz within `borrowck`
+# refers to the borrowck-specific graphviz adapter traits.
+dot = { path = "../libgraphviz", package = "graphviz" }
 rustc = { path = "../librustc" }
 rustc_mir = { path = "../librustc_mir" }
-rustc_errors = { path = "../librustc_errors" }
-rustc_data_structures = { path = "../librustc_data_structures" }
\ No newline at end of file
+errors = { path = "../librustc_errors", package = "rustc_errors" }
+rustc_data_structures = { path = "../librustc_data_structures" }
diff --git a/src/librustc_borrowck/borrowck/check_loans.rs b/src/librustc_borrowck/borrowck/check_loans.rs
index cafb29e..f675c8d 100644
--- a/src/librustc_borrowck/borrowck/check_loans.rs
+++ b/src/librustc_borrowck/borrowck/check_loans.rs
@@ -7,10 +7,10 @@
 // 3. assignments do not affect things loaned out as immutable
 // 4. moves do not affect things loaned out in any way
 
-use self::UseError::*;
+use UseError::*;
 
-use borrowck::*;
-use borrowck::InteriorKind::{InteriorElement, InteriorField};
+use crate::borrowck::*;
+use crate::borrowck::InteriorKind::{InteriorElement, InteriorField};
 use rustc::middle::expr_use_visitor as euv;
 use rustc::middle::expr_use_visitor::MutateMode;
 use rustc::middle::mem_categorization as mc;
@@ -22,6 +22,7 @@
 use rustc::hir;
 use rustc::hir::Node;
 use rustc_mir::util::borrowck_errors::{BorrowckErrors, Origin};
+use log::debug;
 
 use std::rc::Rc;
 
@@ -101,7 +102,7 @@
 
     fn matched_pat(&mut self,
                    _matched_pat: &hir::Pat,
-                   _cmt: &mc::cmt_,
+                   _cmt: &mc::cmt_<'_>,
                    _mode: euv::MatchMode) { }
 
     fn consume_pat(&mut self,
@@ -910,7 +911,7 @@
     pub fn report_illegal_mutation(&self,
                                    span: Span,
                                    loan_path: &LoanPath<'tcx>,
-                                   loan: &Loan) {
+                                   loan: &Loan<'_>) {
         self.bccx.cannot_assign_to_borrowed(
             span, loan.span, &self.bccx.loan_path_to_string(loan_path), Origin::Ast)
             .emit();
diff --git a/src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs b/src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs
index f5e27a9..6b050fd 100644
--- a/src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs
+++ b/src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs
@@ -1,9 +1,9 @@
 //! Computes moves.
 
-use borrowck::*;
-use borrowck::gather_loans::move_error::MovePlace;
-use borrowck::gather_loans::move_error::{MoveError, MoveErrorCollector};
-use borrowck::move_data::*;
+use crate::borrowck::*;
+use crate::borrowck::gather_loans::move_error::MovePlace;
+use crate::borrowck::gather_loans::move_error::{MoveError, MoveErrorCollector};
+use crate::borrowck::move_data::*;
 use rustc::middle::expr_use_visitor as euv;
 use rustc::middle::mem_categorization as mc;
 use rustc::middle::mem_categorization::Categorization;
@@ -15,6 +15,7 @@
 use syntax_pos::Span;
 use rustc::hir::*;
 use rustc::hir::Node;
+use log::debug;
 
 struct GatherMoveInfo<'c, 'tcx: 'c> {
     id: hir::ItemLocalId,
diff --git a/src/librustc_borrowck/borrowck/gather_loans/lifetime.rs b/src/librustc_borrowck/borrowck/gather_loans/lifetime.rs
index 8fc0a3d..1159745 100644
--- a/src/librustc_borrowck/borrowck/gather_loans/lifetime.rs
+++ b/src/librustc_borrowck/borrowck/gather_loans/lifetime.rs
@@ -1,7 +1,7 @@
 //! This module implements the check that the lifetime of a borrow
 //! does not exceed the lifetime of the value being borrowed.
 
-use borrowck::*;
+use crate::borrowck::*;
 use rustc::middle::expr_use_visitor as euv;
 use rustc::middle::mem_categorization as mc;
 use rustc::middle::mem_categorization::Categorization;
@@ -10,6 +10,7 @@
 
 use syntax::ast;
 use syntax_pos::Span;
+use log::debug;
 
 type R = Result<(),()>;
 
diff --git a/src/librustc_borrowck/borrowck/gather_loans/mod.rs b/src/librustc_borrowck/borrowck/gather_loans/mod.rs
index d681c77..c21a43b 100644
--- a/src/librustc_borrowck/borrowck/gather_loans/mod.rs
+++ b/src/librustc_borrowck/borrowck/gather_loans/mod.rs
@@ -6,8 +6,8 @@
 // their associated scopes.  In phase two, checking loans, we will then make
 // sure that all of these loans are honored.
 
-use borrowck::*;
-use borrowck::move_data::MoveData;
+use crate::borrowck::*;
+use crate::borrowck::move_data::MoveData;
 use rustc::middle::expr_use_visitor as euv;
 use rustc::middle::mem_categorization as mc;
 use rustc::middle::mem_categorization::Categorization;
@@ -17,8 +17,9 @@
 use syntax::ast;
 use syntax_pos::Span;
 use rustc::hir;
+use log::debug;
 
-use self::restrictions::RestrictionResult;
+use restrictions::RestrictionResult;
 
 mod lifetime;
 mod restrictions;
@@ -427,7 +428,7 @@
         // }
     }
 
-    pub fn mark_loan_path_as_mutated(&self, loan_path: &LoanPath) {
+    pub fn mark_loan_path_as_mutated(&self, loan_path: &LoanPath<'_>) {
         //! For mutable loans of content whose mutability derives
         //! from a local variable, mark the mutability decl as necessary.
 
diff --git a/src/librustc_borrowck/borrowck/gather_loans/move_error.rs b/src/librustc_borrowck/borrowck/gather_loans/move_error.rs
index 00cbc25..622dd8e 100644
--- a/src/librustc_borrowck/borrowck/gather_loans/move_error.rs
+++ b/src/librustc_borrowck/borrowck/gather_loans/move_error.rs
@@ -1,4 +1,4 @@
-use borrowck::BorrowckCtxt;
+use crate::borrowck::BorrowckCtxt;
 use rustc::middle::mem_categorization as mc;
 use rustc::middle::mem_categorization::Categorization;
 use rustc::middle::mem_categorization::NoteClosureEnv;
@@ -8,7 +8,8 @@
 use syntax::ast;
 use syntax_pos;
 use errors::{DiagnosticBuilder, Applicability};
-use borrowck::gather_loans::gather_moves::PatternSource;
+use crate::borrowck::gather_loans::gather_moves::PatternSource;
+use log::debug;
 
 pub struct MoveErrorCollector<'tcx> {
     errors: Vec<MoveError<'tcx>>
@@ -167,10 +168,10 @@
     }
 }
 
-fn note_move_destination(mut err: DiagnosticBuilder,
+fn note_move_destination(mut err: DiagnosticBuilder<'_>,
                          move_to_span: syntax_pos::Span,
                          pat_name: ast::Name,
-                         is_first_note: bool) -> DiagnosticBuilder {
+                         is_first_note: bool) -> DiagnosticBuilder<'_> {
     if is_first_note {
         err.span_label(
             move_to_span,
diff --git a/src/librustc_borrowck/borrowck/gather_loans/restrictions.rs b/src/librustc_borrowck/borrowck/gather_loans/restrictions.rs
index a43a7f1..9f4c05a 100644
--- a/src/librustc_borrowck/borrowck/gather_loans/restrictions.rs
+++ b/src/librustc_borrowck/borrowck/gather_loans/restrictions.rs
@@ -1,13 +1,14 @@
 //! Computes the restrictions that result from a borrow.
 
-use borrowck::*;
+use crate::borrowck::*;
 use rustc::middle::expr_use_visitor as euv;
 use rustc::middle::mem_categorization as mc;
 use rustc::middle::mem_categorization::Categorization;
 use rustc::ty;
 use syntax_pos::Span;
+use log::debug;
 
-use borrowck::ToInteriorKind;
+use crate::borrowck::ToInteriorKind;
 
 use std::rc::Rc;
 
diff --git a/src/librustc_borrowck/borrowck/mod.rs b/src/librustc_borrowck/borrowck/mod.rs
index e40c2b4..4ced72c 100644
--- a/src/librustc_borrowck/borrowck/mod.rs
+++ b/src/librustc_borrowck/borrowck/mod.rs
@@ -2,13 +2,13 @@
 
 #![allow(non_camel_case_types)]
 
-pub use self::LoanPathKind::*;
-pub use self::LoanPathElem::*;
-pub use self::bckerr_code::*;
-pub use self::AliasableViolationKind::*;
-pub use self::MovedValueUseKind::*;
+pub use LoanPathKind::*;
+pub use LoanPathElem::*;
+pub use bckerr_code::*;
+pub use AliasableViolationKind::*;
+pub use MovedValueUseKind::*;
 
-use self::InteriorKind::*;
+use InteriorKind::*;
 
 use rustc::hir::HirId;
 use rustc::hir::Node;
@@ -37,10 +37,11 @@
 use syntax::ast;
 use syntax_pos::{MultiSpan, Span};
 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
+use log::debug;
 
 use rustc::hir;
 
-use dataflow::{DataFlowContext, BitwiseOperator, DataFlowOperator, KillFrom};
+use crate::dataflow::{DataFlowContext, BitwiseOperator, DataFlowOperator, KillFrom};
 
 pub mod check_loans;
 
@@ -61,7 +62,7 @@
     });
 }
 
-pub fn provide(providers: &mut Providers) {
+pub fn provide(providers: &mut Providers<'_>) {
     *providers = Providers {
         borrowck,
         ..*providers
@@ -398,7 +399,7 @@
 }
 
 fn closure_to_block(closure_id: LocalDefId,
-                    tcx: TyCtxt) -> ast::NodeId {
+                    tcx: TyCtxt<'_, '_, '_>) -> ast::NodeId {
     let closure_id = tcx.hir().local_def_id_to_node_id(closure_id);
     match tcx.hir().get(closure_id) {
         Node::Expr(expr) => match expr.node {
@@ -1214,8 +1215,8 @@
     }
 
     fn note_immutability_blame(&self,
-                               db: &mut DiagnosticBuilder,
-                               blame: Option<ImmutabilityBlame>,
+                               db: &mut DiagnosticBuilder<'_>,
+                               blame: Option<ImmutabilityBlame<'_>>,
                                error_node_id: ast::NodeId) {
         match blame {
             None => {}
@@ -1271,7 +1272,7 @@
      // binding: either to make the binding mutable (if its type is
      // not a mutable reference) or to avoid borrowing altogether
     fn note_immutable_local(&self,
-                            db: &mut DiagnosticBuilder,
+                            db: &mut DiagnosticBuilder<'_>,
                             borrowed_node_id: ast::NodeId,
                             binding_node_id: ast::NodeId) {
         let let_span = self.tcx.hir().span(binding_node_id);
@@ -1349,7 +1350,7 @@
         }
     }
 
-    fn note_and_explain_mutbl_error(&self, db: &mut DiagnosticBuilder, err: &BckError<'a, 'tcx>,
+    fn note_and_explain_mutbl_error(&self, db: &mut DiagnosticBuilder<'_>, err: &BckError<'a, 'tcx>,
                                     error_span: &Span) {
         match err.cmt.note {
             mc::NoteClosureEnv(upvar_id) | mc::NoteUpvarRef(upvar_id) => {
@@ -1487,7 +1488,7 @@
 }
 
 impl<'tcx> fmt::Debug for InteriorKind {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match *self {
             InteriorField(mc::FieldIndex(_, info)) => write!(f, "{}", info),
             InteriorElement => write!(f, "[]"),
@@ -1496,7 +1497,7 @@
 }
 
 impl<'tcx> fmt::Debug for Loan<'tcx> {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(f, "Loan_{}({:?}, {:?}, {:?}-{:?}, {:?})",
                self.index,
                self.loan_path,
@@ -1508,7 +1509,7 @@
 }
 
 impl<'tcx> fmt::Debug for LoanPath<'tcx> {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match self.kind {
             LpVar(id) => {
                 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir().node_to_string(id)))
@@ -1543,7 +1544,7 @@
 }
 
 impl<'tcx> fmt::Display for LoanPath<'tcx> {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match self.kind {
             LpVar(id) => {
                 write!(f, "$({})", ty::tls::with(|tcx| tcx.hir().node_to_user_string(id)))
diff --git a/src/librustc_borrowck/borrowck/move_data.rs b/src/librustc_borrowck/borrowck/move_data.rs
index 56c9f92..a206c37 100644
--- a/src/librustc_borrowck/borrowck/move_data.rs
+++ b/src/librustc_borrowck/borrowck/move_data.rs
@@ -1,11 +1,11 @@
 //! Data structures used for tracking moves. Please see the extensive
 //! comments in the section "Moves and initialization" in `README.md`.
 
-pub use self::MoveKind::*;
+pub use MoveKind::*;
 
-use dataflow::{DataFlowContext, BitwiseOperator, DataFlowOperator, KillFrom};
+use crate::dataflow::{DataFlowContext, BitwiseOperator, DataFlowOperator, KillFrom};
 
-use borrowck::*;
+use crate::borrowck::*;
 use rustc::cfg;
 use rustc::ty::{self, TyCtxt};
 use rustc::util::nodemap::FxHashMap;
@@ -15,6 +15,7 @@
 use std::usize;
 use syntax_pos::Span;
 use rustc::hir;
+use log::debug;
 
 #[derive(Default)]
 pub struct MoveData<'tcx> {
@@ -145,7 +146,7 @@
 
 pub type AssignDataFlow<'a, 'tcx> = DataFlowContext<'a, 'tcx, AssignDataFlowOperator>;
 
-fn loan_path_is_precise(loan_path: &LoanPath) -> bool {
+fn loan_path_is_precise(loan_path: &LoanPath<'_>) -> bool {
     match loan_path.kind {
         LpVar(_) | LpUpvar(_) => {
             true
@@ -428,8 +429,8 @@
     /// killed by scoping. See `README.md` for more details.
     fn add_gen_kills(&self,
                      bccx: &BorrowckCtxt<'a, 'tcx>,
-                     dfcx_moves: &mut MoveDataFlow,
-                     dfcx_assign: &mut AssignDataFlow) {
+                     dfcx_moves: &mut MoveDataFlow<'_, '_>,
+                     dfcx_assign: &mut AssignDataFlow<'_, '_>) {
         for (i, the_move) in self.moves.borrow().iter().enumerate() {
             dfcx_moves.add_gen(the_move.id, i);
         }
@@ -537,7 +538,7 @@
                   path: MovePathIndex,
                   kill_id: hir::ItemLocalId,
                   kill_kind: KillFrom,
-                  dfcx_moves: &mut MoveDataFlow) {
+                  dfcx_moves: &mut MoveDataFlow<'_, '_>) {
         // We can only perform kills for paths that refer to a unique location,
         // since otherwise we may kill a move from one location with an
         // assignment referring to another location.
diff --git a/src/librustc_borrowck/borrowck/unused.rs b/src/librustc_borrowck/borrowck/unused.rs
index 5db98f0..60a9c18 100644
--- a/src/librustc_borrowck/borrowck/unused.rs
+++ b/src/librustc_borrowck/borrowck/unused.rs
@@ -7,7 +7,7 @@
 use std::slice;
 use syntax::ptr::P;
 
-use borrowck::BorrowckCtxt;
+use crate::borrowck::BorrowckCtxt;
 
 pub fn check<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, body: &'tcx hir::Body) {
     let mut used_mut = bccx.used_mut_nodes.borrow().clone();
diff --git a/src/librustc_borrowck/dataflow.rs b/src/librustc_borrowck/dataflow.rs
index 8cf6205..90f33ed 100644
--- a/src/librustc_borrowck/dataflow.rs
+++ b/src/librustc_borrowck/dataflow.rs
@@ -10,6 +10,7 @@
 use std::mem;
 use std::usize;
 use syntax::print::pprust::PrintState;
+use log::debug;
 
 use rustc_data_structures::graph::implementation::OUTGOING;
 
@@ -80,7 +81,7 @@
     fn initial_value(&self) -> bool;
 }
 
-struct PropagationContext<'a, 'b: 'a, 'tcx: 'b, O: 'a> {
+struct PropagationContext<'a, 'b: 'a, 'tcx: 'b, O> {
     dfcx: &'a mut DataFlowContext<'b, 'tcx, O>,
     changed: bool
 }
@@ -99,12 +100,12 @@
 }
 
 impl<'a, 'tcx, O:DataFlowOperator> pprust::PpAnn for DataFlowContext<'a, 'tcx, O> {
-    fn nested(&self, state: &mut pprust::State, nested: pprust::Nested) -> io::Result<()> {
+    fn nested(&self, state: &mut pprust::State<'_>, nested: pprust::Nested) -> io::Result<()> {
         pprust::PpAnn::nested(self.tcx.hir(), state, nested)
     }
     fn pre(&self,
-           ps: &mut pprust::State,
-           node: pprust::AnnNode) -> io::Result<()> {
+           ps: &mut pprust::State<'_>,
+           node: pprust::AnnNode<'_>) -> io::Result<()> {
         let id = match node {
             pprust::AnnNode::Name(_) => return Ok(()),
             pprust::AnnNode::Expr(expr) => expr.hir_id.local_id,
diff --git a/src/librustc_borrowck/graphviz.rs b/src/librustc_borrowck/graphviz.rs
index adad8c5..77056d4 100644
--- a/src/librustc_borrowck/graphviz.rs
+++ b/src/librustc_borrowck/graphviz.rs
@@ -2,16 +2,15 @@
 //! libgraphviz traits, specialized to attaching borrowck analysis
 //! data to rendered labels.
 
-pub use self::Variant::*;
+pub use Variant::*;
 
 pub use rustc::cfg::graphviz::{Node, Edge};
 use rustc::cfg::graphviz as cfg_dot;
 
-use borrowck;
-use borrowck::{BorrowckCtxt, LoanPath};
-use dot;
+use crate::borrowck::{self, BorrowckCtxt, LoanPath};
+use crate::dataflow::{DataFlowOperator, DataFlowContext, EntryOrExit};
+use log::debug;
 use rustc::cfg::CFGIndex;
-use dataflow::{DataFlowOperator, DataFlowContext, EntryOrExit};
 use std::rc::Rc;
 
 #[derive(Debug, Copy, Clone)]
@@ -53,7 +52,7 @@
         sets
     }
 
-    fn dataflow_for_variant(&self, e: EntryOrExit, n: &Node, v: Variant) -> String {
+    fn dataflow_for_variant(&self, e: EntryOrExit, n: &Node<'_>, v: Variant) -> String {
         let cfgidx = n.0;
         match v {
             Loans   => self.dataflow_loans_for(e, cfgidx),
@@ -89,7 +88,7 @@
         let dfcx = &self.analysis_data.loans;
         let loan_index_to_path = |loan_index| {
             let all_loans = &self.analysis_data.all_loans;
-            let l: &borrowck::Loan = &all_loans[loan_index];
+            let l: &borrowck::Loan<'_> = &all_loans[loan_index];
             l.loan_path()
         };
         self.build_set(e, cfgidx, dfcx, loan_index_to_path)
diff --git a/src/librustc_borrowck/lib.rs b/src/librustc_borrowck/lib.rs
index 8bdc4e1..cf4669d 100644
--- a/src/librustc_borrowck/lib.rs
+++ b/src/librustc_borrowck/lib.rs
@@ -1,25 +1,14 @@
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-      html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-      html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 
 #![allow(non_camel_case_types)]
+#![deny(rust_2018_idioms)]
 
 #![feature(nll)]
 
 #![recursion_limit="256"]
 
-#[macro_use] extern crate log;
-extern crate syntax;
-extern crate syntax_pos;
-extern crate rustc_errors as errors;
-extern crate rustc_data_structures;
-
-// for "clarity", rename the graphviz crate to dot; graphviz within `borrowck`
-// refers to the borrowck-specific graphviz adapter traits.
-extern crate graphviz as dot;
 #[macro_use]
 extern crate rustc;
-extern crate rustc_mir;
 
 pub use borrowck::check_crate;
 pub use borrowck::build_borrowck_dataflow_data_for_fn;
diff --git a/src/librustc_codegen_llvm/back/rpath.rs b/src/librustc_codegen_llvm/back/rpath.rs
index aeff23d..a5c828e 100644
--- a/src/librustc_codegen_llvm/back/rpath.rs
+++ b/src/librustc_codegen_llvm/back/rpath.rs
@@ -101,9 +101,9 @@
 
     let cwd = env::current_dir().unwrap();
     let mut lib = fs::canonicalize(&cwd.join(lib)).unwrap_or_else(|_| cwd.join(lib));
-    lib.pop();
+    lib.pop(); // strip filename
     let mut output = cwd.join(&config.out_filename);
-    output.pop();
+    output.pop(); // strip filename
     let output = fs::canonicalize(&output).unwrap_or(output);
     let relative = path_relative_from(&lib, &output).unwrap_or_else(||
         panic!("couldn't create relative path from {:?} to {:?}", output, lib));
diff --git a/src/librustc_codegen_llvm/base.rs b/src/librustc_codegen_llvm/base.rs
index 6e1ef44..d9f44ca 100644
--- a/src/librustc_codegen_llvm/base.rs
+++ b/src/librustc_codegen_llvm/base.rs
@@ -20,6 +20,7 @@
 
 use llvm;
 use metadata;
+use rustc::dep_graph;
 use rustc::mir::mono::{Linkage, Visibility, Stats};
 use rustc::middle::cstore::{EncodedMetadata};
 use rustc::ty::TyCtxt;
@@ -145,7 +146,8 @@
     let ((stats, module), _) = tcx.dep_graph.with_task(dep_node,
                                                        tcx,
                                                        cgu_name,
-                                                       module_codegen);
+                                                       module_codegen,
+                                                       dep_graph::hash_result);
     let time_to_codegen = start_time.elapsed();
 
     // We assume that the cost to run LLVM on a CGU is proportional to
diff --git a/src/librustc_codegen_llvm/lib.rs b/src/librustc_codegen_llvm/lib.rs
index ab2fb67..ad8db25 100644
--- a/src/librustc_codegen_llvm/lib.rs
+++ b/src/librustc_codegen_llvm/lib.rs
@@ -4,9 +4,7 @@
 //!
 //! This API is completely unstable and subject to change.
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-      html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-      html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 
 #![feature(box_patterns)]
 #![feature(box_syntax)]
diff --git a/src/librustc_codegen_ssa/lib.rs b/src/librustc_codegen_ssa/lib.rs
index 1accbeb..58b3f04 100644
--- a/src/librustc_codegen_ssa/lib.rs
+++ b/src/librustc_codegen_ssa/lib.rs
@@ -1,6 +1,4 @@
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-      html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-      html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 
 #![feature(box_patterns)]
 #![feature(box_syntax)]
diff --git a/src/librustc_codegen_utils/Cargo.toml b/src/librustc_codegen_utils/Cargo.toml
index 34a09f3..5f241eb 100644
--- a/src/librustc_codegen_utils/Cargo.toml
+++ b/src/librustc_codegen_utils/Cargo.toml
@@ -2,6 +2,7 @@
 authors = ["The Rust Project Developers"]
 name = "rustc_codegen_utils"
 version = "0.0.0"
+edition = "2018"
 
 [lib]
 name = "rustc_codegen_utils"
diff --git a/src/librustc_codegen_utils/codegen_backend.rs b/src/librustc_codegen_utils/codegen_backend.rs
index 8981c54..28d7d18 100644
--- a/src/librustc_codegen_utils/codegen_backend.rs
+++ b/src/librustc_codegen_utils/codegen_backend.rs
@@ -4,9 +4,7 @@
 //!
 //! This API is completely unstable and subject to change.
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-      html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-      html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 #![deny(warnings)]
 
 #![feature(box_syntax)]
@@ -31,7 +29,7 @@
 use rustc::middle::cstore::MetadataLoader;
 use rustc::dep_graph::DepGraph;
 use rustc_target::spec::Target;
-use link::out_filename;
+use crate::link::out_filename;
 
 pub use rustc_data_structures::sync::MetadataRef;
 
@@ -44,8 +42,8 @@
     fn diagnostics(&self) -> &[(&'static str, &'static str)] { &[] }
 
     fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync>;
-    fn provide(&self, _providers: &mut Providers);
-    fn provide_extern(&self, _providers: &mut Providers);
+    fn provide(&self, _providers: &mut Providers<'_>);
+    fn provide_extern(&self, _providers: &mut Providers<'_>);
     fn codegen_crate<'a, 'tcx>(
         &self,
         tcx: TyCtxt<'a, 'tcx, 'tcx>,
@@ -111,8 +109,8 @@
         box NoLlvmMetadataLoader
     }
 
-    fn provide(&self, providers: &mut Providers) {
-        ::symbol_names::provide(providers);
+    fn provide(&self, providers: &mut Providers<'_>) {
+        crate::symbol_names::provide(providers);
 
         providers.target_features_whitelist = |_tcx, _cnum| {
             Default::default() // Just a dummy
@@ -120,7 +118,7 @@
         providers.is_reachable_non_generic = |_tcx, _defid| true;
         providers.exported_symbols = |_tcx, _crate| Arc::new(Vec::new());
     }
-    fn provide_extern(&self, providers: &mut Providers) {
+    fn provide_extern(&self, providers: &mut Providers<'_>) {
         providers.is_reachable_non_generic = |_tcx, _defid| true;
     }
 
@@ -131,12 +129,12 @@
     ) -> Box<dyn Any> {
         use rustc_mir::monomorphize::item::MonoItem;
 
-        ::check_for_rustc_errors_attr(tcx);
-        ::symbol_names_test::report_symbol_names(tcx);
-        ::rustc_incremental::assert_dep_graph(tcx);
-        ::rustc_incremental::assert_module_sources::assert_module_sources(tcx);
+        crate::check_for_rustc_errors_attr(tcx);
+        crate::symbol_names_test::report_symbol_names(tcx);
+        rustc_incremental::assert_dep_graph(tcx);
+        rustc_incremental::assert_module_sources::assert_module_sources(tcx);
         // FIXME: Fix this
-        // ::rustc::middle::dependency_format::calculate(tcx);
+        // rustc::middle::dependency_format::calculate(tcx);
         let _ = tcx.link_args(LOCAL_CRATE);
         let _ = tcx.native_libraries(LOCAL_CRATE);
         let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
diff --git a/src/librustc_codegen_utils/lib.rs b/src/librustc_codegen_utils/lib.rs
index 8e96f98..2b70141 100644
--- a/src/librustc_codegen_utils/lib.rs
+++ b/src/librustc_codegen_utils/lib.rs
@@ -2,9 +2,7 @@
 //!
 //! This API is completely unstable and subject to change.
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-      html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-      html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 
 #![feature(box_patterns)]
 #![feature(box_syntax)]
@@ -16,18 +14,10 @@
 
 #![recursion_limit="256"]
 
-extern crate flate2;
-#[macro_use]
-extern crate log;
+#![deny(rust_2018_idioms)]
 
 #[macro_use]
 extern crate rustc;
-extern crate rustc_target;
-extern crate rustc_metadata;
-extern crate rustc_mir;
-extern crate rustc_incremental;
-extern crate syntax;
-extern crate syntax_pos;
 #[macro_use] extern crate rustc_data_structures;
 
 use rustc::ty::TyCtxt;
@@ -42,7 +32,7 @@
 /// error in codegen. This is used to write compile-fail tests
 /// that actually test that compilation succeeds without
 /// reporting an error.
-pub fn check_for_rustc_errors_attr(tcx: TyCtxt) {
+pub fn check_for_rustc_errors_attr(tcx: TyCtxt<'_, '_, '_>) {
     if let Some((def_id, _)) = tcx.entry_fn(LOCAL_CRATE) {
         if tcx.has_attr(def_id, "rustc_error") {
             tcx.sess.span_fatal(tcx.def_span(def_id), "compilation successful");
diff --git a/src/librustc_codegen_utils/link.rs b/src/librustc_codegen_utils/link.rs
index 09e22bd..f3a1b21 100644
--- a/src/librustc_codegen_utils/link.rs
+++ b/src/librustc_codegen_utils/link.rs
@@ -41,7 +41,7 @@
                        attrs: &[ast::Attribute],
                        input: &Input) -> String {
     let validate = |s: String, span: Option<Span>| {
-        ::rustc_metadata::validate_crate_name(sess, &s, span);
+        rustc_metadata::validate_crate_name(sess, &s, span);
         s
     };
 
diff --git a/src/librustc_codegen_utils/symbol_names.rs b/src/librustc_codegen_utils/symbol_names.rs
index 3238a0b..8d10585 100644
--- a/src/librustc_codegen_utils/symbol_names.rs
+++ b/src/librustc_codegen_utils/symbol_names.rs
@@ -103,10 +103,12 @@
 
 use syntax_pos::symbol::Symbol;
 
+use log::debug;
+
 use std::fmt::Write;
 use std::mem::discriminant;
 
-pub fn provide(providers: &mut Providers) {
+pub fn provide(providers: &mut Providers<'_>) {
     *providers = Providers {
         def_symbol_name,
         symbol_name,
diff --git a/src/librustc_cratesio_shim/Cargo.toml b/src/librustc_cratesio_shim/Cargo.toml
index b8e494e..6bdfbe0 100644
--- a/src/librustc_cratesio_shim/Cargo.toml
+++ b/src/librustc_cratesio_shim/Cargo.toml
@@ -15,6 +15,7 @@
 authors = ["The Rust Project Developers"]
 name = "rustc_cratesio_shim"
 version = "0.0.0"
+edition = "2018"
 
 [lib]
 crate-type = ["dylib"]
diff --git a/src/librustc_cratesio_shim/src/lib.rs b/src/librustc_cratesio_shim/src/lib.rs
index 4024087..4c170f4 100644
--- a/src/librustc_cratesio_shim/src/lib.rs
+++ b/src/librustc_cratesio_shim/src/lib.rs
@@ -1,3 +1,5 @@
+#![deny(rust_2018_idioms)]
+
 // See Cargo.toml for a comment explaining this crate.
 #![allow(unused_extern_crates)]
 
diff --git a/src/librustc_data_structures/Cargo.toml b/src/librustc_data_structures/Cargo.toml
index 1754376..f781952 100644
--- a/src/librustc_data_structures/Cargo.toml
+++ b/src/librustc_data_structures/Cargo.toml
@@ -2,6 +2,7 @@
 authors = ["The Rust Project Developers"]
 name = "rustc_data_structures"
 version = "0.0.0"
+edition = "2018"
 
 [lib]
 name = "rustc_data_structures"
@@ -16,8 +17,8 @@
 graphviz = { path = "../libgraphviz" }
 cfg-if = "0.1.2"
 stable_deref_trait = "1.0.0"
-rustc-rayon = "0.1.1"
-rustc-rayon-core = "0.1.1"
+rayon = { version = "0.1.1", package = "rustc-rayon" }
+rayon-core = { version = "0.1.1", package = "rustc-rayon-core" }
 rustc-hash = "1.0.1"
 smallvec = { version = "0.6.7", features = ["union", "may_dangle"] }
 
diff --git a/src/librustc_data_structures/bit_set.rs b/src/librustc_data_structures/bit_set.rs
index 8adfe37..05d2185 100644
--- a/src/librustc_data_structures/bit_set.rs
+++ b/src/librustc_data_structures/bit_set.rs
@@ -1,4 +1,4 @@
-use indexed_vec::{Idx, IndexVec};
+use crate::indexed_vec::{Idx, IndexVec};
 use smallvec::SmallVec;
 use std::fmt;
 use std::iter;
@@ -208,7 +208,7 @@
 }
 
 impl<T: Idx> fmt::Debug for BitSet<T> {
-    fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
         w.debug_list()
          .entries(self.iter())
          .finish()
@@ -366,7 +366,7 @@
         dense
     }
 
-    fn iter(&self) -> slice::Iter<T> {
+    fn iter(&self) -> slice::Iter<'_, T> {
         self.elems.iter()
     }
 }
@@ -536,7 +536,7 @@
         }
     }
 
-    pub fn iter(&self) -> HybridIter<T> {
+    pub fn iter(&self) -> HybridIter<'_, T> {
         match self {
             HybridBitSet::Sparse(sparse) => HybridIter::Sparse(sparse.iter()),
             HybridBitSet::Dense(dense) => HybridIter::Dense(dense.iter()),
diff --git a/src/librustc_data_structures/fingerprint.rs b/src/librustc_data_structures/fingerprint.rs
index 2e596ca..c4c0db5 100644
--- a/src/librustc_data_structures/fingerprint.rs
+++ b/src/librustc_data_structures/fingerprint.rs
@@ -1,5 +1,5 @@
+use crate::stable_hasher;
 use std::mem;
-use stable_hasher;
 use serialize;
 use serialize::opaque::{EncodeResult, Encoder, Decoder};
 
@@ -70,7 +70,7 @@
 }
 
 impl ::std::fmt::Display for Fingerprint {
-    fn fmt(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
+    fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
         write!(formatter, "{:x}-{:x}", self.0, self.1)
     }
 }
diff --git a/src/librustc_data_structures/flock.rs b/src/librustc_data_structures/flock.rs
index 2dea249..255c5fd 100644
--- a/src/librustc_data_structures/flock.rs
+++ b/src/librustc_data_structures/flock.rs
@@ -14,12 +14,9 @@
     if #[cfg(unix)] {
         use std::ffi::{CString, OsStr};
         use std::os::unix::prelude::*;
-        use libc;
 
         #[cfg(any(target_os = "linux", target_os = "android"))]
         mod os {
-            use libc;
-
             #[repr(C)]
             pub struct flock {
                 pub l_type: libc::c_short,
@@ -35,8 +32,6 @@
 
         #[cfg(target_os = "freebsd")]
         mod os {
-            use libc;
-
             #[repr(C)]
             pub struct flock {
                 pub l_start: libc::off_t,
@@ -53,8 +48,6 @@
                   target_os = "netbsd",
                   target_os = "openbsd"))]
         mod os {
-            use libc;
-
             #[repr(C)]
             pub struct flock {
                 pub l_start: libc::off_t,
@@ -70,8 +63,6 @@
 
         #[cfg(target_os = "haiku")]
         mod os {
-            use libc;
-
             #[repr(C)]
             pub struct flock {
                 pub l_type: libc::c_short,
@@ -87,8 +78,6 @@
 
         #[cfg(any(target_os = "macos", target_os = "ios"))]
         mod os {
-            use libc;
-
             #[repr(C)]
             pub struct flock {
                 pub l_start: libc::off_t,
@@ -104,8 +93,6 @@
 
         #[cfg(target_os = "solaris")]
         mod os {
-            use libc;
-
             #[repr(C)]
             pub struct flock {
                 pub l_type: libc::c_short,
diff --git a/src/librustc_data_structures/graph/dominators/mod.rs b/src/librustc_data_structures/graph/dominators/mod.rs
index 536efff..aaed41d 100644
--- a/src/librustc_data_structures/graph/dominators/mod.rs
+++ b/src/librustc_data_structures/graph/dominators/mod.rs
@@ -117,7 +117,7 @@
         self.immediate_dominators[node].unwrap()
     }
 
-    pub fn dominators(&self, node: Node) -> Iter<Node> {
+    pub fn dominators(&self, node: Node) -> Iter<'_, Node> {
         assert!(self.is_reachable(node), "node {:?} is not reachable", node);
         Iter {
             dominators: self,
@@ -136,7 +136,7 @@
     }
 }
 
-pub struct Iter<'dom, Node: Idx + 'dom> {
+pub struct Iter<'dom, Node: Idx> {
     dominators: &'dom Dominators<Node>,
     node: Option<Node>,
 }
@@ -171,7 +171,7 @@
 }
 
 impl<Node: Idx> fmt::Debug for DominatorTree<Node> {
-    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
         fmt::Debug::fmt(
             &DominatorTreeNode {
                 tree: self,
@@ -188,7 +188,7 @@
 }
 
 impl<'tree, Node: Idx> fmt::Debug for DominatorTreeNode<'tree, Node> {
-    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
         let subtrees: Vec<_> = self.tree
             .children(self.node)
             .iter()
diff --git a/src/librustc_data_structures/graph/implementation/mod.rs b/src/librustc_data_structures/graph/implementation/mod.rs
index 0768873..a8b7340 100644
--- a/src/librustc_data_structures/graph/implementation/mod.rs
+++ b/src/librustc_data_structures/graph/implementation/mod.rs
@@ -20,10 +20,10 @@
 //! the field `next_edge`). Each of those fields is an array that should
 //! be indexed by the direction (see the type `Direction`).
 
-use bit_set::BitSet;
+use crate::bit_set::BitSet;
+use crate::snapshot_vec::{SnapshotVec, SnapshotVecDelegate};
 use std::fmt::Debug;
 use std::usize;
-use snapshot_vec::{SnapshotVec, SnapshotVecDelegate};
 
 #[cfg(test)]
 mod tests;
@@ -212,15 +212,19 @@
             .all(|(edge_idx, edge)| f(edge_idx, edge))
     }
 
-    pub fn outgoing_edges(&self, source: NodeIndex) -> AdjacentEdges<N, E> {
+    pub fn outgoing_edges(&self, source: NodeIndex) -> AdjacentEdges<'_, N, E> {
         self.adjacent_edges(source, OUTGOING)
     }
 
-    pub fn incoming_edges(&self, source: NodeIndex) -> AdjacentEdges<N, E> {
+    pub fn incoming_edges(&self, source: NodeIndex) -> AdjacentEdges<'_, N, E> {
         self.adjacent_edges(source, INCOMING)
     }
 
-    pub fn adjacent_edges(&self, source: NodeIndex, direction: Direction) -> AdjacentEdges<N, E> {
+    pub fn adjacent_edges(
+        &self,
+        source: NodeIndex,
+        direction: Direction
+    ) -> AdjacentEdges<'_, N, E> {
         let first_edge = self.node(source).first_edge[direction.repr];
         AdjacentEdges {
             graph: self,
@@ -291,11 +295,7 @@
 
 // # Iterators
 
-pub struct AdjacentEdges<'g, N, E>
-where
-    N: 'g,
-    E: 'g,
-{
+pub struct AdjacentEdges<'g, N, E> {
     graph: &'g Graph<N, E>,
     direction: Direction,
     next: EdgeIndex,
@@ -331,11 +331,7 @@
     }
 }
 
-pub struct DepthFirstTraversal<'g, N, E>
-where
-    N: 'g,
-    E: 'g,
-{
+pub struct DepthFirstTraversal<'g, N, E> {
     graph: &'g Graph<N, E>,
     stack: Vec<NodeIndex>,
     visited: BitSet<usize>,
diff --git a/src/librustc_data_structures/graph/implementation/tests.rs b/src/librustc_data_structures/graph/implementation/tests.rs
index a7a2504..82c6da3 100644
--- a/src/librustc_data_structures/graph/implementation/tests.rs
+++ b/src/librustc_data_structures/graph/implementation/tests.rs
@@ -1,4 +1,4 @@
-use graph::implementation::*;
+use crate::graph::implementation::*;
 use std::fmt::Debug;
 
 type TestGraph = Graph<&'static str, &'static str>;
diff --git a/src/librustc_data_structures/graph/scc/mod.rs b/src/librustc_data_structures/graph/scc/mod.rs
index baab377..e3264fd 100644
--- a/src/librustc_data_structures/graph/scc/mod.rs
+++ b/src/librustc_data_structures/graph/scc/mod.rs
@@ -3,9 +3,9 @@
 //! node in the graph. This uses Tarjan's algorithm that completes in
 //! O(n) time.
 
-use fx::FxHashSet;
-use graph::{DirectedGraph, WithNumNodes, WithSuccessors};
-use indexed_vec::{Idx, IndexVec};
+use crate::fx::FxHashSet;
+use crate::graph::{DirectedGraph, WithNumNodes, WithSuccessors};
+use crate::indexed_vec::{Idx, IndexVec};
 use std::ops::Range;
 
 mod test;
@@ -93,7 +93,7 @@
     }
 }
 
-struct SccsConstruction<'c, G: DirectedGraph + WithNumNodes + WithSuccessors + 'c, S: Idx> {
+struct SccsConstruction<'c, G: DirectedGraph + WithNumNodes + WithSuccessors, S: Idx> {
     graph: &'c G,
 
     /// The state of each node; used during walk to record the stack
diff --git a/src/librustc_data_structures/graph/scc/test.rs b/src/librustc_data_structures/graph/scc/test.rs
index e23cb13..da3a1ce 100644
--- a/src/librustc_data_structures/graph/scc/test.rs
+++ b/src/librustc_data_structures/graph/scc/test.rs
@@ -1,6 +1,6 @@
 #![cfg(test)]
 
-use graph::test::TestGraph;
+use crate::graph::test::TestGraph;
 use super::*;
 
 #[test]
diff --git a/src/librustc_data_structures/graph/test.rs b/src/librustc_data_structures/graph/test.rs
index 3d482e4..b390c41 100644
--- a/src/librustc_data_structures/graph/test.rs
+++ b/src/librustc_data_structures/graph/test.rs
@@ -1,4 +1,4 @@
-use fx::FxHashMap;
+use crate::fx::FxHashMap;
 use std::cmp::max;
 use std::slice;
 use std::iter;
diff --git a/src/librustc_data_structures/indexed_vec.rs b/src/librustc_data_structures/indexed_vec.rs
index 8d8fbe5..516ea7f 100644
--- a/src/librustc_data_structures/indexed_vec.rs
+++ b/src/librustc_data_structures/indexed_vec.rs
@@ -257,7 +257,7 @@
      @type         [$type:ident]
      @debug_format [$debug_format:tt]) => (
         impl ::std::fmt::Debug for $type {
-            fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
+            fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                 write!(fmt, $debug_format, self.as_u32())
             }
         }
@@ -495,7 +495,7 @@
 }
 
 impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
-    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
         fmt::Debug::fmt(&self.raw, fmt)
     }
 }
@@ -573,7 +573,7 @@
     }
 
     #[inline]
-    pub fn iter(&self) -> slice::Iter<T> {
+    pub fn iter(&self) -> slice::Iter<'_, T> {
         self.raw.iter()
     }
 
@@ -589,7 +589,7 @@
     }
 
     #[inline]
-    pub fn iter_mut(&mut self) -> slice::IterMut<T> {
+    pub fn iter_mut(&mut self) -> slice::IterMut<'_, T> {
         self.raw.iter_mut()
     }
 
diff --git a/src/librustc_data_structures/lib.rs b/src/librustc_data_structures/lib.rs
index ec71f51..08b453c 100644
--- a/src/librustc_data_structures/lib.rs
+++ b/src/librustc_data_structures/lib.rs
@@ -6,9 +6,7 @@
 //!
 //! This API is completely unstable and subject to change.
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-      html_favicon_url = "https://www.rust-lang.org/favicon.ico",
-      html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 
 #![feature(in_band_lifetimes)]
 #![feature(unboxed_closures)]
@@ -26,23 +24,16 @@
 #![cfg_attr(unix, feature(libc))]
 #![cfg_attr(test, feature(test))]
 
-extern crate core;
-extern crate ena;
+#![deny(rust_2018_idioms)]
+
 #[macro_use]
 extern crate log;
+#[allow(unused_extern_crates)]
 extern crate serialize as rustc_serialize; // used by deriving
 #[cfg(unix)]
 extern crate libc;
-extern crate parking_lot;
 #[macro_use]
 extern crate cfg_if;
-extern crate stable_deref_trait;
-extern crate rustc_rayon as rayon;
-extern crate rustc_rayon_core as rayon_core;
-extern crate rustc_hash;
-extern crate serialize;
-extern crate graphviz;
-extern crate smallvec;
 
 // See librustc_cratesio_shim/Cargo.toml for a comment explaining this.
 #[allow(unused_extern_crates)]
diff --git a/src/librustc_data_structures/obligation_forest/graphviz.rs b/src/librustc_data_structures/obligation_forest/graphviz.rs
index c2e3938..72551b4 100644
--- a/src/librustc_data_structures/obligation_forest/graphviz.rs
+++ b/src/librustc_data_structures/obligation_forest/graphviz.rs
@@ -1,5 +1,5 @@
+use crate::obligation_forest::{ForestObligation, ObligationForest};
 use graphviz as dot;
-use obligation_forest::{ForestObligation, ObligationForest};
 use std::env::var_os;
 use std::fs::File;
 use std::path::Path;
@@ -41,22 +41,22 @@
     type Node = usize;
     type Edge = (usize, usize);
 
-    fn graph_id(&self) -> dot::Id {
+    fn graph_id(&self) -> dot::Id<'_> {
         dot::Id::new("trait_obligation_forest").unwrap()
     }
 
-    fn node_id(&self, index: &Self::Node) -> dot::Id {
+    fn node_id(&self, index: &Self::Node) -> dot::Id<'_> {
         dot::Id::new(format!("obligation_{}", index)).unwrap()
     }
 
-    fn node_label(&self, index: &Self::Node) -> dot::LabelText {
+    fn node_label(&self, index: &Self::Node) -> dot::LabelText<'_> {
         let node = &self.nodes[*index];
         let label = format!("{:?} ({:?})", node.obligation.as_predicate(), node.state.get());
 
         dot::LabelText::LabelStr(label.into())
     }
 
-    fn edge_label(&self, (_index_source, _index_target): &Self::Edge) -> dot::LabelText {
+    fn edge_label(&self, (_index_source, _index_target): &Self::Edge) -> dot::LabelText<'_> {
         dot::LabelText::LabelStr("".into())
     }
 }
@@ -65,11 +65,11 @@
     type Node = usize;
     type Edge = (usize, usize);
 
-    fn nodes(&self) -> dot::Nodes<Self::Node> {
+    fn nodes(&self) -> dot::Nodes<'_, Self::Node> {
         (0..self.nodes.len()).collect()
     }
 
-    fn edges(&self) -> dot::Edges<Self::Edge> {
+    fn edges(&self) -> dot::Edges<'_, Self::Edge> {
         (0..self.nodes.len())
             .flat_map(|i| {
                 let node = &self.nodes[i];
diff --git a/src/librustc_data_structures/obligation_forest/mod.rs b/src/librustc_data_structures/obligation_forest/mod.rs
index 9dd7d20..546bb64 100644
--- a/src/librustc_data_structures/obligation_forest/mod.rs
+++ b/src/librustc_data_structures/obligation_forest/mod.rs
@@ -80,7 +80,7 @@
 //! processing step, we compress the vector to remove completed and error
 //! nodes, which aren't needed anymore.
 
-use fx::{FxHashMap, FxHashSet};
+use crate::fx::{FxHashMap, FxHashSet};
 
 use std::cell::Cell;
 use std::collections::hash_map::Entry;
@@ -733,7 +733,7 @@
 
 // I need a Clone closure
 #[derive(Clone)]
-struct GetObligation<'a, O: 'a>(&'a [Node<O>]);
+struct GetObligation<'a, O>(&'a [Node<O>]);
 
 impl<'a, 'b, O> FnOnce<(&'b usize,)> for GetObligation<'a, O> {
     type Output = &'a O;
diff --git a/src/librustc_data_structures/owning_ref/mod.rs b/src/librustc_data_structures/owning_ref/mod.rs
index 0b126e5..30e510c 100644
--- a/src/librustc_data_structures/owning_ref/mod.rs
+++ b/src/librustc_data_structures/owning_ref/mod.rs
@@ -1002,7 +1002,7 @@
     where O: Debug,
           T: Debug,
 {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(f,
                "OwningRef {{ owner: {:?}, reference: {:?} }}",
                self.owner(),
@@ -1014,7 +1014,7 @@
     where O: Debug,
           T: Debug,
 {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(f,
                "OwningRefMut {{ owner: {:?}, reference: {:?} }}",
                self.owner(),
@@ -1047,7 +1047,7 @@
     where O: Sync, for<'a> (&'a mut T): Sync {}
 
 impl Debug for dyn Erased {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(f, "<Erased>",)
     }
 }
diff --git a/src/librustc_data_structures/ptr_key.rs b/src/librustc_data_structures/ptr_key.rs
index 322dcbe..bf3ae2d 100644
--- a/src/librustc_data_structures/ptr_key.rs
+++ b/src/librustc_data_structures/ptr_key.rs
@@ -4,7 +4,7 @@
 /// A wrapper around reference that compares and hashes like a pointer.
 /// Can be used as a key in sets/maps indexed by pointers to avoid `unsafe`.
 #[derive(Debug)]
-pub struct PtrKey<'a, T: 'a>(pub &'a T);
+pub struct PtrKey<'a, T>(pub &'a T);
 
 impl<'a, T> Clone for PtrKey<'a, T> {
     fn clone(&self) -> Self { *self }
diff --git a/src/librustc_data_structures/snapshot_map/mod.rs b/src/librustc_data_structures/snapshot_map/mod.rs
index d408727..91d6e29 100644
--- a/src/librustc_data_structures/snapshot_map/mod.rs
+++ b/src/librustc_data_structures/snapshot_map/mod.rs
@@ -1,4 +1,4 @@
-use fx::FxHashMap;
+use crate::fx::FxHashMap;
 use std::hash::Hash;
 use std::ops;
 use std::mem;
diff --git a/src/librustc_data_structures/sorted_map.rs b/src/librustc_data_structures/sorted_map.rs
index 64bbb8d..1f674c1 100644
--- a/src/librustc_data_structures/sorted_map.rs
+++ b/src/librustc_data_structures/sorted_map.rs
@@ -111,7 +111,7 @@
 
     /// Iterate over elements, sorted by key
     #[inline]
-    pub fn iter(&self) -> ::std::slice::Iter<(K, V)> {
+    pub fn iter(&self) -> ::std::slice::Iter<'_, (K, V)> {
         self.data.iter()
     }
 
diff --git a/src/librustc_data_structures/stable_hasher.rs b/src/librustc_data_structures/stable_hasher.rs
index 4583f12..19343a9 100644
--- a/src/librustc_data_structures/stable_hasher.rs
+++ b/src/librustc_data_structures/stable_hasher.rs
@@ -1,7 +1,9 @@
 use std::hash::{Hash, Hasher, BuildHasher};
 use std::marker::PhantomData;
 use std::mem;
-use sip128::SipHasher128;
+use crate::sip128::SipHasher128;
+use crate::indexed_vec;
+use crate::bit_set;
 
 /// When hashing something that ends up affecting properties like symbol names,
 /// we want these symbol names to be calculated independently of other factors
@@ -17,7 +19,7 @@
 }
 
 impl<W: StableHasherResult> ::std::fmt::Debug for StableHasher<W> {
-    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
+    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
         write!(f, "{:?}", self.state)
     }
 }
@@ -433,7 +435,7 @@
     }
 }
 
-impl<I: ::indexed_vec::Idx, T, CTX> HashStable<CTX> for ::indexed_vec::IndexVec<I, T>
+impl<I: indexed_vec::Idx, T, CTX> HashStable<CTX> for indexed_vec::IndexVec<I, T>
     where T: HashStable<CTX>,
 {
     fn hash_stable<W: StableHasherResult>(&self,
@@ -447,7 +449,7 @@
 }
 
 
-impl<I: ::indexed_vec::Idx, CTX> HashStable<CTX> for ::bit_set::BitSet<I>
+impl<I: indexed_vec::Idx, CTX> HashStable<CTX> for bit_set::BitSet<I>
 {
     fn hash_stable<W: StableHasherResult>(&self,
                                           ctx: &mut CTX,
diff --git a/src/librustc_data_structures/svh.rs b/src/librustc_data_structures/svh.rs
index 7494795..3757f92 100644
--- a/src/librustc_data_structures/svh.rs
+++ b/src/librustc_data_structures/svh.rs
@@ -9,7 +9,7 @@
 use std::hash::{Hash, Hasher};
 use serialize::{Encodable, Decodable, Encoder, Decoder};
 
-use stable_hasher;
+use crate::stable_hasher;
 
 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
 pub struct Svh {
@@ -40,7 +40,7 @@
 }
 
 impl fmt::Display for Svh {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         f.pad(&self.to_string())
     }
 }
diff --git a/src/librustc_data_structures/sync.rs b/src/librustc_data_structures/sync.rs
index 7fef1f3..ba1f6eb 100644
--- a/src/librustc_data_structures/sync.rs
+++ b/src/librustc_data_structures/sync.rs
@@ -21,7 +21,7 @@
 use std::hash::{Hash, BuildHasher};
 use std::marker::PhantomData;
 use std::ops::{Deref, DerefMut};
-use owning_ref::{Erased, OwningRef};
+use crate::owning_ref::{Erased, OwningRef};
 
 pub fn serial_join<A, B, RA, RB>(oper_a: A, oper_b: B) -> (RA, RB)
     where A: FnOnce() -> RA,
@@ -261,12 +261,12 @@
             }
 
             #[inline(always)]
-            pub fn lock(&self) -> LockGuard<T> {
+            pub fn lock(&self) -> LockGuard<'_, T> {
                 self.0.lock()
             }
 
             #[inline(always)]
-            pub fn lock_mut(&self) -> LockGuard<T> {
+            pub fn lock_mut(&self) -> LockGuard<'_, T> {
                 self.lock()
             }
         }
@@ -490,19 +490,19 @@
 
     #[cfg(parallel_compiler)]
     #[inline(always)]
-    pub fn try_lock(&self) -> Option<LockGuard<T>> {
+    pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
         self.0.try_lock()
     }
 
     #[cfg(not(parallel_compiler))]
     #[inline(always)]
-    pub fn try_lock(&self) -> Option<LockGuard<T>> {
+    pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
         self.0.try_borrow_mut().ok()
     }
 
     #[cfg(parallel_compiler)]
     #[inline(always)]
-    pub fn lock(&self) -> LockGuard<T> {
+    pub fn lock(&self) -> LockGuard<'_, T> {
         if ERROR_CHECKING {
             self.0.try_lock().expect("lock was already held")
         } else {
@@ -512,7 +512,7 @@
 
     #[cfg(not(parallel_compiler))]
     #[inline(always)]
-    pub fn lock(&self) -> LockGuard<T> {
+    pub fn lock(&self) -> LockGuard<'_, T> {
         self.0.borrow_mut()
     }
 
@@ -522,12 +522,12 @@
     }
 
     #[inline(always)]
-    pub fn borrow(&self) -> LockGuard<T> {
+    pub fn borrow(&self) -> LockGuard<'_, T> {
         self.lock()
     }
 
     #[inline(always)]
-    pub fn borrow_mut(&self) -> LockGuard<T> {
+    pub fn borrow_mut(&self) -> LockGuard<'_, T> {
         self.lock()
     }
 }
@@ -568,13 +568,13 @@
 
     #[cfg(not(parallel_compiler))]
     #[inline(always)]
-    pub fn read(&self) -> ReadGuard<T> {
+    pub fn read(&self) -> ReadGuard<'_, T> {
         self.0.borrow()
     }
 
     #[cfg(parallel_compiler)]
     #[inline(always)]
-    pub fn read(&self) -> ReadGuard<T> {
+    pub fn read(&self) -> ReadGuard<'_, T> {
         if ERROR_CHECKING {
             self.0.try_read().expect("lock was already held")
         } else {
@@ -589,25 +589,25 @@
 
     #[cfg(not(parallel_compiler))]
     #[inline(always)]
-    pub fn try_write(&self) -> Result<WriteGuard<T>, ()> {
+    pub fn try_write(&self) -> Result<WriteGuard<'_, T>, ()> {
         self.0.try_borrow_mut().map_err(|_| ())
     }
 
     #[cfg(parallel_compiler)]
     #[inline(always)]
-    pub fn try_write(&self) -> Result<WriteGuard<T>, ()> {
+    pub fn try_write(&self) -> Result<WriteGuard<'_, T>, ()> {
         self.0.try_write().ok_or(())
     }
 
     #[cfg(not(parallel_compiler))]
     #[inline(always)]
-    pub fn write(&self) -> WriteGuard<T> {
+    pub fn write(&self) -> WriteGuard<'_, T> {
         self.0.borrow_mut()
     }
 
     #[cfg(parallel_compiler)]
     #[inline(always)]
-    pub fn write(&self) -> WriteGuard<T> {
+    pub fn write(&self) -> WriteGuard<'_, T> {
         if ERROR_CHECKING {
             self.0.try_write().expect("lock was already held")
         } else {
@@ -621,12 +621,12 @@
     }
 
     #[inline(always)]
-    pub fn borrow(&self) -> ReadGuard<T> {
+    pub fn borrow(&self) -> ReadGuard<'_, T> {
         self.read()
     }
 
     #[inline(always)]
-    pub fn borrow_mut(&self) -> WriteGuard<T> {
+    pub fn borrow_mut(&self) -> WriteGuard<'_, T> {
         self.write()
     }
 }
diff --git a/src/librustc_data_structures/tiny_list.rs b/src/librustc_data_structures/tiny_list.rs
index d660486..3d74516 100644
--- a/src/librustc_data_structures/tiny_list.rs
+++ b/src/librustc_data_structures/tiny_list.rs
@@ -123,7 +123,7 @@
 mod test {
     use super::*;
     extern crate test;
-    use self::test::Bencher;
+    use test::Bencher;
 
     #[test]
     fn test_contains_and_insert() {
diff --git a/src/librustc_data_structures/transitive_relation.rs b/src/librustc_data_structures/transitive_relation.rs
index 9d675ed..39aed98 100644
--- a/src/librustc_data_structures/transitive_relation.rs
+++ b/src/librustc_data_structures/transitive_relation.rs
@@ -1,8 +1,8 @@
-use bit_set::BitMatrix;
-use fx::FxHashMap;
-use sync::Lock;
+use crate::bit_set::BitMatrix;
+use crate::fx::FxHashMap;
+use crate::stable_hasher::{HashStable, StableHasher, StableHasherResult};
+use crate::sync::Lock;
 use rustc_serialize::{Encodable, Encoder, Decodable, Decoder};
-use stable_hasher::{HashStable, StableHasher, StableHasherResult};
 use std::fmt::Debug;
 use std::hash::Hash;
 use std::mem;
diff --git a/src/librustc_data_structures/vec_linked_list.rs b/src/librustc_data_structures/vec_linked_list.rs
index 3b6984d..c00c707 100644
--- a/src/librustc_data_structures/vec_linked_list.rs
+++ b/src/librustc_data_structures/vec_linked_list.rs
@@ -1,4 +1,4 @@
-use indexed_vec::{Idx, IndexVec};
+use crate::indexed_vec::{Idx, IndexVec};
 
 pub fn iter<Ls>(
     first: Option<Ls::LinkIndex>,
diff --git a/src/librustc_data_structures/work_queue.rs b/src/librustc_data_structures/work_queue.rs
index 0a928de..06418b1 100644
--- a/src/librustc_data_structures/work_queue.rs
+++ b/src/librustc_data_structures/work_queue.rs
@@ -1,5 +1,5 @@
-use bit_set::BitSet;
-use indexed_vec::Idx;
+use crate::bit_set::BitSet;
+use crate::indexed_vec::Idx;
 use std::collections::VecDeque;
 
 /// A work queue is a handy data structure for tracking work left to
diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs
index 18f73f6..f34a7e0 100644
--- a/src/librustc_driver/lib.rs
+++ b/src/librustc_driver/lib.rs
@@ -4,9 +4,7 @@
 //!
 //! This API is completely unstable and subject to change.
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-      html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-      html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 
 #![feature(box_syntax)]
 #![cfg_attr(unix, feature(libc))]
@@ -840,7 +838,15 @@
                 early_error(sopts.error_format, "no input filename given");
             }
             1 => panic!("make_input should have provided valid inputs"),
-            _ => early_error(sopts.error_format, "multiple input filenames provided"),
+            _ =>
+                early_error(
+                    sopts.error_format,
+                    &format!(
+                        "multiple input filenames provided (first two filenames are `{}` and `{}`)",
+                        matches.free[0],
+                        matches.free[1],
+                    ),
+                )
         }
     }
 
diff --git a/src/librustc_errors/emitter.rs b/src/librustc_errors/emitter.rs
index 061d236..2821201 100644
--- a/src/librustc_errors/emitter.rs
+++ b/src/librustc_errors/emitter.rs
@@ -672,8 +672,8 @@
         //   | |  something about `foo`
         //   | something about `fn foo()`
         annotations_position.sort_by(|a, b| {
-            // Decreasing order
-            a.1.len().cmp(&b.1.len()).reverse()
+            // Decreasing order. When `a` and `b` are the same length, prefer `Primary`.
+            (a.1.len(), !a.1.is_primary).cmp(&(b.1.len(), !b.1.is_primary)).reverse()
         });
 
         // Write the underlines.
diff --git a/src/librustc_errors/lib.rs b/src/librustc_errors/lib.rs
index 831415e..ea530fa 100644
--- a/src/librustc_errors/lib.rs
+++ b/src/librustc_errors/lib.rs
@@ -1,6 +1,4 @@
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-      html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-      html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 
 #![feature(custom_attribute)]
 #![allow(unused_attributes)]
diff --git a/src/librustc_incremental/Cargo.toml b/src/librustc_incremental/Cargo.toml
index b8519ee..10b448b 100644
--- a/src/librustc_incremental/Cargo.toml
+++ b/src/librustc_incremental/Cargo.toml
@@ -2,6 +2,7 @@
 authors = ["The Rust Project Developers"]
 name = "rustc_incremental"
 version = "0.0.0"
+edition = "2018"
 
 [lib]
 name = "rustc_incremental"
diff --git a/src/librustc_incremental/assert_dep_graph.rs b/src/librustc_incremental/assert_dep_graph.rs
index 57ab484..b715a32 100644
--- a/src/librustc_incremental/assert_dep_graph.rs
+++ b/src/librustc_incremental/assert_dep_graph.rs
@@ -217,7 +217,7 @@
     }
 }
 
-fn dump_graph(tcx: TyCtxt) {
+fn dump_graph(tcx: TyCtxt<'_, '_, '_>) {
     let path: String = env::var("RUST_DEP_GRAPH").unwrap_or_else(|_| "dep_graph".to_string());
     let query = tcx.dep_graph.query();
 
@@ -261,11 +261,11 @@
 impl<'a, 'tcx, 'q> dot::GraphWalk<'a> for GraphvizDepGraph<'q> {
     type Node = &'q DepNode;
     type Edge = (&'q DepNode, &'q DepNode);
-    fn nodes(&self) -> dot::Nodes<&'q DepNode> {
+    fn nodes(&self) -> dot::Nodes<'_, &'q DepNode> {
         let nodes: Vec<_> = self.0.iter().cloned().collect();
         nodes.into()
     }
-    fn edges(&self) -> dot::Edges<(&'q DepNode, &'q DepNode)> {
+    fn edges(&self) -> dot::Edges<'_, (&'q DepNode, &'q DepNode)> {
         self.1[..].into()
     }
     fn source(&self, edge: &(&'q DepNode, &'q DepNode)) -> &'q DepNode {
@@ -279,10 +279,10 @@
 impl<'a, 'tcx, 'q> dot::Labeller<'a> for GraphvizDepGraph<'q> {
     type Node = &'q DepNode;
     type Edge = (&'q DepNode, &'q DepNode);
-    fn graph_id(&self) -> dot::Id {
+    fn graph_id(&self) -> dot::Id<'_> {
         dot::Id::new("DependencyGraph").unwrap()
     }
-    fn node_id(&self, n: &&'q DepNode) -> dot::Id {
+    fn node_id(&self, n: &&'q DepNode) -> dot::Id<'_> {
         let s: String =
             format!("{:?}", n).chars()
                               .map(|c| if c == '_' || c.is_alphanumeric() { c } else { '_' })
@@ -290,7 +290,7 @@
         debug!("n={:?} s={:?}", n, s);
         dot::Id::new(s).unwrap()
     }
-    fn node_label(&self, n: &&'q DepNode) -> dot::LabelText {
+    fn node_label(&self, n: &&'q DepNode) -> dot::LabelText<'_> {
         dot::LabelText::label(format!("{:?}", n))
     }
 }
diff --git a/src/librustc_incremental/lib.rs b/src/librustc_incremental/lib.rs
index ae2e6e0..346ddaa 100644
--- a/src/librustc_incremental/lib.rs
+++ b/src/librustc_incremental/lib.rs
@@ -1,24 +1,19 @@
 //! Support for serializing the dep-graph and reloading it.
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-      html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-      html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 
 #![feature(nll)]
 #![feature(specialization)]
 
 #![recursion_limit="256"]
 
-extern crate graphviz;
+#![deny(rust_2018_idioms)]
+
 #[macro_use] extern crate rustc;
-extern crate rustc_data_structures;
-extern crate serialize as rustc_serialize;
-extern crate rand;
-extern crate rustc_fs_util;
+#[allow(unused_extern_crates)]
+extern crate serialize as rustc_serialize; // used by deriving
 
 #[macro_use] extern crate log;
-extern crate syntax;
-extern crate syntax_pos;
 
 mod assert_dep_graph;
 pub mod assert_module_sources;
diff --git a/src/librustc_incremental/persist/dirty_clean.rs b/src/librustc_incremental/persist/dirty_clean.rs
index 3ff4d2e..51f3bcd 100644
--- a/src/librustc_incremental/persist/dirty_clean.rs
+++ b/src/librustc_incremental/persist/dirty_clean.rs
@@ -67,11 +67,11 @@
     label_strs::ImplTraitRef,
 ];
 
-/// DepNodes for MirValidated/Optimized, which is relevant in "executable"
+/// DepNodes for MirBuilt/Optimized, which is relevant in "executable"
 /// code, i.e., functions+methods
 const BASE_MIR: &[&str] = &[
     label_strs::MirOptimized,
-    label_strs::MirValidated,
+    label_strs::MirBuilt,
 ];
 
 /// Struct, Enum and Union DepNodes
@@ -538,7 +538,7 @@
 ///
 /// Also make sure that the `label` and `except` fields do not
 /// both exist.
-fn check_config(tcx: TyCtxt, attr: &Attribute) -> bool {
+fn check_config(tcx: TyCtxt<'_, '_, '_>, attr: &Attribute) -> bool {
     debug!("check_config(attr={:?})", attr);
     let config = &tcx.sess.parse_sess.config;
     debug!("check_config: config={:?}", config);
@@ -573,7 +573,7 @@
     }
 }
 
-fn expect_associated_value(tcx: TyCtxt, item: &NestedMetaItem) -> ast::Name {
+fn expect_associated_value(tcx: TyCtxt<'_, '_, '_>, item: &NestedMetaItem) -> ast::Name {
     if let Some(value) = item.value_str() {
         value
     } else {
diff --git a/src/librustc_incremental/persist/load.rs b/src/librustc_incremental/persist/load.rs
index f330de7..ecf8bc4 100644
--- a/src/librustc_incremental/persist/load.rs
+++ b/src/librustc_incremental/persist/load.rs
@@ -9,7 +9,6 @@
 use rustc_serialize::Decodable as RustcDecodable;
 use rustc_serialize::opaque::Decoder;
 use std::path::Path;
-use std;
 
 use super::data::*;
 use super::fs::*;
diff --git a/src/librustc_incremental/persist/mod.rs b/src/librustc_incremental/persist/mod.rs
index bd59f24..3aad4f5 100644
--- a/src/librustc_incremental/persist/mod.rs
+++ b/src/librustc_incremental/persist/mod.rs
@@ -10,16 +10,16 @@
 mod work_product;
 mod file_format;
 
-pub use self::fs::finalize_session_directory;
-pub use self::fs::garbage_collect_session_directories;
-pub use self::fs::in_incr_comp_dir;
-pub use self::fs::in_incr_comp_dir_sess;
-pub use self::fs::prepare_session_directory;
-pub use self::load::dep_graph_tcx_init;
-pub use self::load::load_dep_graph;
-pub use self::load::load_query_result_cache;
-pub use self::load::LoadResult;
-pub use self::save::save_dep_graph;
-pub use self::save::save_work_product_index;
-pub use self::work_product::copy_cgu_workproducts_to_incr_comp_cache_dir;
-pub use self::work_product::delete_workproduct_files;
+pub use fs::finalize_session_directory;
+pub use fs::garbage_collect_session_directories;
+pub use fs::in_incr_comp_dir;
+pub use fs::in_incr_comp_dir_sess;
+pub use fs::prepare_session_directory;
+pub use load::dep_graph_tcx_init;
+pub use load::load_dep_graph;
+pub use load::load_query_result_cache;
+pub use load::LoadResult;
+pub use save::save_dep_graph;
+pub use save::save_work_product_index;
+pub use work_product::copy_cgu_workproducts_to_incr_comp_cache_dir;
+pub use work_product::delete_workproduct_files;
diff --git a/src/librustc_incremental/persist/save.rs b/src/librustc_incremental/persist/save.rs
index 6a7553b..34fe2f1 100644
--- a/src/librustc_incremental/persist/save.rs
+++ b/src/librustc_incremental/persist/save.rs
@@ -129,7 +129,7 @@
     }
 }
 
-fn encode_dep_graph(tcx: TyCtxt,
+fn encode_dep_graph(tcx: TyCtxt<'_, '_, '_>,
                     encoder: &mut Encoder) {
     // First encode the commandline arguments hash
     tcx.sess.opts.dep_tracking_hash().encode(encoder).unwrap();
@@ -234,7 +234,7 @@
     serialized_products.encode(encoder).unwrap();
 }
 
-fn encode_query_cache(tcx: TyCtxt,
+fn encode_query_cache(tcx: TyCtxt<'_, '_, '_>,
                       encoder: &mut Encoder) {
     time(tcx.sess, "serialize query result cache", || {
         tcx.serialize_query_result_cache(encoder).unwrap();
diff --git a/src/librustc_incremental/persist/work_product.rs b/src/librustc_incremental/persist/work_product.rs
index 535f693..3495b27 100644
--- a/src/librustc_incremental/persist/work_product.rs
+++ b/src/librustc_incremental/persist/work_product.rs
@@ -1,6 +1,6 @@
 //! This module contains files for saving intermediate work-products.
 
-use persist::fs::*;
+use crate::persist::fs::*;
 use rustc::dep_graph::{WorkProduct, WorkProductId, WorkProductFileKind};
 use rustc::session::Session;
 use rustc_fs_util::link_or_copy;
diff --git a/src/librustc_lint/Cargo.toml b/src/librustc_lint/Cargo.toml
index 7fb7a06..82f7118 100644
--- a/src/librustc_lint/Cargo.toml
+++ b/src/librustc_lint/Cargo.toml
@@ -2,6 +2,7 @@
 authors = ["The Rust Project Developers"]
 name = "rustc_lint"
 version = "0.0.0"
+edition = "2018"
 
 [lib]
 name = "rustc_lint"
diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs
index 7c25d8d..cbcc7f3 100644
--- a/src/librustc_lint/builtin.rs
+++ b/src/librustc_lint/builtin.rs
@@ -21,6 +21,7 @@
 use rustc::hir::def::Def;
 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
 use rustc::ty::{self, Ty};
+use rustc::{lint, util};
 use hir::Node;
 use util::nodemap::NodeSet;
 use lint::{LateContext, LintContext, LintArray};
@@ -42,10 +43,13 @@
 use syntax::errors::{Applicability, DiagnosticBuilder};
 use syntax::print::pprust::expr_to_string;
 use syntax::visit::FnKind;
+use syntax::struct_span_err;
 
 use rustc::hir::{self, GenericParamKind, PatKind};
 
-use nonstandard_style::{MethodLateContext, method_context};
+use crate::nonstandard_style::{MethodLateContext, method_context};
+
+use log::debug;
 
 // hardwired lints from librustc
 pub use lint::builtin::*;
@@ -70,7 +74,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for WhileTrue {
-    fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
+    fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
         if let hir::ExprKind::While(ref cond, ..) = e.node {
             if let hir::ExprKind::Lit(ref lit) = cond.node {
                 if let ast::LitKind::Bool(true) = lit.node {
@@ -102,7 +106,7 @@
 pub struct BoxPointers;
 
 impl BoxPointers {
-    fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext, span: Span, ty: Ty) {
+    fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext<'_, '_>, span: Span, ty: Ty<'_>) {
         for leaf_ty in ty.walk() {
             if leaf_ty.is_box() {
                 let m = format!("type uses owned (Box type) pointers: {}", ty);
@@ -123,7 +127,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
-    fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
+    fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
         match it.node {
             hir::ItemKind::Fn(..) |
             hir::ItemKind::Ty(..) |
@@ -150,7 +154,7 @@
         }
     }
 
-    fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
+    fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
         let ty = cx.tables.node_id_to_type(e.hir_id);
         self.check_heap_type(cx, e.span, ty);
     }
@@ -176,7 +180,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
-    fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
+    fn check_pat(&mut self, cx: &LateContext<'_, '_>, pat: &hir::Pat) {
         if let PatKind::Struct(ref qpath, ref field_pats, _) = pat.node {
             let variant = cx.tables.pat_ty(pat).ty_adt_def()
                                    .expect("struct pattern type is not an ADT")
@@ -233,7 +237,7 @@
 }
 
 impl UnsafeCode {
-    fn report_unsafe(&self, cx: &EarlyContext, span: Span, desc: &'static str) {
+    fn report_unsafe(&self, cx: &EarlyContext<'_>, span: Span, desc: &'static str) {
         // This comes from a macro that has #[allow_internal_unsafe].
         if span.allows_unsafe() {
             return;
@@ -244,7 +248,7 @@
 }
 
 impl EarlyLintPass for UnsafeCode {
-    fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) {
+    fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
         if attr.check_name("allow_internal_unsafe") {
             self.report_unsafe(cx, attr.span, "`allow_internal_unsafe` allows defining \
                                                macros using unsafe without triggering \
@@ -252,7 +256,7 @@
         }
     }
 
-    fn check_expr(&mut self, cx: &EarlyContext, e: &ast::Expr) {
+    fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
         if let ast::ExprKind::Block(ref blk, _) = e.node {
             // Don't warn about generated blocks, that'll just pollute the output.
             if blk.rules == ast::BlockCheckMode::Unsafe(ast::UserProvided) {
@@ -261,7 +265,7 @@
         }
     }
 
-    fn check_item(&mut self, cx: &EarlyContext, it: &ast::Item) {
+    fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
         match it.node {
             ast::ItemKind::Trait(_, ast::Unsafety::Unsafe, ..) => {
                 self.report_unsafe(cx, it.span, "declaration of an `unsafe` trait")
@@ -276,8 +280,8 @@
     }
 
     fn check_fn(&mut self,
-                cx: &EarlyContext,
-                fk: FnKind,
+                cx: &EarlyContext<'_>,
+                fk: FnKind<'_>,
                 _: &ast::FnDecl,
                 span: Span,
                 _: ast::NodeId) {
@@ -296,7 +300,7 @@
         }
     }
 
-    fn check_trait_item(&mut self, cx: &EarlyContext, item: &ast::TraitItem) {
+    fn check_trait_item(&mut self, cx: &EarlyContext<'_>, item: &ast::TraitItem) {
         if let ast::TraitItemKind::Method(ref sig, None) = item.node {
             if sig.header.unsafety == ast::Unsafety::Unsafe {
                 self.report_unsafe(cx, item.span, "declaration of an `unsafe` method")
@@ -354,7 +358,7 @@
     }
 
     fn check_missing_docs_attrs(&self,
-                                cx: &LateContext,
+                                cx: &LateContext<'_, '_>,
                                 id: Option<ast::NodeId>,
                                 attrs: &[ast::Attribute],
                                 sp: Span,
@@ -399,7 +403,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
-    fn enter_lint_attrs(&mut self, _: &LateContext, attrs: &[ast::Attribute]) {
+    fn enter_lint_attrs(&mut self, _: &LateContext<'_, '_>, attrs: &[ast::Attribute]) {
         let doc_hidden = self.doc_hidden() ||
                          attrs.iter().any(|attr| {
             attr.check_name("doc") &&
@@ -411,11 +415,11 @@
         self.doc_hidden_stack.push(doc_hidden);
     }
 
-    fn exit_lint_attrs(&mut self, _: &LateContext, _attrs: &[ast::Attribute]) {
+    fn exit_lint_attrs(&mut self, _: &LateContext<'_, '_>, _attrs: &[ast::Attribute]) {
         self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
     }
 
-    fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) {
+    fn check_crate(&mut self, cx: &LateContext<'_, '_>, krate: &hir::Crate) {
         self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
 
         for macro_def in &krate.exported_macros {
@@ -428,7 +432,7 @@
         }
     }
 
-    fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
+    fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
         let desc = match it.node {
             hir::ItemKind::Fn(..) => "a function",
             hir::ItemKind::Mod(..) => "a module",
@@ -473,7 +477,7 @@
         self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
     }
 
-    fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
+    fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, trait_item: &hir::TraitItem) {
         if self.private_traits.contains(&trait_item.id) {
             return;
         }
@@ -491,7 +495,7 @@
                                       desc);
     }
 
-    fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
+    fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem) {
         // If the method is an impl for a trait, don't doc.
         if method_context(cx, impl_item.id) == MethodLateContext::TraitImpl {
             return;
@@ -510,7 +514,7 @@
                                       desc);
     }
 
-    fn check_struct_field(&mut self, cx: &LateContext, sf: &hir::StructField) {
+    fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, sf: &hir::StructField) {
         if !sf.is_positional() {
             self.check_missing_docs_attrs(cx,
                                           Some(sf.id),
@@ -520,7 +524,7 @@
         }
     }
 
-    fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
+    fn check_variant(&mut self, cx: &LateContext<'_, '_>, v: &hir::Variant, _: &hir::Generics) {
         self.check_missing_docs_attrs(cx,
                                       Some(v.node.data.id()),
                                       &v.node.attrs,
@@ -549,7 +553,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
-    fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
+    fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
         if !cx.access_levels.is_reachable(item.id) {
             return;
         }
@@ -620,7 +624,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
-    fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
+    fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
         if !cx.access_levels.is_reachable(item.id) {
             return;
         }
@@ -681,7 +685,7 @@
 }
 
 impl EarlyLintPass for AnonymousParameters {
-    fn check_trait_item(&mut self, cx: &EarlyContext, it: &ast::TraitItem) {
+    fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::TraitItem) {
         match it.node {
             ast::TraitItemKind::Method(ref sig, _) => {
                 for arg in sig.decl.inputs.iter() {
@@ -749,7 +753,7 @@
 }
 
 impl EarlyLintPass for DeprecatedAttr {
-    fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) {
+    fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) {
         for &&(n, _, _, ref g) in &self.depr_attrs {
             if attr.name() == n {
                 if let &AttributeGate::Gated(Stability::Deprecated(link, suggestion),
@@ -804,15 +808,15 @@
 }
 
 impl EarlyLintPass for UnusedDocComment {
-    fn check_local(&mut self, cx: &EarlyContext, decl: &ast::Local) {
+    fn check_local(&mut self, cx: &EarlyContext<'_>, decl: &ast::Local) {
         self.warn_if_doc(decl.attrs.iter(), cx);
     }
 
-    fn check_arm(&mut self, cx: &EarlyContext, arm: &ast::Arm) {
+    fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
         self.warn_if_doc(arm.attrs.iter(), cx);
     }
 
-    fn check_expr(&mut self, cx: &EarlyContext, expr: &ast::Expr) {
+    fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
         self.warn_if_doc(expr.attrs.iter(), cx);
     }
 }
@@ -837,7 +841,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
-    fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
+    fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
         if cx.tcx.plugin_registrar_fn(LOCAL_CRATE).is_some() {
             // We're compiling a plugin; it's fine to link other plugins.
             return;
@@ -894,7 +898,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
-    fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
+    fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
         match it.node {
             hir::ItemKind::Fn(.., ref generics, _) => {
                 if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, "no_mangle") {
@@ -968,7 +972,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
-    fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
+    fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &hir::Expr) {
         use rustc_target::spec::abi::Abi::RustIntrinsic;
 
         let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
@@ -1004,7 +1008,7 @@
             None
         }
 
-        fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
+        fn def_id_is_transmute(cx: &LateContext<'_, '_>, def_id: DefId) -> bool {
             cx.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
             cx.tcx.item_name(def_id) == "transmute"
         }
@@ -1032,7 +1036,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
-    fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
+    fn check_attribute(&mut self, ctx: &LateContext<'_, '_>, attr: &ast::Attribute) {
         if attr.check_name("feature") {
             if let Some(items) = attr.meta_item_list() {
                 for item in items {
@@ -1063,7 +1067,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
-    fn check_item(&mut self, ctx: &LateContext, item: &hir::Item) {
+    fn check_item(&mut self, ctx: &LateContext<'_, '_>, item: &hir::Item) {
         if let hir::ItemKind::Union(ref vdata, _) = item.node {
             for field in vdata.fields() {
                 let field_ty = ctx.tcx.type_of(ctx.tcx.hir().local_def_id(field.id));
@@ -1099,7 +1103,7 @@
 }
 
 impl UnreachablePub {
-    fn perform_lint(&self, cx: &LateContext, what: &str, id: ast::NodeId,
+    fn perform_lint(&self, cx: &LateContext<'_, '_>, what: &str, id: ast::NodeId,
                     vis: &hir::Visibility, span: Span, exportable: bool) {
         let mut applicability = Applicability::MachineApplicable;
         match vis.node {
@@ -1134,20 +1138,20 @@
 
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnreachablePub {
-    fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
+    fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
         self.perform_lint(cx, "item", item.id, &item.vis, item.span, true);
     }
 
-    fn check_foreign_item(&mut self, cx: &LateContext, foreign_item: &hir::ForeignItem) {
+    fn check_foreign_item(&mut self, cx: &LateContext<'_, '_>, foreign_item: &hir::ForeignItem) {
         self.perform_lint(cx, "item", foreign_item.id, &foreign_item.vis,
                           foreign_item.span, true);
     }
 
-    fn check_struct_field(&mut self, cx: &LateContext, field: &hir::StructField) {
+    fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, field: &hir::StructField) {
         self.perform_lint(cx, "field", field.id, &field.vis, field.span, false);
     }
 
-    fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
+    fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, impl_item: &hir::ImplItem) {
         self.perform_lint(cx, "item", impl_item.id, &impl_item.vis, impl_item.span, false);
     }
 }
@@ -1193,7 +1197,7 @@
         }
     }
 
-    fn suggest_changing_assoc_types(ty: &hir::Ty, err: &mut DiagnosticBuilder) {
+    fn suggest_changing_assoc_types(ty: &hir::Ty, err: &mut DiagnosticBuilder<'_>) {
         // Access to associates types should use `<T as Bound>::Assoc`, which does not need a
         // bound.  Let's see if this type does that.
 
@@ -1225,7 +1229,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeAliasBounds {
-    fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
+    fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::Item) {
         let (ty, type_alias_generics) = match item.node {
             hir::ItemKind::Ty(ref ty, ref generics) => (&*ty, generics),
             _ => return,
@@ -1281,7 +1285,7 @@
         lint_array!()
     }
 }
-fn check_const(cx: &LateContext, body_id: hir::BodyId) {
+fn check_const(cx: &LateContext<'_, '_>, body_id: hir::BodyId) {
     let def_id = cx.tcx.hir().body_owner_def_id(body_id);
     let is_static = cx.tcx.is_static(def_id).is_some();
     let param_env = if is_static {
@@ -1299,7 +1303,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedBrokenConst {
-    fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
+    fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
         match it.node {
             hir::ItemKind::Const(_, body_id) => {
                 check_const(cx, body_id);
@@ -1429,7 +1433,7 @@
 }
 
 impl EarlyLintPass for EllipsisInclusiveRangePatterns {
-    fn check_pat(&mut self, cx: &EarlyContext, pat: &ast::Pat, visit_subpats: &mut bool) {
+    fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat, visit_subpats: &mut bool) {
         use self::ast::{PatKind, RangeEnd, RangeSyntax::DotDotDot};
 
         /// If `pat` is a `...` pattern, return the start and end of the range, as well as the span
@@ -1507,7 +1511,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnnameableTestItems {
-    fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
+    fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
         if self.items_nameable {
             if let hir::ItemKind::Mod(..) = it.node {}
             else {
@@ -1526,7 +1530,7 @@
         }
     }
 
-    fn check_item_post(&mut self, _cx: &LateContext, it: &hir::Item) {
+    fn check_item_post(&mut self, _cx: &LateContext<'_, '_>, it: &hir::Item) {
         if !self.items_nameable && self.boundary == it.id {
             self.items_nameable = true;
         }
@@ -1554,7 +1558,7 @@
 }
 
 impl KeywordIdents {
-    fn check_tokens(&mut self, cx: &EarlyContext, tokens: TokenStream) {
+    fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: TokenStream) {
         for tt in tokens.into_trees() {
             match tt {
                 TokenTree::Token(span, tok) => match tok.ident() {
@@ -1576,13 +1580,13 @@
 }
 
 impl EarlyLintPass for KeywordIdents {
-    fn check_mac_def(&mut self, cx: &EarlyContext, mac_def: &ast::MacroDef, _id: ast::NodeId) {
+    fn check_mac_def(&mut self, cx: &EarlyContext<'_>, mac_def: &ast::MacroDef, _id: ast::NodeId) {
         self.check_tokens(cx, mac_def.stream());
     }
-    fn check_mac(&mut self, cx: &EarlyContext, mac: &ast::Mac) {
+    fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::Mac) {
         self.check_tokens(cx, mac.node.tts.clone().into());
     }
-    fn check_ident(&mut self, cx: &EarlyContext, ident: ast::Ident) {
+    fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: ast::Ident) {
         let ident_str = &ident.as_str()[..];
         let cur_edition = cx.sess.edition();
         let is_raw_ident = |ident: ast::Ident| {
@@ -1665,7 +1669,7 @@
 impl ExplicitOutlivesRequirements {
     fn collect_outlives_bound_spans(
         &self,
-        cx: &LateContext,
+        cx: &LateContext<'_, '_>,
         item_def_id: DefId,
         param_name: &str,
         bounds: &hir::GenericBounds,
diff --git a/src/librustc_lint/diagnostics.rs b/src/librustc_lint/diagnostics.rs
index 9a608e4..3165673 100644
--- a/src/librustc_lint/diagnostics.rs
+++ b/src/librustc_lint/diagnostics.rs
@@ -1,3 +1,5 @@
+use syntax::{register_diagnostic, register_diagnostics};
+
 register_diagnostics! {
     E0721, // `await` keyword
 }
diff --git a/src/librustc_lint/lib.rs b/src/librustc_lint/lib.rs
index 6607951..5c243e1 100644
--- a/src/librustc_lint/lib.rs
+++ b/src/librustc_lint/lib.rs
@@ -9,9 +9,7 @@
 //!
 //! This API is completely unstable and subject to change.
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-      html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-      html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 
 #![cfg_attr(test, feature(test))]
 #![feature(box_patterns)]
@@ -21,15 +19,10 @@
 
 #![recursion_limit="256"]
 
-#[macro_use]
-extern crate syntax;
+#![deny(rust_2018_idioms)]
+
 #[macro_use]
 extern crate rustc;
-#[macro_use]
-extern crate log;
-extern crate rustc_target;
-extern crate syntax_pos;
-extern crate rustc_data_structures;
 
 mod diagnostics;
 mod nonstandard_style;
@@ -51,7 +44,6 @@
     parser::ILL_FORMED_ATTRIBUTE_INPUT,
 };
 use rustc::session;
-use rustc::util;
 use rustc::hir;
 
 use syntax::ast;
@@ -356,6 +348,11 @@
             reference: "issue #57644 <https://github.com/rust-lang/rust/issues/57644>",
             edition: None,
         },
+        FutureIncompatibleInfo {
+            id: LintId::of(DUPLICATE_MATCHER_BINDING_NAME),
+            reference: "issue #57593 <https://github.com/rust-lang/rust/issues/57593>",
+            edition: None,
+        },
         ]);
 
     // Register renamed and removed lints.
diff --git a/src/librustc_lint/nonstandard_style.rs b/src/librustc_lint/nonstandard_style.rs
index ae2ed28..2dbafc7 100644
--- a/src/librustc_lint/nonstandard_style.rs
+++ b/src/librustc_lint/nonstandard_style.rs
@@ -1,6 +1,7 @@
 use rustc::hir::{self, GenericParamKind, PatKind};
 use rustc::hir::def::Def;
 use rustc::hir::intravisit::FnKind;
+use rustc::lint;
 use rustc::ty;
 use rustc_target::spec::abi::Abi;
 use lint::{EarlyContext, LateContext, LintContext, LintArray};
@@ -17,7 +18,7 @@
     PlainImpl,
 }
 
-pub fn method_context(cx: &LateContext, id: ast::NodeId) -> MethodLateContext {
+pub fn method_context(cx: &LateContext<'_, '_>, id: ast::NodeId) -> MethodLateContext {
     let def_id = cx.tcx.hir().local_def_id(id);
     let item = cx.tcx.associated_item(def_id);
     match item.container {
@@ -41,7 +42,7 @@
 pub struct NonCamelCaseTypes;
 
 impl NonCamelCaseTypes {
-    fn check_case(&self, cx: &EarlyContext, sort: &str, ident: &Ident) {
+    fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) {
         fn char_has_case(c: char) -> bool {
             c.is_lowercase() || c.is_uppercase()
         }
@@ -115,7 +116,7 @@
 }
 
 impl EarlyLintPass for NonCamelCaseTypes {
-    fn check_item(&mut self, cx: &EarlyContext, it: &ast::Item) {
+    fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
         let has_repr_c = it.attrs
             .iter()
             .any(|attr| {
@@ -138,11 +139,11 @@
         }
     }
 
-    fn check_variant(&mut self, cx: &EarlyContext, v: &ast::Variant, _: &ast::Generics) {
+    fn check_variant(&mut self, cx: &EarlyContext<'_>, v: &ast::Variant, _: &ast::Generics) {
         self.check_case(cx, "variant", &v.node.ident);
     }
 
-    fn check_generic_param(&mut self, cx: &EarlyContext, param: &ast::GenericParam) {
+    fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
         if let ast::GenericParamKind::Type { .. } = param.kind {
             self.check_case(cx, "type parameter", &param.ident);
         }
@@ -190,7 +191,7 @@
     }
 
     /// Checks if a given identifier is snake case, and reports a diagnostic if not.
-    fn check_snake_case(&self, cx: &LateContext, sort: &str, ident: &Ident) {
+    fn check_snake_case(&self, cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
         fn is_snake_case(ident: &str) -> bool {
             if ident.is_empty() {
                 return true;
@@ -249,7 +250,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase {
-    fn check_crate(&mut self, cx: &LateContext, cr: &hir::Crate) {
+    fn check_crate(&mut self, cx: &LateContext<'_, '_>, cr: &hir::Crate) {
         let crate_ident = if let Some(name) = &cx.tcx.sess.opts.crate_name {
             Some(Ident::from_str(name))
         } else {
@@ -286,7 +287,7 @@
         }
     }
 
-    fn check_generic_param(&mut self, cx: &LateContext, param: &hir::GenericParam) {
+    fn check_generic_param(&mut self, cx: &LateContext<'_, '_>, param: &hir::GenericParam) {
         if let GenericParamKind::Lifetime { .. } = param.kind {
             self.check_snake_case(cx, "lifetime", &param.name.ident());
         }
@@ -294,8 +295,8 @@
 
     fn check_fn(
         &mut self,
-        cx: &LateContext,
-        fk: FnKind,
+        cx: &LateContext<'_, '_>,
+        fk: FnKind<'_>,
         _: &hir::FnDecl,
         _: &hir::Body,
         _: Span,
@@ -324,13 +325,13 @@
         }
     }
 
-    fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
+    fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
         if let hir::ItemKind::Mod(_) = it.node {
             self.check_snake_case(cx, "module", &it.ident);
         }
     }
 
-    fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
+    fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::TraitItem) {
         if let hir::TraitItemKind::Method(_, hir::TraitMethod::Required(pnames)) = &item.node {
             self.check_snake_case(cx, "trait method", &item.ident);
             for param_name in pnames {
@@ -339,7 +340,7 @@
         }
     }
 
-    fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
+    fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat) {
         if let &PatKind::Binding(_, _, _, ident, _) = &p.node {
             self.check_snake_case(cx, "variable", &ident);
         }
@@ -347,7 +348,7 @@
 
     fn check_struct_def(
         &mut self,
-        cx: &LateContext,
+        cx: &LateContext<'_, '_>,
         s: &hir::VariantData,
         _: ast::Name,
         _: &hir::Generics,
@@ -369,7 +370,7 @@
 pub struct NonUpperCaseGlobals;
 
 impl NonUpperCaseGlobals {
-    fn check_upper_case(cx: &LateContext, sort: &str, ident: &Ident) {
+    fn check_upper_case(cx: &LateContext<'_, '_>, sort: &str, ident: &Ident) {
         let name = &ident.name.as_str();
 
         if name.chars().any(|c| c.is_lowercase()) {
@@ -399,7 +400,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonUpperCaseGlobals {
-    fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
+    fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
         match it.node {
             hir::ItemKind::Static(..) if !attr::contains_name(&it.attrs, "no_mangle") => {
                 NonUpperCaseGlobals::check_upper_case(cx, "static variable", &it.ident);
@@ -411,19 +412,19 @@
         }
     }
 
-    fn check_trait_item(&mut self, cx: &LateContext, ti: &hir::TraitItem) {
+    fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, ti: &hir::TraitItem) {
         if let hir::TraitItemKind::Const(..) = ti.node {
             NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ti.ident);
         }
     }
 
-    fn check_impl_item(&mut self, cx: &LateContext, ii: &hir::ImplItem) {
+    fn check_impl_item(&mut self, cx: &LateContext<'_, '_>, ii: &hir::ImplItem) {
         if let hir::ImplItemKind::Const(..) = ii.node {
             NonUpperCaseGlobals::check_upper_case(cx, "associated constant", &ii.ident);
         }
     }
 
-    fn check_pat(&mut self, cx: &LateContext, p: &hir::Pat) {
+    fn check_pat(&mut self, cx: &LateContext<'_, '_>, p: &hir::Pat) {
         // Lint for constants that look like binding identifiers (#7526)
         if let PatKind::Path(hir::QPath::Resolved(None, ref path)) = p.node {
             if let Def::Const(..) = path.def {
diff --git a/src/librustc_lint/types.rs b/src/librustc_lint/types.rs
index 4abd55b..f6b7ccf 100644
--- a/src/librustc_lint/types.rs
+++ b/src/librustc_lint/types.rs
@@ -4,6 +4,7 @@
 use rustc::ty::subst::Substs;
 use rustc::ty::{self, AdtKind, ParamEnv, Ty, TyCtxt};
 use rustc::ty::layout::{self, IntegerExt, LayoutOf, VariantIdx};
+use rustc::{lint, util};
 use rustc_data_structures::indexed_vec::Idx;
 use util::nodemap::FxHashSet;
 use lint::{LateContext, LintContext, LintArray};
@@ -23,6 +24,8 @@
 
 use rustc::mir::interpret::{sign_extend, truncate};
 
+use log::debug;
+
 declare_lint! {
     UNUSED_COMPARISONS,
     Warn,
@@ -241,7 +244,7 @@
             }
         }
 
-        fn check_limits(cx: &LateContext,
+        fn check_limits(cx: &LateContext<'_, '_>,
                         binop: hir::BinOp,
                         l: &hir::Expr,
                         r: &hir::Expr)
@@ -298,7 +301,7 @@
             }
         }
 
-        fn get_bin_hex_repr(cx: &LateContext, lit: &ast::Lit) -> Option<String> {
+        fn get_bin_hex_repr(cx: &LateContext<'_, '_>, lit: &ast::Lit) -> Option<String> {
             let src = cx.sess().source_map().span_to_snippet(lit.span).ok()?;
             let firstch = src.chars().next()?;
 
@@ -320,7 +323,7 @@
         //
         // No suggestion for: `isize`, `usize`.
         fn get_type_suggestion<'a>(
-            t: &ty::TyKind,
+            t: &ty::TyKind<'_>,
             val: u128,
             negative: bool,
         ) -> Option<String> {
@@ -364,9 +367,9 @@
         }
 
         fn report_bin_hex_error(
-            cx: &LateContext,
+            cx: &LateContext<'_, '_>,
             expr: &hir::Expr,
-            ty: ty::TyKind,
+            ty: ty::TyKind<'_>,
             repr_str: String,
             val: u128,
             negative: bool,
@@ -481,7 +484,7 @@
     fn check_type_for_ffi(&self,
                           cache: &mut FxHashSet<Ty<'tcx>>,
                           ty: Ty<'tcx>) -> FfiResult<'tcx> {
-        use self::FfiResult::*;
+        use FfiResult::*;
 
         let cx = self.cx.tcx;
 
@@ -799,7 +802,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImproperCTypes {
-    fn check_foreign_item(&mut self, cx: &LateContext, it: &hir::ForeignItem) {
+    fn check_foreign_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::ForeignItem) {
         let mut vis = ImproperCTypesVisitor { cx };
         let abi = cx.tcx.hir().get_foreign_abi(it.id);
         if abi != Abi::RustIntrinsic && abi != Abi::PlatformIntrinsic {
@@ -829,7 +832,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VariantSizeDifferences {
-    fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
+    fn check_item(&mut self, cx: &LateContext<'_, '_>, it: &hir::Item) {
         if let hir::ItemKind::Enum(ref enum_definition, _) = it.node {
             let item_def_id = cx.tcx.hir().local_def_id(it.id);
             let t = cx.tcx.type_of(item_def_id);
diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs
index acf5da1..407e6842 100644
--- a/src/librustc_lint/unused.rs
+++ b/src/librustc_lint/unused.rs
@@ -1,5 +1,6 @@
 use rustc::hir::def::Def;
 use rustc::hir::def_id::DefId;
+use rustc::lint;
 use rustc::ty;
 use rustc::ty::adjustment;
 use lint::{LateContext, EarlyContext, LintContext, LintArray};
@@ -16,6 +17,8 @@
 
 use rustc::hir;
 
+use log::debug;
+
 declare_lint! {
     pub UNUSED_MUST_USE,
     Warn,
@@ -43,7 +46,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults {
-    fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
+    fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt) {
         let expr = match s.node {
             hir::StmtKind::Semi(ref expr) => &**expr,
             _ => return,
@@ -168,7 +171,7 @@
         }
 
         fn check_must_use(
-            cx: &LateContext,
+            cx: &LateContext<'_, '_>,
             def_id: DefId,
             sp: Span,
             descr_pre_path: &str,
@@ -212,7 +215,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathStatements {
-    fn check_stmt(&mut self, cx: &LateContext, s: &hir::Stmt) {
+    fn check_stmt(&mut self, cx: &LateContext<'_, '_>, s: &hir::Stmt) {
         if let hir::StmtKind::Semi(ref expr) = s.node {
             if let hir::ExprKind::Path(_) = expr.node {
                 cx.span_lint(PATH_STATEMENTS, s.span, "path statement with no effect");
@@ -241,7 +244,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAttributes {
-    fn check_attribute(&mut self, cx: &LateContext, attr: &ast::Attribute) {
+    fn check_attribute(&mut self, cx: &LateContext<'_, '_>, attr: &ast::Attribute) {
         debug!("checking attribute: {:?}", attr);
         // Note that check_name() marks the attribute as used if it matches.
         for &(name, ty, ..) in BUILTIN_ATTRIBUTES {
@@ -303,7 +306,7 @@
 
 impl UnusedParens {
     fn check_unused_parens_expr(&self,
-                                cx: &EarlyContext,
+                                cx: &EarlyContext<'_>,
                                 value: &ast::Expr,
                                 msg: &str,
                                 followed_by_block: bool) {
@@ -325,7 +328,7 @@
     }
 
     fn check_unused_parens_pat(&self,
-                                cx: &EarlyContext,
+                                cx: &EarlyContext<'_>,
                                 value: &ast::Pat,
                                 msg: &str) {
         if let ast::PatKind::Paren(_) = value.node {
@@ -339,7 +342,7 @@
         }
     }
 
-    fn remove_outer_parens(cx: &EarlyContext, span: Span, pattern: &str, msg: &str) {
+    fn remove_outer_parens(cx: &EarlyContext<'_>, span: Span, pattern: &str, msg: &str) {
         let span_msg = format!("unnecessary parentheses around {}", msg);
         let mut err = cx.struct_span_lint(UNUSED_PARENS, span, &span_msg);
         let mut ate_left_paren = false;
@@ -387,7 +390,7 @@
 }
 
 impl EarlyLintPass for UnusedParens {
-    fn check_expr(&mut self, cx: &EarlyContext, e: &ast::Expr) {
+    fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
         use syntax::ast::ExprKind::*;
         let (value, msg, followed_by_block) = match e.node {
             If(ref cond, ..) => (cond, "`if` condition", true),
@@ -429,7 +432,7 @@
         self.check_unused_parens_expr(cx, &value, msg, followed_by_block);
     }
 
-    fn check_pat(&mut self, cx: &EarlyContext, p: &ast::Pat, _: &mut bool) {
+    fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &ast::Pat, _: &mut bool) {
         use ast::PatKind::{Paren, Range};
         // The lint visitor will visit each subpattern of `p`. We do not want to lint any range
         // pattern no matter where it occurs in the pattern. For something like `&(a..=b)`, there
@@ -443,7 +446,7 @@
         }
     }
 
-    fn check_stmt(&mut self, cx: &EarlyContext, s: &ast::Stmt) {
+    fn check_stmt(&mut self, cx: &EarlyContext<'_>, s: &ast::Stmt) {
         if let ast::StmtKind::Local(ref local) = s.node {
             if let Some(ref value) = local.init {
                 self.check_unused_parens_expr(cx, &value, "assigned value", false);
@@ -462,7 +465,7 @@
 pub struct UnusedImportBraces;
 
 impl UnusedImportBraces {
-    fn check_use_tree(&self, cx: &EarlyContext, use_tree: &ast::UseTree, item: &ast::Item) {
+    fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: &ast::Item) {
         if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
             // Recursively check nested UseTrees
             for &(ref tree, _) in items {
@@ -509,7 +512,7 @@
 }
 
 impl EarlyLintPass for UnusedImportBraces {
-    fn check_item(&mut self, cx: &EarlyContext, item: &ast::Item) {
+    fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
         if let ast::ItemKind::Use(ref use_tree) = item.node {
             self.check_use_tree(cx, use_tree, item);
         }
@@ -536,7 +539,7 @@
 }
 
 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation {
-    fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
+    fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr) {
         match e.node {
             hir::ExprKind::Box(_) => {}
             _ => return,
diff --git a/src/librustc_llvm/lib.rs b/src/librustc_llvm/lib.rs
index 99c5e24..3fcb20a 100644
--- a/src/librustc_llvm/lib.rs
+++ b/src/librustc_llvm/lib.rs
@@ -1,9 +1,7 @@
 #![deny(rust_2018_idioms)]
 #![feature(static_nobundle)]
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 
 // See librustc_cratesio_shim/Cargo.toml for a comment explaining this.
 #[allow(unused_extern_crates)]
diff --git a/src/librustc_metadata/Cargo.toml b/src/librustc_metadata/Cargo.toml
index 337c87c..e234f4f 100644
--- a/src/librustc_metadata/Cargo.toml
+++ b/src/librustc_metadata/Cargo.toml
@@ -2,6 +2,7 @@
 authors = ["The Rust Project Developers"]
 name = "rustc_metadata"
 version = "0.0.0"
+edition = "2018"
 
 [lib]
 name = "rustc_metadata"
@@ -14,7 +15,7 @@
 memmap = "0.6"
 rustc = { path = "../librustc" }
 rustc_data_structures = { path = "../librustc_data_structures" }
-rustc_errors = { path = "../librustc_errors" }
+errors = { path = "../librustc_errors", package = "rustc_errors" }
 rustc_target = { path = "../librustc_target" }
 serialize = { path = "../libserialize" }
 stable_deref_trait = "1.0.0"
diff --git a/src/librustc_metadata/creader.rs b/src/librustc_metadata/creader.rs
index e9785e7..0b4c8a5 100644
--- a/src/librustc_metadata/creader.rs
+++ b/src/librustc_metadata/creader.rs
@@ -1,9 +1,9 @@
 //! Validates all used crates and extern libraries and loads their metadata
 
-use cstore::{self, CStore, CrateSource, MetadataBlob};
-use locator::{self, CratePaths};
-use decoder::proc_macro_def_path_table;
-use schema::CrateRoot;
+use crate::cstore::{self, CStore, CrateSource, MetadataBlob};
+use crate::locator::{self, CratePaths};
+use crate::decoder::proc_macro_def_path_table;
+use crate::schema::CrateRoot;
 use rustc_data_structures::sync::{Lrc, RwLock, Lock};
 
 use rustc::hir::def_id::CrateNum;
@@ -29,8 +29,9 @@
 use syntax::ext::base::SyntaxExtension;
 use syntax::symbol::Symbol;
 use syntax::visit;
+use syntax::{span_err, span_fatal};
 use syntax_pos::{Span, DUMMY_SP};
-use log;
+use log::{debug, info, log_enabled};
 
 pub struct Library {
     pub dylib: Option<(PathBuf, PathKind)>,
@@ -342,7 +343,7 @@
         }
     }
 
-    fn load(&mut self, locate_ctxt: &mut locator::Context) -> Option<LoadResult> {
+    fn load(&mut self, locate_ctxt: &mut locator::Context<'_>) -> Option<LoadResult> {
         let library = locate_ctxt.maybe_load_library_crate()?;
 
         // In the case that we're loading a crate, but not matching
@@ -427,7 +428,7 @@
         // The map from crate numbers in the crate we're resolving to local crate numbers.
         // We map 0 and all other holes in the map to our parent crate. The "additional"
         // self-dependencies should be harmless.
-        ::std::iter::once(krate).chain(crate_root.crate_deps
+        std::iter::once(krate).chain(crate_root.crate_deps
                                                  .decode(metadata)
                                                  .map(|dep| {
             info!("resolving dep crate {} hash: `{}` extra filename: `{}`", dep.name, dep.hash,
@@ -522,7 +523,7 @@
     fn load_derive_macros(&mut self, root: &CrateRoot, dylib: Option<PathBuf>, span: Span)
                           -> Vec<(ast::Name, Lrc<SyntaxExtension>)> {
         use std::{env, mem};
-        use dynamic_lib::DynamicLibrary;
+        use crate::dynamic_lib::DynamicLibrary;
         use proc_macro::bridge::client::ProcMacro;
         use syntax_ext::deriving::custom::ProcMacroDerive;
         use syntax_ext::proc_macro_impl::{AttrProcMacro, BangProcMacro};
@@ -996,7 +997,7 @@
                        item.ident, orig_name);
                 let orig_name = match orig_name {
                     Some(orig_name) => {
-                        ::validate_crate_name(Some(self.sess), &orig_name.as_str(),
+                        crate::validate_crate_name(Some(self.sess), &orig_name.as_str(),
                                             Some(item.span));
                         orig_name
                     }
diff --git a/src/librustc_metadata/cstore.rs b/src/librustc_metadata/cstore.rs
index 543fb5d..a2f69bc 100644
--- a/src/librustc_metadata/cstore.rs
+++ b/src/librustc_metadata/cstore.rs
@@ -1,7 +1,7 @@
 // The crate store - a central repo for information collected about external
 // crates and libraries
 
-use schema;
+use crate::schema;
 use rustc::hir::def_id::{CrateNum, DefIndex};
 use rustc::hir::map::definitions::DefPathTable;
 use rustc::middle::cstore::{DepKind, ExternCrate, MetadataLoader};
@@ -19,7 +19,7 @@
 pub use rustc::middle::cstore::NativeLibraryKind::*;
 pub use rustc::middle::cstore::{CrateSource, LibSource, ForeignModule};
 
-pub use cstore_impl::{provide, provide_extern};
+pub use crate::cstore_impl::{provide, provide_extern};
 
 // A map from external crate numbers (as decoded from some crate file) to
 // local crate numbers (as generated during this session). Each external
diff --git a/src/librustc_metadata/cstore_impl.rs b/src/librustc_metadata/cstore_impl.rs
index e61229d..b248c6b 100644
--- a/src/librustc_metadata/cstore_impl.rs
+++ b/src/librustc_metadata/cstore_impl.rs
@@ -1,9 +1,9 @@
-use cstore::{self, LoadedMacro};
-use encoder;
-use link_args;
-use native_libs;
-use foreign_modules;
-use schema;
+use crate::cstore::{self, LoadedMacro};
+use crate::encoder;
+use crate::link_args;
+use crate::native_libs;
+use crate::foreign_modules;
+use crate::schema;
 
 use rustc::ty::query::QueryConfig;
 use rustc::middle::cstore::{CrateStore, DepKind,
@@ -29,6 +29,7 @@
 use syntax::source_map;
 use syntax::edition::Edition;
 use syntax::parse::source_file_to_stream;
+use syntax::parse::parser::emit_unclosed_delims;
 use syntax::symbol::Symbol;
 use syntax_pos::{Span, NO_EXPANSION, FileName};
 use rustc_data_structures::bit_set::BitSet;
@@ -51,7 +52,7 @@
                     index: CRATE_DEF_INDEX
                 });
                 let dep_node = def_path_hash
-                    .to_dep_node(::rustc::dep_graph::DepKind::CrateMetadata);
+                    .to_dep_node(rustc::dep_graph::DepKind::CrateMetadata);
                 // The DepNodeIndex of the DepNode::CrateMetadata should be
                 // cached somewhere, so that we can use read_index().
                 $tcx.dep_graph.read(dep_node);
@@ -421,7 +422,7 @@
             use syntax::ext::base::SyntaxExtension;
             use syntax_ext::proc_macro_impl::BangProcMacro;
 
-            let client = ::proc_macro::bridge::client::Client::expand1(::proc_macro::quote);
+            let client = proc_macro::bridge::client::Client::expand1(proc_macro::quote);
             let ext = SyntaxExtension::ProcMacro {
                 expander: Box::new(BangProcMacro { client }),
                 allow_internal_unstable: true,
@@ -436,7 +437,8 @@
 
         let source_file = sess.parse_sess.source_map().new_source_file(source_name, def.body);
         let local_span = Span::new(source_file.start_pos, source_file.end_pos, NO_EXPANSION);
-        let body = source_file_to_stream(&sess.parse_sess, source_file, None);
+        let (body, errors) = source_file_to_stream(&sess.parse_sess, source_file, None);
+        emit_unclosed_delims(&errors, &sess.diagnostic());
 
         // Mark the attrs as used
         let attrs = data.get_item_attrs(id.index, sess);
diff --git a/src/librustc_metadata/decoder.rs b/src/librustc_metadata/decoder.rs
index ad6296e..6d7907b 100644
--- a/src/librustc_metadata/decoder.rs
+++ b/src/librustc_metadata/decoder.rs
@@ -1,7 +1,7 @@
 // Decoding metadata from a single crate's metadata
 
-use cstore::{self, CrateMetadata, MetadataBlob, NativeLibrary, ForeignModule};
-use schema::*;
+use crate::cstore::{self, CrateMetadata, MetadataBlob, NativeLibrary, ForeignModule};
+use crate::schema::*;
 
 use rustc_data_structures::sync::{Lrc, ReadGuard};
 use rustc::hir::map::{DefKey, DefPath, DefPathData, DefPathHash, Definitions};
@@ -34,6 +34,7 @@
 use syntax::ext::base::{MacroKind, SyntaxExtension};
 use syntax::ext::hygiene::Mark;
 use syntax_pos::{self, Span, BytePos, Pos, DUMMY_SP, NO_EXPANSION};
+use log::debug;
 
 pub struct DecodeContext<'a, 'tcx: 'a> {
     opaque: opaque::Decoder<'a>,
@@ -545,7 +546,7 @@
 
     fn get_variant(&self,
                    tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                   item: &Entry,
+                   item: &Entry<'_>,
                    index: DefIndex,
                    adt_kind: ty::AdtKind)
                    -> ty::VariantDef
diff --git a/src/librustc_metadata/diagnostics.rs b/src/librustc_metadata/diagnostics.rs
index 1b18524..c27d13b 100644
--- a/src/librustc_metadata/diagnostics.rs
+++ b/src/librustc_metadata/diagnostics.rs
@@ -1,5 +1,7 @@
 #![allow(non_snake_case)]
 
+use syntax::{register_diagnostic, register_diagnostics, register_long_diagnostics};
+
 register_long_diagnostics! {
 E0454: r##"
 A link name was given with an empty name. Erroneous code example:
diff --git a/src/librustc_metadata/dynamic_lib.rs b/src/librustc_metadata/dynamic_lib.rs
index 7d1c3c0..b9dc419 100644
--- a/src/librustc_metadata/dynamic_lib.rs
+++ b/src/librustc_metadata/dynamic_lib.rs
@@ -76,7 +76,6 @@
 #[cfg(test)]
 mod tests {
     use super::*;
-    use libc;
     use std::mem;
 
     #[test]
@@ -127,7 +126,6 @@
 
 #[cfg(unix)]
 mod dl {
-    use libc;
     use std::ffi::{CStr, OsStr, CString};
     use std::os::unix::prelude::*;
     use std::ptr;
diff --git a/src/librustc_metadata/encoder.rs b/src/librustc_metadata/encoder.rs
index 3b212f3..4699f4c 100644
--- a/src/librustc_metadata/encoder.rs
+++ b/src/librustc_metadata/encoder.rs
@@ -1,7 +1,7 @@
-use index::Index;
-use index_builder::{FromId, IndexBuilder, Untracked};
-use isolated_encoder::IsolatedEncoder;
-use schema::*;
+use crate::index::Index;
+use crate::index_builder::{FromId, IndexBuilder, Untracked};
+use crate::isolated_encoder::IsolatedEncoder;
+use crate::schema::*;
 
 use rustc::middle::cstore::{LinkagePreference, NativeLibrary,
                             EncodedMetadata, ForeignModule};
@@ -34,6 +34,7 @@
 use syntax::source_map::Spanned;
 use syntax::symbol::keywords;
 use syntax_pos::{self, hygiene, FileName, SourceFile, Span};
+use log::{debug, trace};
 
 use rustc::hir::{self, PatKind};
 use rustc::hir::itemlikevisit::ItemLikeVisitor;
@@ -673,7 +674,7 @@
         let def_id = field.did;
         debug!("IsolatedEncoder::encode_field({:?})", def_id);
 
-        let variant_id = tcx.hir().as_local_node_id(variant.did).unwrap();
+        let variant_id = tcx.hir().as_local_hir_id(variant.did).unwrap();
         let variant_data = tcx.hir().expect_variant_data(variant_id);
 
         Entry {
@@ -1521,7 +1522,7 @@
     // symbol associated with them (they weren't translated) or if they're an FFI
     // definition (as that's not defined in this crate).
     fn encode_exported_symbols(&mut self,
-                               exported_symbols: &[(ExportedSymbol, SymbolExportLevel)])
+                               exported_symbols: &[(ExportedSymbol<'_>, SymbolExportLevel)])
                                -> EncodedExportedSymbols {
         // The metadata symbol name is special. It should not show up in
         // downstream crates.
diff --git a/src/librustc_metadata/index.rs b/src/librustc_metadata/index.rs
index ccf3982..18f3038 100644
--- a/src/librustc_metadata/index.rs
+++ b/src/librustc_metadata/index.rs
@@ -1,9 +1,10 @@
-use schema::*;
+use crate::schema::*;
 
 use rustc::hir::def_id::{DefId, DefIndex, DefIndexAddressSpace};
 use rustc_serialize::opaque::Encoder;
 use std::slice;
 use std::u32;
+use log::debug;
 
 /// While we are generating the metadata, we also track the position
 /// of each DefIndex. It is not required that all definitions appear
@@ -24,12 +25,12 @@
         }
     }
 
-    pub fn record(&mut self, def_id: DefId, entry: Lazy<Entry>) {
+    pub fn record(&mut self, def_id: DefId, entry: Lazy<Entry<'_>>) {
         assert!(def_id.is_local());
         self.record_index(def_id.index, entry);
     }
 
-    pub fn record_index(&mut self, item: DefIndex, entry: Lazy<Entry>) {
+    pub fn record_index(&mut self, item: DefIndex, entry: Lazy<Entry<'_>>) {
         assert!(entry.position < (u32::MAX as usize));
         let position = entry.position as u32;
         let space_index = item.address_space().index();
diff --git a/src/librustc_metadata/index_builder.rs b/src/librustc_metadata/index_builder.rs
index 3608b12..4175f7a 100644
--- a/src/librustc_metadata/index_builder.rs
+++ b/src/librustc_metadata/index_builder.rs
@@ -45,10 +45,10 @@
 //! give a callback fn, rather than taking a closure: it allows us to
 //! easily control precisely what data is given to that fn.
 
-use encoder::EncodeContext;
-use index::Index;
-use schema::*;
-use isolated_encoder::IsolatedEncoder;
+use crate::encoder::EncodeContext;
+use crate::index::Index;
+use crate::schema::*;
+use crate::isolated_encoder::IsolatedEncoder;
 
 use rustc::hir;
 use rustc::hir::def_id::DefId;
@@ -133,21 +133,21 @@
 /// `DefId` index, or implement the `read` method so that it can add
 /// a read of whatever dep-graph nodes are appropriate.
 pub trait DepGraphRead {
-    fn read(&self, tcx: TyCtxt);
+    fn read(&self, tcx: TyCtxt<'_, '_, '_>);
 }
 
 impl DepGraphRead for DefId {
-    fn read(&self, _tcx: TyCtxt) {}
+    fn read(&self, _tcx: TyCtxt<'_, '_, '_>) {}
 }
 
 impl DepGraphRead for ast::NodeId {
-    fn read(&self, _tcx: TyCtxt) {}
+    fn read(&self, _tcx: TyCtxt<'_, '_, '_>) {}
 }
 
 impl<T> DepGraphRead for Option<T>
     where T: DepGraphRead
 {
-    fn read(&self, tcx: TyCtxt) {
+    fn read(&self, tcx: TyCtxt<'_, '_, '_>) {
         match *self {
             Some(ref v) => v.read(tcx),
             None => (),
@@ -158,7 +158,7 @@
 impl<T> DepGraphRead for [T]
     where T: DepGraphRead
 {
-    fn read(&self, tcx: TyCtxt) {
+    fn read(&self, tcx: TyCtxt<'_, '_, '_>) {
         for i in self {
             i.read(tcx);
         }
@@ -171,7 +171,7 @@
             where $($name: DepGraphRead),*
         {
             #[allow(non_snake_case)]
-            fn read(&self, tcx: TyCtxt) {
+            fn read(&self, tcx: TyCtxt<'_, '_, '_>) {
                 let &($(ref $name),*) = self;
                 $($name.read(tcx);)*
             }
@@ -184,7 +184,7 @@
 macro_rules! read_hir {
     ($t:ty) => {
         impl<'tcx> DepGraphRead for &'tcx $t {
-            fn read(&self, tcx: TyCtxt) {
+            fn read(&self, tcx: TyCtxt<'_, '_, '_>) {
                 tcx.hir().read(self.id);
             }
         }
@@ -208,7 +208,7 @@
 pub struct Untracked<T>(pub T);
 
 impl<T> DepGraphRead for Untracked<T> {
-    fn read(&self, _tcx: TyCtxt) {}
+    fn read(&self, _tcx: TyCtxt<'_, '_, '_>) {}
 }
 
 /// Newtype that can be used to package up misc data extracted from a
@@ -218,7 +218,7 @@
 pub struct FromId<T>(pub ast::NodeId, pub T);
 
 impl<T> DepGraphRead for FromId<T> {
-    fn read(&self, tcx: TyCtxt) {
+    fn read(&self, tcx: TyCtxt<'_, '_, '_>) {
         tcx.hir().read(self.0);
     }
 }
diff --git a/src/librustc_metadata/isolated_encoder.rs b/src/librustc_metadata/isolated_encoder.rs
index c09d35d..e879a73 100644
--- a/src/librustc_metadata/isolated_encoder.rs
+++ b/src/librustc_metadata/isolated_encoder.rs
@@ -1,5 +1,5 @@
-use encoder::EncodeContext;
-use schema::{Lazy, LazySeq};
+use crate::encoder::EncodeContext;
+use crate::schema::{Lazy, LazySeq};
 use rustc::ty::TyCtxt;
 use rustc_serialize::Encodable;
 
diff --git a/src/librustc_metadata/lib.rs b/src/librustc_metadata/lib.rs
index 1a66142..a3490b7 100644
--- a/src/librustc_metadata/lib.rs
+++ b/src/librustc_metadata/lib.rs
@@ -1,6 +1,4 @@
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 
 #![feature(box_patterns)]
 #![feature(libc)]
@@ -15,23 +13,15 @@
 
 #![recursion_limit="256"]
 
+#![deny(rust_2018_idioms)]
+
 extern crate libc;
-#[macro_use]
-extern crate log;
-extern crate memmap;
-extern crate stable_deref_trait;
-#[macro_use]
-extern crate syntax;
-extern crate syntax_pos;
-extern crate flate2;
+#[allow(unused_extern_crates)]
 extern crate serialize as rustc_serialize; // used by deriving
-extern crate rustc_errors as errors;
-extern crate syntax_ext;
 extern crate proc_macro;
 
 #[macro_use]
 extern crate rustc;
-extern crate rustc_target;
 #[macro_use]
 extern crate rustc_data_structures;
 
diff --git a/src/librustc_metadata/locator.rs b/src/librustc_metadata/locator.rs
index 6b49d6b..f120072 100644
--- a/src/librustc_metadata/locator.rs
+++ b/src/librustc_metadata/locator.rs
@@ -212,9 +212,9 @@
 //! no means all of the necessary details. Take a look at the rest of
 //! metadata::locator or metadata::creader for all the juicy details!
 
-use cstore::{MetadataRef, MetadataBlob};
-use creader::Library;
-use schema::{METADATA_HEADER, rustc_version};
+use crate::cstore::{MetadataRef, MetadataBlob};
+use crate::creader::Library;
+use crate::schema::{METADATA_HEADER, rustc_version};
 
 use rustc_data_structures::fx::FxHashSet;
 use rustc_data_structures::svh::Svh;
@@ -226,6 +226,7 @@
 
 use errors::DiagnosticBuilder;
 use syntax::symbol::Symbol;
+use syntax::struct_span_err;
 use syntax_pos::Span;
 use rustc_target::spec::{Target, TargetTriple};
 
@@ -241,6 +242,8 @@
 
 use rustc_data_structures::owning_ref::OwningRef;
 
+use log::{debug, info, warn};
+
 pub struct CrateMismatch {
     path: PathBuf,
     got: String,
@@ -283,7 +286,7 @@
 }
 
 impl fmt::Display for CrateFlavor {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         f.write_str(match *self {
             CrateFlavor::Rlib => "rlib",
             CrateFlavor::Rmeta => "rmeta",
@@ -600,7 +603,7 @@
             }
         }
 
-        let mut err: Option<DiagnosticBuilder> = None;
+        let mut err: Option<DiagnosticBuilder<'_>> = None;
         for (lib, kind) in m {
             info!("{} reading metadata from: {}", flavor, lib.display());
             let (hash, metadata) =
diff --git a/src/librustc_metadata/native_libs.rs b/src/librustc_metadata/native_libs.rs
index 1f00086..118fb20 100644
--- a/src/librustc_metadata/native_libs.rs
+++ b/src/librustc_metadata/native_libs.rs
@@ -9,6 +9,7 @@
 use syntax::source_map::Span;
 use syntax::feature_gate::{self, GateIssue};
 use syntax::symbol::Symbol;
+use syntax::{span_err, struct_span_err};
 
 pub fn collect<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Vec<NativeLibrary> {
     let mut collector = Collector {
diff --git a/src/librustc_metadata/schema.rs b/src/librustc_metadata/schema.rs
index f3ff974..af79ea3 100644
--- a/src/librustc_metadata/schema.rs
+++ b/src/librustc_metadata/schema.rs
@@ -1,4 +1,4 @@
-use index;
+use crate::index;
 
 use rustc::hir;
 use rustc::hir::def::{self, CtorKind};
@@ -518,7 +518,7 @@
     ImplFinal,
 }
 
-impl_stable_hash_for!(enum ::schema::AssociatedContainer {
+impl_stable_hash_for!(enum crate::schema::AssociatedContainer {
     TraitRequired,
     TraitWithDefault,
     ImplDefault,
diff --git a/src/librustc_mir/Cargo.toml b/src/librustc_mir/Cargo.toml
index f0234c4..44a6b41 100644
--- a/src/librustc_mir/Cargo.toml
+++ b/src/librustc_mir/Cargo.toml
@@ -2,6 +2,7 @@
 authors = ["The Rust Project Developers"]
 name = "rustc_mir"
 version = "0.0.0"
+edition = "2018"
 
 [lib]
 name = "rustc_mir"
@@ -12,7 +13,7 @@
 arena = { path = "../libarena" }
 bitflags = "1.0"
 either = "1.5.0"
-graphviz = { path = "../libgraphviz" }
+dot = { path = "../libgraphviz", package = "graphviz" }
 log = "0.4"
 log_settings = "0.1.1"
 polonius-engine = "0.6.2"
diff --git a/src/librustc_mir/borrow_check/borrow_set.rs b/src/librustc_mir/borrow_check/borrow_set.rs
index ecbc611..2788f5d 100644
--- a/src/librustc_mir/borrow_check/borrow_set.rs
+++ b/src/librustc_mir/borrow_check/borrow_set.rs
@@ -1,7 +1,7 @@
-use borrow_check::place_ext::PlaceExt;
-use borrow_check::nll::ToRegionVid;
-use dataflow::indexes::BorrowIndex;
-use dataflow::move_paths::MoveData;
+use crate::borrow_check::place_ext::PlaceExt;
+use crate::borrow_check::nll::ToRegionVid;
+use crate::dataflow::indexes::BorrowIndex;
+use crate::dataflow::move_paths::MoveData;
 use rustc::mir::traversal;
 use rustc::mir::visit::{
     PlaceContext, Visitor, NonUseContext, MutatingUseContext, NonMutatingUseContext
@@ -72,7 +72,7 @@
 }
 
 impl<'tcx> fmt::Display for BorrowData<'tcx> {
-    fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
         let kind = match self.kind {
             mir::BorrowKind::Shared => "",
             mir::BorrowKind::Shallow => "shallow ",
diff --git a/src/librustc_mir/borrow_check/error_reporting.rs b/src/librustc_mir/borrow_check/error_reporting.rs
index b070031..5a8d754 100644
--- a/src/librustc_mir/borrow_check/error_reporting.rs
+++ b/src/librustc_mir/borrow_check/error_reporting.rs
@@ -1,7 +1,7 @@
-use borrow_check::nll::explain_borrow::BorrowExplanation;
-use borrow_check::nll::region_infer::{RegionName, RegionNameSource};
-use borrow_check::prefixes::IsPrefixOf;
-use borrow_check::WriteKind;
+use crate::borrow_check::nll::explain_borrow::BorrowExplanation;
+use crate::borrow_check::nll::region_infer::{RegionName, RegionNameSource};
+use crate::borrow_check::prefixes::IsPrefixOf;
+use crate::borrow_check::WriteKind;
 use rustc::hir;
 use rustc::hir::def_id::DefId;
 use rustc::middle::region::ScopeTree;
@@ -22,10 +22,10 @@
 use super::borrow_set::BorrowData;
 use super::{Context, MirBorrowckCtxt};
 use super::{InitializationRequiringAction, PrefixSet};
-use dataflow::drop_flag_effects;
-use dataflow::move_paths::indexes::MoveOutIndex;
-use dataflow::move_paths::MovePathIndex;
-use util::borrowck_errors::{BorrowckErrors, Origin};
+use crate::dataflow::drop_flag_effects;
+use crate::dataflow::move_paths::indexes::MoveOutIndex;
+use crate::dataflow::move_paths::MovePathIndex;
+use crate::util::borrowck_errors::{BorrowckErrors, Origin};
 
 #[derive(Debug)]
 struct MoveSite {
@@ -833,13 +833,13 @@
                 format!("`{}` would have to be valid for `{}`...", name, region_name),
             );
 
-            if let Some(fn_node_id) = self.infcx.tcx.hir().as_local_node_id(self.mir_def_id) {
+            if let Some(fn_hir_id) = self.infcx.tcx.hir().as_local_hir_id(self.mir_def_id) {
                 err.span_label(
                     drop_span,
                     format!(
                         "...but `{}` will be dropped here, when the function `{}` returns",
                         name,
-                        self.infcx.tcx.hir().name(fn_node_id),
+                        self.infcx.tcx.hir().name_by_hir_id(fn_hir_id),
                     ),
                 );
 
@@ -1726,7 +1726,7 @@
     }
 
     /// End-user visible description of the `field`nth field of `base`
-    fn describe_field(&self, base: &Place, field: Field) -> String {
+    fn describe_field(&self, base: &Place<'_>, field: Field) -> String {
         match *base {
             Place::Local(local) => {
                 let local = &self.mir.local_decls[local];
@@ -1751,7 +1751,7 @@
     }
 
     /// End-user visible description of the `field_index`nth field of `ty`
-    fn describe_field_from_ty(&self, ty: &ty::Ty, field: Field) -> String {
+    fn describe_field_from_ty(&self, ty: &ty::Ty<'_>, field: Field) -> String {
         if ty.is_box() {
             // If the type is a box, the field is described from the boxed type
             self.describe_field_from_ty(&ty.boxed_ty(), field)
@@ -1860,7 +1860,7 @@
     fn annotate_argument_and_return_for_borrow(
         &self,
         borrow: &BorrowData<'tcx>,
-    ) -> Option<AnnotatedBorrowFnSignature> {
+    ) -> Option<AnnotatedBorrowFnSignature<'_>> {
         // Define a fallback for when we can't match a closure.
         let fallback = || {
             let is_closure = self.infcx.tcx.is_closure(self.mir_def_id);
@@ -2081,7 +2081,7 @@
         &self,
         did: DefId,
         sig: ty::PolyFnSig<'tcx>,
-    ) -> Option<AnnotatedBorrowFnSignature> {
+    ) -> Option<AnnotatedBorrowFnSignature<'_>> {
         debug!("annotate_fn_sig: did={:?} sig={:?}", did, sig);
         let is_closure = self.infcx.tcx.is_closure(did);
         let fn_node_id = self.infcx.tcx.hir().as_local_node_id(did)?;
@@ -2368,14 +2368,22 @@
     }
 
     // Add a span label to the arguments of the closure, if it exists.
-    pub(super) fn args_span_label(self, err: &mut DiagnosticBuilder, message: impl Into<String>) {
+    pub(super) fn args_span_label(
+        self,
+        err: &mut DiagnosticBuilder<'_>,
+        message: impl Into<String>,
+    ) {
         if let UseSpans::ClosureUse { args_span, .. } = self {
             err.span_label(args_span, message);
         }
     }
 
     // Add a span label to the use of the captured variable, if it exists.
-    pub(super) fn var_span_label(self, err: &mut DiagnosticBuilder, message: impl Into<String>) {
+    pub(super) fn var_span_label(
+        self,
+        err: &mut DiagnosticBuilder<'_>,
+        message: impl Into<String>,
+    ) {
         if let UseSpans::ClosureUse { var_span, .. } = self {
             err.span_label(var_span, message);
         }
@@ -2563,7 +2571,7 @@
 
     /// Helper to retrieve span(s) of given borrow from the current MIR
     /// representation
-    pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData) -> UseSpans {
+    pub(super) fn retrieve_borrow_spans(&self, borrow: &BorrowData<'_>) -> UseSpans {
         let span = self.mir.source_info(borrow.reserve_location).span;
         self.borrow_spans(span, borrow.reserve_location)
     }
diff --git a/src/librustc_mir/borrow_check/flows.rs b/src/librustc_mir/borrow_check/flows.rs
index 4eeb19c..8de39f0 100644
--- a/src/librustc_mir/borrow_check/flows.rs
+++ b/src/librustc_mir/borrow_check/flows.rs
@@ -7,16 +7,16 @@
 use rustc::ty::RegionVid;
 use rustc_data_structures::bit_set::BitIter;
 
-use borrow_check::location::LocationIndex;
+use crate::borrow_check::location::LocationIndex;
 
 use polonius_engine::Output;
 
-use dataflow::move_paths::indexes::BorrowIndex;
-use dataflow::move_paths::HasMoveData;
-use dataflow::Borrows;
-use dataflow::EverInitializedPlaces;
-use dataflow::{FlowAtLocation, FlowsAtLocation};
-use dataflow::MaybeUninitializedPlaces;
+use crate::dataflow::move_paths::indexes::BorrowIndex;
+use crate::dataflow::move_paths::HasMoveData;
+use crate::dataflow::Borrows;
+use crate::dataflow::EverInitializedPlaces;
+use crate::dataflow::{FlowAtLocation, FlowsAtLocation};
+use crate::dataflow::MaybeUninitializedPlaces;
 use either::Either;
 use std::fmt;
 use std::rc::Rc;
@@ -57,7 +57,7 @@
         }
     }
 
-    crate fn with_outgoing_borrows(&self, op: impl FnOnce(BitIter<BorrowIndex>)) {
+    crate fn with_outgoing_borrows(&self, op: impl FnOnce(BitIter<'_, BorrowIndex>)) {
         self.borrows.with_iter_outgoing(op)
     }
 }
@@ -93,7 +93,7 @@
 }
 
 impl<'b, 'gcx, 'tcx> fmt::Display for Flows<'b, 'gcx, 'tcx> {
-    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
         let mut s = String::new();
 
         s.push_str("borrows in effect: [");
diff --git a/src/librustc_mir/borrow_check/mod.rs b/src/librustc_mir/borrow_check/mod.rs
index 5597e4a..45a8c9e 100644
--- a/src/librustc_mir/borrow_check/mod.rs
+++ b/src/librustc_mir/borrow_check/mod.rs
@@ -1,6 +1,6 @@
 //! This query borrow-checks the MIR to (further) ensure it is not broken.
 
-use borrow_check::nll::region_infer::RegionInferenceContext;
+use crate::borrow_check::nll::region_infer::RegionInferenceContext;
 use rustc::hir;
 use rustc::hir::Node;
 use rustc::hir::def_id::DefId;
@@ -25,16 +25,16 @@
 
 use syntax_pos::Span;
 
-use dataflow::indexes::{BorrowIndex, InitIndex, MoveOutIndex, MovePathIndex};
-use dataflow::move_paths::{HasMoveData, LookupResult, MoveData, MoveError};
-use dataflow::Borrows;
-use dataflow::DataflowResultsConsumer;
-use dataflow::FlowAtLocation;
-use dataflow::MoveDataParamEnv;
-use dataflow::{do_dataflow, DebugFormatted};
-use dataflow::EverInitializedPlaces;
-use dataflow::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
-use util::borrowck_errors::{BorrowckErrors, Origin};
+use crate::dataflow::indexes::{BorrowIndex, InitIndex, MoveOutIndex, MovePathIndex};
+use crate::dataflow::move_paths::{HasMoveData, LookupResult, MoveData, MoveError};
+use crate::dataflow::Borrows;
+use crate::dataflow::DataflowResultsConsumer;
+use crate::dataflow::FlowAtLocation;
+use crate::dataflow::MoveDataParamEnv;
+use crate::dataflow::{do_dataflow, DebugFormatted};
+use crate::dataflow::EverInitializedPlaces;
+use crate::dataflow::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
+use crate::util::borrowck_errors::{BorrowckErrors, Origin};
 
 use self::borrow_set::{BorrowData, BorrowSet};
 use self::flows::Flows;
@@ -59,7 +59,7 @@
 
 pub(crate) mod nll;
 
-pub fn provide(providers: &mut Providers) {
+pub fn provide(providers: &mut Providers<'_>) {
     *providers = Providers {
         mir_borrowck,
         ..*providers
@@ -108,7 +108,7 @@
     }
 
     let opt_closure_req = tcx.infer_ctxt().enter(|infcx| {
-        let input_mir: &Mir = &input_mir.borrow();
+        let input_mir: &Mir<'_> = &input_mir.borrow();
         do_mir_borrowck(&infcx, input_mir, def_id)
     });
     debug!("mir_borrowck done");
diff --git a/src/librustc_mir/borrow_check/move_errors.rs b/src/librustc_mir/borrow_check/move_errors.rs
index 8539b5c..2a5433d 100644
--- a/src/librustc_mir/borrow_check/move_errors.rs
+++ b/src/librustc_mir/borrow_check/move_errors.rs
@@ -6,13 +6,13 @@
 use rustc_errors::{DiagnosticBuilder,Applicability};
 use syntax_pos::Span;
 
-use borrow_check::MirBorrowckCtxt;
-use borrow_check::prefixes::PrefixSet;
-use dataflow::move_paths::{
+use crate::borrow_check::MirBorrowckCtxt;
+use crate::borrow_check::prefixes::PrefixSet;
+use crate::dataflow::move_paths::{
     IllegalMoveOrigin, IllegalMoveOriginKind, InitLocation,
     LookupResult, MoveError, MovePathIndex,
 };
-use util::borrowck_errors::{BorrowckErrors, Origin};
+use crate::util::borrowck_errors::{BorrowckErrors, Origin};
 
 // Often when desugaring a pattern match we may have many individual moves in
 // MIR that are all part of one operation from the user's point-of-view. For
@@ -63,7 +63,7 @@
 }
 
 impl Display for BorrowedContentSource {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match *self {
             BorrowedContentSource::Arc => write!(f, "an `Arc`"),
             BorrowedContentSource::Rc => write!(f, "an `Rc`"),
@@ -240,7 +240,7 @@
 
     fn report(&mut self, error: GroupedMoveError<'tcx>) {
         let (mut err, err_span) = {
-            let (span, original_path, kind): (Span, &Place<'tcx>, &IllegalMoveOriginKind) =
+            let (span, original_path, kind): (Span, &Place<'tcx>, &IllegalMoveOriginKind<'_>) =
                 match error {
                     GroupedMoveError::MovesFromPlace {
                         span,
@@ -308,9 +308,8 @@
                                         let upvar_decl = &self.mir.upvar_decls[field.index()];
                                         let upvar_hir_id =
                                             upvar_decl.var_hir_id.assert_crate_local();
-                                        let upvar_node_id =
-                                            self.infcx.tcx.hir().hir_to_node_id(upvar_hir_id);
-                                        let upvar_span = self.infcx.tcx.hir().span(upvar_node_id);
+                                        let upvar_span = self.infcx.tcx.hir().span_by_hir_id(
+                                            upvar_hir_id);
                                         diag.span_label(upvar_span, "captured outer variable");
                                         break;
                                     }
diff --git a/src/librustc_mir/borrow_check/mutability_errors.rs b/src/librustc_mir/borrow_check/mutability_errors.rs
index 9d3ce76..dad8d90 100644
--- a/src/librustc_mir/borrow_check/mutability_errors.rs
+++ b/src/librustc_mir/borrow_check/mutability_errors.rs
@@ -8,11 +8,11 @@
 use syntax_pos::Span;
 use syntax_pos::symbol::keywords;
 
-use dataflow::move_paths::InitLocation;
-use borrow_check::MirBorrowckCtxt;
-use util::borrowck_errors::{BorrowckErrors, Origin};
-use util::collect_writes::FindAssignments;
-use util::suggest_ref_mut;
+use crate::dataflow::move_paths::InitLocation;
+use crate::borrow_check::MirBorrowckCtxt;
+use crate::util::borrowck_errors::{BorrowckErrors, Origin};
+use crate::util::collect_writes::FindAssignments;
+use crate::util::suggest_ref_mut;
 use rustc_errors::Applicability;
 
 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
@@ -611,7 +611,7 @@
      })
 }
 
-fn is_closure_or_generator(ty: ty::Ty) -> bool {
+fn is_closure_or_generator(ty: ty::Ty<'_>) -> bool {
     ty.is_closure() || ty.is_generator()
 }
 
diff --git a/src/librustc_mir/borrow_check/nll/constraint_generation.rs b/src/librustc_mir/borrow_check/nll/constraint_generation.rs
index 588f46c..c02c2b4 100644
--- a/src/librustc_mir/borrow_check/nll/constraint_generation.rs
+++ b/src/librustc_mir/borrow_check/nll/constraint_generation.rs
@@ -1,8 +1,8 @@
-use borrow_check::borrow_set::BorrowSet;
-use borrow_check::location::LocationTable;
-use borrow_check::nll::ToRegionVid;
-use borrow_check::nll::facts::AllFacts;
-use borrow_check::nll::region_infer::values::LivenessValues;
+use crate::borrow_check::borrow_set::BorrowSet;
+use crate::borrow_check::location::LocationTable;
+use crate::borrow_check::nll::ToRegionVid;
+use crate::borrow_check::nll::facts::AllFacts;
+use crate::borrow_check::nll::region_infer::values::LivenessValues;
 use rustc::infer::InferCtxt;
 use rustc::mir::visit::TyContext;
 use rustc::mir::visit::Visitor;
diff --git a/src/librustc_mir/borrow_check/nll/constraints/graph.rs b/src/librustc_mir/borrow_check/nll/constraints/graph.rs
index fe9ccb4..2479dfd 100644
--- a/src/librustc_mir/borrow_check/nll/constraints/graph.rs
+++ b/src/librustc_mir/borrow_check/nll/constraints/graph.rs
@@ -1,6 +1,6 @@
-use borrow_check::nll::type_check::Locations;
-use borrow_check::nll::constraints::ConstraintIndex;
-use borrow_check::nll::constraints::{ConstraintSet, OutlivesConstraint};
+use crate::borrow_check::nll::type_check::Locations;
+use crate::borrow_check::nll::constraints::ConstraintIndex;
+use crate::borrow_check::nll::constraints::{ConstraintSet, OutlivesConstraint};
 use rustc::mir::ConstraintCategory;
 use rustc::ty::RegionVid;
 use rustc_data_structures::graph;
diff --git a/src/librustc_mir/borrow_check/nll/constraints/mod.rs b/src/librustc_mir/borrow_check/nll/constraints/mod.rs
index 146bd65..d3f9743 100644
--- a/src/librustc_mir/borrow_check/nll/constraints/mod.rs
+++ b/src/librustc_mir/borrow_check/nll/constraints/mod.rs
@@ -2,7 +2,7 @@
 use rustc::ty::RegionVid;
 use rustc_data_structures::graph::scc::Sccs;
 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
-use borrow_check::nll::type_check::Locations;
+use crate::borrow_check::nll::type_check::Locations;
 
 use std::fmt;
 use std::ops::Deref;
@@ -84,7 +84,7 @@
 }
 
 impl fmt::Debug for OutlivesConstraint {
-    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(
             formatter,
             "({:?}: {:?}) due to {:?}",
diff --git a/src/librustc_mir/borrow_check/nll/explain_borrow/find_use.rs b/src/librustc_mir/borrow_check/nll/explain_borrow/find_use.rs
index 53035da..c5aaf5b 100644
--- a/src/librustc_mir/borrow_check/nll/explain_borrow/find_use.rs
+++ b/src/librustc_mir/borrow_check/nll/explain_borrow/find_use.rs
@@ -1,13 +1,13 @@
 use std::collections::VecDeque;
 use std::rc::Rc;
 
-use borrow_check::nll::region_infer::{Cause, RegionInferenceContext};
-use borrow_check::nll::ToRegionVid;
+use crate::borrow_check::nll::region_infer::{Cause, RegionInferenceContext};
+use crate::borrow_check::nll::ToRegionVid;
+use crate::util::liveness::{self, DefUse};
 use rustc::mir::visit::{MirVisitable, PlaceContext, Visitor};
 use rustc::mir::{Local, Location, Mir};
 use rustc::ty::{RegionVid, TyCtxt};
 use rustc_data_structures::fx::FxHashSet;
-use util::liveness::{self, DefUse};
 
 crate fn find<'tcx>(
     mir: &Mir<'tcx>,
diff --git a/src/librustc_mir/borrow_check/nll/explain_borrow/mod.rs b/src/librustc_mir/borrow_check/nll/explain_borrow/mod.rs
index 968c0f5..8e57d10 100644
--- a/src/librustc_mir/borrow_check/nll/explain_borrow/mod.rs
+++ b/src/librustc_mir/borrow_check/nll/explain_borrow/mod.rs
@@ -1,8 +1,8 @@
-use borrow_check::borrow_set::BorrowData;
-use borrow_check::error_reporting::UseSpans;
-use borrow_check::nll::ConstraintDescription;
-use borrow_check::nll::region_infer::{Cause, RegionName};
-use borrow_check::{Context, MirBorrowckCtxt, WriteKind};
+use crate::borrow_check::borrow_set::BorrowData;
+use crate::borrow_check::error_reporting::UseSpans;
+use crate::borrow_check::nll::ConstraintDescription;
+use crate::borrow_check::nll::region_infer::{Cause, RegionName};
+use crate::borrow_check::{Context, MirBorrowckCtxt, WriteKind};
 use rustc::ty::{self, TyCtxt};
 use rustc::mir::{
     CastKind, ConstraintCategory, FakeReadCause, Local, Location, Mir, Operand,
@@ -14,7 +14,7 @@
 
 mod find_use;
 
-pub(in borrow_check) enum BorrowExplanation {
+pub(in crate::borrow_check) enum BorrowExplanation {
     UsedLater(LaterUseKind, Span),
     UsedLaterInLoop(LaterUseKind, Span),
     UsedLaterWhenDropped {
@@ -33,7 +33,7 @@
 }
 
 #[derive(Clone, Copy)]
-pub(in borrow_check) enum LaterUseKind {
+pub(in crate::borrow_check) enum LaterUseKind {
     TraitCapture,
     ClosureCapture,
     Call,
@@ -42,13 +42,13 @@
 }
 
 impl BorrowExplanation {
-    pub(in borrow_check) fn is_explained(&self) -> bool {
+    pub(in crate::borrow_check) fn is_explained(&self) -> bool {
         match self {
             BorrowExplanation::Unexplained => false,
             _ => true,
         }
     }
-    pub(in borrow_check) fn add_explanation_to_diagnostic<'cx, 'gcx, 'tcx>(
+    pub(in crate::borrow_check) fn add_explanation_to_diagnostic<'cx, 'gcx, 'tcx>(
         &self,
         tcx: TyCtxt<'cx, 'gcx, 'tcx>,
         mir: &Mir<'tcx>,
@@ -187,7 +187,7 @@
     ///   - second half is the place being accessed
     ///
     /// [d]: https://rust-lang.github.io/rfcs/2094-nll.html#leveraging-intuition-framing-errors-in-terms-of-points
-    pub(in borrow_check) fn explain_why_borrow_contains_point(
+    pub(in crate::borrow_check) fn explain_why_borrow_contains_point(
         &self,
         context: Context,
         borrow: &BorrowData<'tcx>,
diff --git a/src/librustc_mir/borrow_check/nll/facts.rs b/src/librustc_mir/borrow_check/nll/facts.rs
index bc33a1c..9672d3e 100644
--- a/src/librustc_mir/borrow_check/nll/facts.rs
+++ b/src/librustc_mir/borrow_check/nll/facts.rs
@@ -1,5 +1,5 @@
-use borrow_check::location::{LocationIndex, LocationTable};
-use dataflow::indexes::BorrowIndex;
+use crate::borrow_check::location::{LocationIndex, LocationTable};
+use crate::dataflow::indexes::BorrowIndex;
 use polonius_engine::AllFacts as PoloniusAllFacts;
 use polonius_engine::Atom;
 use rustc::ty::{RegionVid, TyCtxt};
diff --git a/src/librustc_mir/borrow_check/nll/invalidation.rs b/src/librustc_mir/borrow_check/nll/invalidation.rs
index 112b399..3df6b79 100644
--- a/src/librustc_mir/borrow_check/nll/invalidation.rs
+++ b/src/librustc_mir/borrow_check/nll/invalidation.rs
@@ -1,15 +1,15 @@
-use borrow_check::borrow_set::BorrowSet;
-use borrow_check::location::LocationTable;
-use borrow_check::{JustWrite, WriteAndRead};
-use borrow_check::{AccessDepth, Deep, Shallow};
-use borrow_check::{ReadOrWrite, Activation, Read, Reservation, Write};
-use borrow_check::{Context, ContextKind};
-use borrow_check::{LocalMutationIsAllowed, MutateMode};
-use borrow_check::ArtificialField;
-use borrow_check::{ReadKind, WriteKind};
-use borrow_check::nll::facts::AllFacts;
-use borrow_check::path_utils::*;
-use dataflow::move_paths::indexes::BorrowIndex;
+use crate::borrow_check::borrow_set::BorrowSet;
+use crate::borrow_check::location::LocationTable;
+use crate::borrow_check::{JustWrite, WriteAndRead};
+use crate::borrow_check::{AccessDepth, Deep, Shallow};
+use crate::borrow_check::{ReadOrWrite, Activation, Read, Reservation, Write};
+use crate::borrow_check::{Context, ContextKind};
+use crate::borrow_check::{LocalMutationIsAllowed, MutateMode};
+use crate::borrow_check::ArtificialField;
+use crate::borrow_check::{ReadKind, WriteKind};
+use crate::borrow_check::nll::facts::AllFacts;
+use crate::borrow_check::path_utils::*;
+use crate::dataflow::move_paths::indexes::BorrowIndex;
 use rustc::ty::TyCtxt;
 use rustc::mir::visit::Visitor;
 use rustc::mir::{BasicBlock, Location, Mir, Place, Rvalue};
diff --git a/src/librustc_mir/borrow_check/nll/mod.rs b/src/librustc_mir/borrow_check/nll/mod.rs
index a092c3b..84fdbb9 100644
--- a/src/librustc_mir/borrow_check/nll/mod.rs
+++ b/src/librustc_mir/borrow_check/nll/mod.rs
@@ -1,13 +1,14 @@
-use borrow_check::borrow_set::BorrowSet;
-use borrow_check::location::{LocationIndex, LocationTable};
-use borrow_check::nll::facts::AllFactsExt;
-use borrow_check::nll::type_check::{MirTypeckResults, MirTypeckRegionConstraints};
-use borrow_check::nll::type_check::liveness::liveness_map::NllLivenessMap;
-use borrow_check::nll::region_infer::values::RegionValueElements;
-use dataflow::indexes::BorrowIndex;
-use dataflow::move_paths::MoveData;
-use dataflow::FlowAtLocation;
-use dataflow::MaybeInitializedPlaces;
+use crate::borrow_check::borrow_set::BorrowSet;
+use crate::borrow_check::location::{LocationIndex, LocationTable};
+use crate::borrow_check::nll::facts::AllFactsExt;
+use crate::borrow_check::nll::type_check::{MirTypeckResults, MirTypeckRegionConstraints};
+use crate::borrow_check::nll::type_check::liveness::liveness_map::NllLivenessMap;
+use crate::borrow_check::nll::region_infer::values::RegionValueElements;
+use crate::dataflow::indexes::BorrowIndex;
+use crate::dataflow::move_paths::MoveData;
+use crate::dataflow::FlowAtLocation;
+use crate::dataflow::MaybeInitializedPlaces;
+use crate::transform::MirSource;
 use rustc::hir::def_id::DefId;
 use rustc::infer::InferCtxt;
 use rustc::mir::{ClosureOutlivesSubject, ClosureRegionRequirements, Mir};
@@ -19,12 +20,11 @@
 use std::path::PathBuf;
 use std::rc::Rc;
 use std::str::FromStr;
-use transform::MirSource;
 
 use self::mir_util::PassWhere;
 use polonius_engine::{Algorithm, Output};
-use util as mir_util;
-use util::pretty;
+use crate::util as mir_util;
+use crate::util::pretty;
 
 mod constraint_generation;
 pub mod explain_borrow;
@@ -45,7 +45,7 @@
 /// scraping out the set of universal regions (e.g., region parameters)
 /// declared on the function. That set will need to be given to
 /// `compute_regions`.
-pub(in borrow_check) fn replace_regions_in_mir<'cx, 'gcx, 'tcx>(
+pub(in crate::borrow_check) fn replace_regions_in_mir<'cx, 'gcx, 'tcx>(
     infcx: &InferCtxt<'cx, 'gcx, 'tcx>,
     def_id: DefId,
     param_env: ty::ParamEnv<'tcx>,
@@ -68,7 +68,7 @@
 /// Computes the (non-lexical) regions from the input MIR.
 ///
 /// This may result in errors being reported.
-pub(in borrow_check) fn compute_regions<'cx, 'gcx, 'tcx>(
+pub(in crate::borrow_check) fn compute_regions<'cx, 'gcx, 'tcx>(
     infcx: &InferCtxt<'cx, 'gcx, 'tcx>,
     def_id: DefId,
     universal_regions: UniversalRegions<'tcx>,
@@ -209,10 +209,10 @@
 
 fn dump_mir_results<'a, 'gcx, 'tcx>(
     infcx: &InferCtxt<'a, 'gcx, 'tcx>,
-    source: MirSource,
+    source: MirSource<'tcx>,
     mir: &Mir<'tcx>,
-    regioncx: &RegionInferenceContext,
-    closure_region_requirements: &Option<ClosureRegionRequirements>,
+    regioncx: &RegionInferenceContext<'_>,
+    closure_region_requirements: &Option<ClosureRegionRequirements<'_>>,
 ) {
     if !mir_util::dump_enabled(infcx.tcx, "nll", source) {
         return;
@@ -254,14 +254,14 @@
     );
 
     // Also dump the inference graph constraints as a graphviz file.
-    let _: io::Result<()> = try_block! {
+    let _: io::Result<()> = try {
         let mut file =
             pretty::create_dump_file(infcx.tcx, "regioncx.all.dot", None, "nll", &0, source)?;
         regioncx.dump_graphviz_raw_constraints(&mut file)?;
     };
 
     // Also dump the inference graph constraints as a graphviz file.
-    let _: io::Result<()> = try_block! {
+    let _: io::Result<()> = try {
         let mut file =
             pretty::create_dump_file(infcx.tcx, "regioncx.scc.dot", None, "nll", &0, source)?;
         regioncx.dump_graphviz_scc_constraints(&mut file)?;
@@ -273,7 +273,7 @@
     mir: &Mir<'tcx>,
     mir_def_id: DefId,
     regioncx: &RegionInferenceContext<'tcx>,
-    closure_region_requirements: &Option<ClosureRegionRequirements>,
+    closure_region_requirements: &Option<ClosureRegionRequirements<'_>>,
     errors_buffer: &mut Vec<Diagnostic>,
 ) {
     let tcx = infcx.tcx;
@@ -322,7 +322,7 @@
 }
 
 fn for_each_region_constraint(
-    closure_region_requirements: &ClosureRegionRequirements,
+    closure_region_requirements: &ClosureRegionRequirements<'_>,
     with_msg: &mut dyn FnMut(&str) -> io::Result<()>,
 ) -> io::Result<()> {
     for req in &closure_region_requirements.outlives_requirements {
diff --git a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/mod.rs b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/mod.rs
index 550668a..3498e34 100644
--- a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/mod.rs
+++ b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/mod.rs
@@ -1,8 +1,9 @@
-use borrow_check::nll::constraints::OutlivesConstraint;
-use borrow_check::nll::region_infer::RegionInferenceContext;
-use borrow_check::nll::type_check::Locations;
-use borrow_check::nll::universal_regions::DefiningTy;
-use borrow_check::nll::ConstraintDescription;
+use crate::borrow_check::nll::constraints::OutlivesConstraint;
+use crate::borrow_check::nll::region_infer::RegionInferenceContext;
+use crate::borrow_check::nll::type_check::Locations;
+use crate::borrow_check::nll::universal_regions::DefiningTy;
+use crate::borrow_check::nll::ConstraintDescription;
+use crate::util::borrowck_errors::{BorrowckErrors, Origin};
 use rustc::hir::def_id::DefId;
 use rustc::infer::error_reporting::nice_region_error::NiceRegionError;
 use rustc::infer::InferCtxt;
@@ -15,7 +16,6 @@
 use syntax::errors::Applicability;
 use syntax::symbol::keywords;
 use syntax_pos::Span;
-use util::borrowck_errors::{BorrowckErrors, Origin};
 
 mod region_name;
 mod var_name;
diff --git a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs
index bff8015..3bb22d3 100644
--- a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs
+++ b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs
@@ -1,7 +1,7 @@
 use std::fmt::{self, Display};
-use borrow_check::nll::region_infer::RegionInferenceContext;
-use borrow_check::nll::universal_regions::DefiningTy;
-use borrow_check::nll::ToRegionVid;
+use crate::borrow_check::nll::region_infer::RegionInferenceContext;
+use crate::borrow_check::nll::universal_regions::DefiningTy;
+use crate::borrow_check::nll::ToRegionVid;
 use rustc::hir;
 use rustc::hir::def_id::DefId;
 use rustc::infer::InferCtxt;
@@ -10,7 +10,7 @@
 use rustc::ty::{self, RegionKind, RegionVid, Ty, TyCtxt};
 use rustc::util::ppaux::RegionHighlightMode;
 use rustc_errors::DiagnosticBuilder;
-use syntax::ast::{Name, DUMMY_NODE_ID};
+use syntax::ast::Name;
 use syntax::symbol::keywords;
 use syntax_pos::Span;
 use syntax_pos::symbol::InternedString;
@@ -109,7 +109,7 @@
 }
 
 impl Display for RegionName {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(f, "{}", self.name)
     }
 }
@@ -293,9 +293,9 @@
         name: &InternedString,
     ) -> Span {
         let scope = error_region.free_region_binding_scope(tcx);
-        let node = tcx.hir().as_local_node_id(scope).unwrap_or(DUMMY_NODE_ID);
+        let node = tcx.hir().as_local_hir_id(scope).unwrap_or(hir::DUMMY_HIR_ID);
 
-        let span = tcx.sess.source_map().def_span(tcx.hir().span(node));
+        let span = tcx.sess.source_map().def_span(tcx.hir().span_by_hir_id(node));
         if let Some(param) = tcx.hir()
             .get_generics(scope)
             .and_then(|generics| generics.get_named(name))
@@ -681,10 +681,13 @@
 
         let (return_span, mir_description) = match tcx.hir().get(mir_node_id) {
             hir::Node::Expr(hir::Expr {
-                node: hir::ExprKind::Closure(_, _, _, span, gen_move),
+                node: hir::ExprKind::Closure(_, return_ty, _, span, gen_move),
                 ..
             }) => (
-                tcx.sess.source_map().end_point(*span),
+                match return_ty.output {
+                    hir::FunctionRetTy::DefaultReturn(_) => tcx.sess.source_map().end_point(*span),
+                    hir::FunctionRetTy::Return(_) => return_ty.output.span(),
+                },
                 if gen_move.is_some() {
                     " of generator"
                 } else {
diff --git a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/var_name.rs b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/var_name.rs
index c2f2e99..f6bbaf2 100644
--- a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/var_name.rs
+++ b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/var_name.rs
@@ -1,5 +1,5 @@
-use borrow_check::nll::region_infer::RegionInferenceContext;
-use borrow_check::nll::ToRegionVid;
+use crate::borrow_check::nll::region_infer::RegionInferenceContext;
+use crate::borrow_check::nll::ToRegionVid;
 use rustc::mir::{Local, Mir};
 use rustc::ty::{RegionVid, TyCtxt};
 use rustc_data_structures::indexed_vec::Idx;
@@ -71,11 +71,10 @@
         upvar_index: usize,
     ) -> (Symbol, Span) {
         let upvar_hir_id = mir.upvar_decls[upvar_index].var_hir_id.assert_crate_local();
-        let upvar_node_id = tcx.hir().hir_to_node_id(upvar_hir_id);
-        debug!("get_upvar_name_and_span_for_region: upvar_node_id={:?}", upvar_node_id);
+        debug!("get_upvar_name_and_span_for_region: upvar_hir_id={:?}", upvar_hir_id);
 
-        let upvar_name = tcx.hir().name(upvar_node_id);
-        let upvar_span = tcx.hir().span(upvar_node_id);
+        let upvar_name = tcx.hir().name_by_hir_id(upvar_hir_id);
+        let upvar_span = tcx.hir().span_by_hir_id(upvar_hir_id);
         debug!("get_upvar_name_and_span_for_region: upvar_name={:?} upvar_span={:?}",
                upvar_name, upvar_span);
 
diff --git a/src/librustc_mir/borrow_check/nll/region_infer/graphviz.rs b/src/librustc_mir/borrow_check/nll/region_infer/graphviz.rs
index 2da158b..cffc66a 100644
--- a/src/librustc_mir/borrow_check/nll/region_infer/graphviz.rs
+++ b/src/librustc_mir/borrow_check/nll/region_infer/graphviz.rs
@@ -3,8 +3,7 @@
 //! data to rendered labels.
 
 use super::*;
-use borrow_check::nll::constraints::OutlivesConstraint;
-use dot;
+use crate::borrow_check::nll::constraints::OutlivesConstraint;
 use std::borrow::Cow;
 use std::io::{self, Write};
 
diff --git a/src/librustc_mir/borrow_check/nll/region_infer/mod.rs b/src/librustc_mir/borrow_check/nll/region_infer/mod.rs
index fee5dc8..7fe6577 100644
--- a/src/librustc_mir/borrow_check/nll/region_infer/mod.rs
+++ b/src/librustc_mir/borrow_check/nll/region_infer/mod.rs
@@ -1,9 +1,11 @@
 use super::universal_regions::UniversalRegions;
-use borrow_check::nll::constraints::graph::NormalConstraintGraph;
-use borrow_check::nll::constraints::{ConstraintSccIndex, ConstraintSet, OutlivesConstraint};
-use borrow_check::nll::region_infer::values::{PlaceholderIndices, RegionElement, ToElementIndex};
-use borrow_check::nll::type_check::free_region_relations::UniversalRegionRelations;
-use borrow_check::nll::type_check::Locations;
+use crate::borrow_check::nll::constraints::graph::NormalConstraintGraph;
+use crate::borrow_check::nll::constraints::{ConstraintSccIndex, ConstraintSet, OutlivesConstraint};
+use crate::borrow_check::nll::region_infer::values::{
+    PlaceholderIndices, RegionElement, ToElementIndex
+};
+use crate::borrow_check::nll::type_check::free_region_relations::UniversalRegionRelations;
+use crate::borrow_check::nll::type_check::Locations;
 use rustc::hir::def_id::DefId;
 use rustc::infer::canonical::QueryRegionConstraint;
 use rustc::infer::region_constraints::{GenericKind, VarInfos, VerifyBound};
diff --git a/src/librustc_mir/borrow_check/nll/type_check/constraint_conversion.rs b/src/librustc_mir/borrow_check/nll/type_check/constraint_conversion.rs
index b7555e5..1a72205 100644
--- a/src/librustc_mir/borrow_check/nll/type_check/constraint_conversion.rs
+++ b/src/librustc_mir/borrow_check/nll/type_check/constraint_conversion.rs
@@ -1,8 +1,8 @@
-use borrow_check::nll::constraints::OutlivesConstraint;
-use borrow_check::nll::region_infer::TypeTest;
-use borrow_check::nll::type_check::{Locations, MirTypeckRegionConstraints};
-use borrow_check::nll::universal_regions::UniversalRegions;
-use borrow_check::nll::ToRegionVid;
+use crate::borrow_check::nll::constraints::OutlivesConstraint;
+use crate::borrow_check::nll::region_infer::TypeTest;
+use crate::borrow_check::nll::type_check::{Locations, MirTypeckRegionConstraints};
+use crate::borrow_check::nll::universal_regions::UniversalRegions;
+use crate::borrow_check::nll::ToRegionVid;
 use rustc::infer::canonical::QueryRegionConstraint;
 use rustc::infer::outlives::env::RegionBoundPairs;
 use rustc::infer::outlives::obligations::{TypeOutlives, TypeOutlivesDelegate};
diff --git a/src/librustc_mir/borrow_check/nll/type_check/free_region_relations.rs b/src/librustc_mir/borrow_check/nll/type_check/free_region_relations.rs
index b19dc90..f549aea 100644
--- a/src/librustc_mir/borrow_check/nll/type_check/free_region_relations.rs
+++ b/src/librustc_mir/borrow_check/nll/type_check/free_region_relations.rs
@@ -1,7 +1,7 @@
-use borrow_check::nll::type_check::constraint_conversion;
-use borrow_check::nll::type_check::{Locations, MirTypeckRegionConstraints};
-use borrow_check::nll::universal_regions::UniversalRegions;
-use borrow_check::nll::ToRegionVid;
+use crate::borrow_check::nll::type_check::constraint_conversion;
+use crate::borrow_check::nll::type_check::{Locations, MirTypeckRegionConstraints};
+use crate::borrow_check::nll::universal_regions::UniversalRegions;
+use crate::borrow_check::nll::ToRegionVid;
 use rustc::infer::canonical::QueryRegionConstraint;
 use rustc::infer::outlives::free_region_map::FreeRegionRelations;
 use rustc::infer::region_constraints::GenericKind;
diff --git a/src/librustc_mir/borrow_check/nll/type_check/input_output.rs b/src/librustc_mir/borrow_check/nll/type_check/input_output.rs
index ef0f7e1..50828c2 100644
--- a/src/librustc_mir/borrow_check/nll/type_check/input_output.rs
+++ b/src/librustc_mir/borrow_check/nll/type_check/input_output.rs
@@ -7,7 +7,7 @@
 //! `RETURN_PLACE` the MIR arguments) are always fully normalized (and
 //! contain revealed `impl Trait` values).
 
-use borrow_check::nll::universal_regions::UniversalRegions;
+use crate::borrow_check::nll::universal_regions::UniversalRegions;
 use rustc::infer::LateBoundRegionConversionTime;
 use rustc::mir::*;
 use rustc::ty::Ty;
diff --git a/src/librustc_mir/borrow_check/nll/type_check/liveness/liveness_map.rs b/src/librustc_mir/borrow_check/nll/type_check/liveness/liveness_map.rs
index dda74e6..5e2e440 100644
--- a/src/librustc_mir/borrow_check/nll/type_check/liveness/liveness_map.rs
+++ b/src/librustc_mir/borrow_check/nll/type_check/liveness/liveness_map.rs
@@ -6,13 +6,13 @@
 //! liveness code so that it only operates over variables with regions in their
 //! types, instead of all variables.
 
-use borrow_check::nll::ToRegionVid;
-use borrow_check::nll::facts::{AllFacts, AllFactsExt};
+use crate::borrow_check::nll::ToRegionVid;
+use crate::borrow_check::nll::facts::{AllFacts, AllFactsExt};
+use crate::util::liveness::LiveVariableMap;
 use rustc::mir::{Local, Mir};
 use rustc::ty::{RegionVid, TyCtxt};
 use rustc_data_structures::fx::FxHashSet;
 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
-use util::liveness::LiveVariableMap;
 
 /// Map between Local and LiveVar indices: the purpose of this
 /// map is to define the subset of local variables for which we need
diff --git a/src/librustc_mir/borrow_check/nll/type_check/liveness/local_use_map.rs b/src/librustc_mir/borrow_check/nll/type_check/liveness/local_use_map.rs
index 3f13cc8..e9765d2 100644
--- a/src/librustc_mir/borrow_check/nll/type_check/liveness/local_use_map.rs
+++ b/src/librustc_mir/borrow_check/nll/type_check/liveness/local_use_map.rs
@@ -1,10 +1,10 @@
-use borrow_check::nll::region_infer::values::{PointIndex, RegionValueElements};
-use borrow_check::nll::type_check::liveness::liveness_map::{LiveVar, NllLivenessMap};
+use crate::borrow_check::nll::region_infer::values::{PointIndex, RegionValueElements};
+use crate::borrow_check::nll::type_check::liveness::liveness_map::{LiveVar, NllLivenessMap};
+use crate::util::liveness::{categorize, DefUse, LiveVariableMap};
 use rustc::mir::visit::{PlaceContext, Visitor};
 use rustc::mir::{Local, Location, Mir};
 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
 use rustc_data_structures::vec_linked_list as vll;
-use util::liveness::{categorize, DefUse, LiveVariableMap};
 
 /// A map that cross references each local with the locations where it
 /// is defined (assigned), used, or dropped. Used during liveness
diff --git a/src/librustc_mir/borrow_check/nll/type_check/liveness/mod.rs b/src/librustc_mir/borrow_check/nll/type_check/liveness/mod.rs
index 633695a..a5510ba 100644
--- a/src/librustc_mir/borrow_check/nll/type_check/liveness/mod.rs
+++ b/src/librustc_mir/borrow_check/nll/type_check/liveness/mod.rs
@@ -1,11 +1,11 @@
-use borrow_check::location::LocationTable;
-use borrow_check::nll::region_infer::values::RegionValueElements;
-use borrow_check::nll::constraints::ConstraintSet;
-use borrow_check::nll::NllLivenessMap;
-use borrow_check::nll::universal_regions::UniversalRegions;
-use dataflow::move_paths::MoveData;
-use dataflow::MaybeInitializedPlaces;
-use dataflow::FlowAtLocation;
+use crate::borrow_check::location::LocationTable;
+use crate::borrow_check::nll::region_infer::values::RegionValueElements;
+use crate::borrow_check::nll::constraints::ConstraintSet;
+use crate::borrow_check::nll::NllLivenessMap;
+use crate::borrow_check::nll::universal_regions::UniversalRegions;
+use crate::dataflow::move_paths::MoveData;
+use crate::dataflow::MaybeInitializedPlaces;
+use crate::dataflow::FlowAtLocation;
 use rustc::mir::Mir;
 use rustc::ty::RegionVid;
 use rustc_data_structures::fx::FxHashSet;
diff --git a/src/librustc_mir/borrow_check/nll/type_check/liveness/trace.rs b/src/librustc_mir/borrow_check/nll/type_check/liveness/trace.rs
index 77e8dd9..d058be0 100644
--- a/src/librustc_mir/borrow_check/nll/type_check/liveness/trace.rs
+++ b/src/librustc_mir/borrow_check/nll/type_check/liveness/trace.rs
@@ -1,12 +1,13 @@
-use borrow_check::location::LocationTable;
-use borrow_check::nll::region_infer::values::{self, PointIndex, RegionValueElements};
-use borrow_check::nll::type_check::liveness::liveness_map::{LiveVar, NllLivenessMap};
-use borrow_check::nll::type_check::liveness::local_use_map::LocalUseMap;
-use borrow_check::nll::type_check::NormalizeLocation;
-use borrow_check::nll::type_check::TypeChecker;
-use dataflow::move_paths::indexes::MovePathIndex;
-use dataflow::move_paths::MoveData;
-use dataflow::{FlowAtLocation, FlowsAtLocation, MaybeInitializedPlaces};
+use crate::borrow_check::location::LocationTable;
+use crate::borrow_check::nll::region_infer::values::{self, PointIndex, RegionValueElements};
+use crate::borrow_check::nll::type_check::liveness::liveness_map::{LiveVar, NllLivenessMap};
+use crate::borrow_check::nll::type_check::liveness::local_use_map::LocalUseMap;
+use crate::borrow_check::nll::type_check::NormalizeLocation;
+use crate::borrow_check::nll::type_check::TypeChecker;
+use crate::dataflow::move_paths::indexes::MovePathIndex;
+use crate::dataflow::move_paths::MoveData;
+use crate::dataflow::{FlowAtLocation, FlowsAtLocation, MaybeInitializedPlaces};
+use crate::util::liveness::LiveVariableMap;
 use rustc::infer::canonical::QueryRegionConstraint;
 use rustc::mir::{BasicBlock, ConstraintCategory, Local, Location, Mir};
 use rustc::traits::query::dropck_outlives::DropckOutlivesResult;
@@ -16,7 +17,6 @@
 use rustc_data_structures::bit_set::HybridBitSet;
 use rustc_data_structures::fx::FxHashMap;
 use std::rc::Rc;
-use util::liveness::LiveVariableMap;
 
 /// This is the heart of the liveness computation. For each variable X
 /// that requires a liveness computation, it walks over all the uses
diff --git a/src/librustc_mir/borrow_check/nll/type_check/mod.rs b/src/librustc_mir/borrow_check/nll/type_check/mod.rs
index 3e6aa35..add07b1 100644
--- a/src/librustc_mir/borrow_check/nll/type_check/mod.rs
+++ b/src/librustc_mir/borrow_check/nll/type_check/mod.rs
@@ -2,24 +2,25 @@
 
 #![allow(unreachable_code)]
 
-use borrow_check::borrow_set::BorrowSet;
-use borrow_check::location::LocationTable;
-use borrow_check::nll::constraints::{ConstraintSet, OutlivesConstraint};
-use borrow_check::nll::facts::AllFacts;
-use borrow_check::nll::region_infer::values::LivenessValues;
-use borrow_check::nll::region_infer::values::PlaceholderIndex;
-use borrow_check::nll::region_infer::values::PlaceholderIndices;
-use borrow_check::nll::region_infer::values::RegionValueElements;
-use borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
-use borrow_check::nll::renumber;
-use borrow_check::nll::type_check::free_region_relations::{
+use crate::borrow_check::borrow_set::BorrowSet;
+use crate::borrow_check::location::LocationTable;
+use crate::borrow_check::nll::constraints::{ConstraintSet, OutlivesConstraint};
+use crate::borrow_check::nll::facts::AllFacts;
+use crate::borrow_check::nll::region_infer::values::LivenessValues;
+use crate::borrow_check::nll::region_infer::values::PlaceholderIndex;
+use crate::borrow_check::nll::region_infer::values::PlaceholderIndices;
+use crate::borrow_check::nll::region_infer::values::RegionValueElements;
+use crate::borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
+use crate::borrow_check::nll::renumber;
+use crate::borrow_check::nll::type_check::free_region_relations::{
     CreateResult, UniversalRegionRelations,
 };
-use borrow_check::nll::universal_regions::{DefiningTy, UniversalRegions};
-use borrow_check::nll::ToRegionVid;
-use dataflow::move_paths::MoveData;
-use dataflow::FlowAtLocation;
-use dataflow::MaybeInitializedPlaces;
+use crate::borrow_check::nll::universal_regions::{DefiningTy, UniversalRegions};
+use crate::borrow_check::nll::ToRegionVid;
+use crate::dataflow::move_paths::MoveData;
+use crate::dataflow::FlowAtLocation;
+use crate::dataflow::MaybeInitializedPlaces;
+use crate::transform::{MirPass, MirSource};
 use either::Either;
 use rustc::hir;
 use rustc::hir::def_id::DefId;
@@ -46,7 +47,6 @@
 use std::rc::Rc;
 use std::{fmt, iter};
 use syntax_pos::{Span, DUMMY_SP};
-use transform::{MirPass, MirSource};
 
 macro_rules! span_mirbug {
     ($context:expr, $elem:expr, $($message:tt)*) => ({
@@ -210,7 +210,7 @@
     extra(&mut checker)
 }
 
-fn translate_outlives_facts(cx: &mut BorrowCheckContext) {
+fn translate_outlives_facts(cx: &mut BorrowCheckContext<'_, '_>) {
     if let Some(facts) = cx.all_facts {
         let location_table = cx.location_table;
         facts
@@ -235,7 +235,7 @@
     }
 }
 
-fn mirbug(tcx: TyCtxt, span: Span, msg: &str) {
+fn mirbug(tcx: TyCtxt<'_, '_, '_>, span: Span, msg: &str) {
     // We sometimes see MIR failures (notably predicate failures) due to
     // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
     // to avoid reporting bugs in those cases.
@@ -266,7 +266,7 @@
         }
     }
 
-    fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
+    fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext<'_>, location: Location) {
         self.sanitize_place(place, location, context);
     }
 
@@ -447,7 +447,7 @@
         &mut self,
         place: &Place<'tcx>,
         location: Location,
-        context: PlaceContext,
+        context: PlaceContext<'_>,
     ) -> PlaceTy<'tcx> {
         debug!("sanitize_place: {:?}", place);
         let place_ty = match *place {
@@ -2427,8 +2427,13 @@
 pub struct TypeckMir;
 
 impl MirPass for TypeckMir {
-    fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, src: MirSource, mir: &mut Mir<'tcx>) {
-        let def_id = src.def_id;
+    fn run_pass<'a, 'tcx>(
+        &self,
+        tcx: TyCtxt<'a, 'tcx, 'tcx>,
+        src: MirSource<'tcx>,
+        mir: &mut Mir<'tcx>,
+    ) {
+        let def_id = src.def_id();
         debug!("run_pass: {:?}", def_id);
 
         // When NLL is enabled, the borrow checker runs the typeck
diff --git a/src/librustc_mir/borrow_check/nll/type_check/relate_tys.rs b/src/librustc_mir/borrow_check/nll/type_check/relate_tys.rs
index 74ad7d9..1748e30 100644
--- a/src/librustc_mir/borrow_check/nll/type_check/relate_tys.rs
+++ b/src/librustc_mir/borrow_check/nll/type_check/relate_tys.rs
@@ -1,5 +1,5 @@
-use borrow_check::nll::constraints::OutlivesConstraint;
-use borrow_check::nll::type_check::{BorrowCheckContext, Locations};
+use crate::borrow_check::nll::constraints::OutlivesConstraint;
+use crate::borrow_check::nll::type_check::{BorrowCheckContext, Locations};
 use rustc::infer::nll_relate::{TypeRelating, TypeRelatingDelegate, NormalizationStrategy};
 use rustc::infer::{InferCtxt, NLLRegionVariableOrigin};
 use rustc::mir::ConstraintCategory;
diff --git a/src/librustc_mir/borrow_check/nll/universal_regions.rs b/src/librustc_mir/borrow_check/nll/universal_regions.rs
index 0a214e6..ad4444e 100644
--- a/src/librustc_mir/borrow_check/nll/universal_regions.rs
+++ b/src/librustc_mir/borrow_check/nll/universal_regions.rs
@@ -771,9 +771,8 @@
                 owner: fn_def_id.index,
                 local_id: *late_bound,
             };
-            let region_node_id = tcx.hir().hir_to_node_id(hir_id);
-            let name = tcx.hir().name(region_node_id).as_interned_str();
-            let region_def_id = tcx.hir().local_def_id(region_node_id);
+            let name = tcx.hir().name_by_hir_id(hir_id).as_interned_str();
+            let region_def_id = tcx.hir().local_def_id_from_hir_id(hir_id);
             let liberated_region = tcx.mk_region(ty::ReFree(ty::FreeRegion {
                 scope: fn_def_id,
                 bound_region: ty::BoundRegion::BrNamed(region_def_id, name),
diff --git a/src/librustc_mir/borrow_check/path_utils.rs b/src/librustc_mir/borrow_check/path_utils.rs
index 6875ace..1cea9f6 100644
--- a/src/librustc_mir/borrow_check/path_utils.rs
+++ b/src/librustc_mir/borrow_check/path_utils.rs
@@ -1,8 +1,8 @@
-use borrow_check::borrow_set::{BorrowSet, BorrowData, TwoPhaseActivation};
-use borrow_check::places_conflict;
-use borrow_check::Context;
-use borrow_check::AccessDepth;
-use dataflow::indexes::BorrowIndex;
+use crate::borrow_check::borrow_set::{BorrowSet, BorrowData, TwoPhaseActivation};
+use crate::borrow_check::places_conflict;
+use crate::borrow_check::Context;
+use crate::borrow_check::AccessDepth;
+use crate::dataflow::indexes::BorrowIndex;
 use rustc::mir::{BasicBlock, Location, Mir, Place};
 use rustc::mir::{ProjectionElem, BorrowKind};
 use rustc::ty::TyCtxt;
diff --git a/src/librustc_mir/borrow_check/place_ext.rs b/src/librustc_mir/borrow_check/place_ext.rs
index 4d0b25b..bad236a 100644
--- a/src/librustc_mir/borrow_check/place_ext.rs
+++ b/src/librustc_mir/borrow_check/place_ext.rs
@@ -2,7 +2,7 @@
 use rustc::mir::ProjectionElem;
 use rustc::mir::{Local, Mir, Place, Mutability};
 use rustc::ty::{self, TyCtxt};
-use borrow_check::borrow_set::LocalsStateAtExit;
+use crate::borrow_check::borrow_set::LocalsStateAtExit;
 
 /// Extension methods for the `Place` type.
 crate trait PlaceExt<'tcx> {
diff --git a/src/librustc_mir/borrow_check/places_conflict.rs b/src/librustc_mir/borrow_check/places_conflict.rs
index ac7182a..cd33f22 100644
--- a/src/librustc_mir/borrow_check/places_conflict.rs
+++ b/src/librustc_mir/borrow_check/places_conflict.rs
@@ -1,6 +1,6 @@
-use borrow_check::ArtificialField;
-use borrow_check::Overlap;
-use borrow_check::{Deep, Shallow, AccessDepth};
+use crate::borrow_check::ArtificialField;
+use crate::borrow_check::Overlap;
+use crate::borrow_check::{Deep, Shallow, AccessDepth};
 use rustc::hir;
 use rustc::mir::{BorrowKind, Mir, Place};
 use rustc::mir::{Projection, ProjectionElem};
diff --git a/src/librustc_mir/borrow_check/used_muts.rs b/src/librustc_mir/borrow_check/used_muts.rs
index 0ff7ff4..8c7359b 100644
--- a/src/librustc_mir/borrow_check/used_muts.rs
+++ b/src/librustc_mir/borrow_check/used_muts.rs
@@ -3,7 +3,7 @@
 
 use rustc_data_structures::fx::FxHashSet;
 
-use borrow_check::MirBorrowckCtxt;
+use crate::borrow_check::MirBorrowckCtxt;
 
 impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> {
     /// Walks the MIR adding to the set of `used_mut` locals that will be ignored for the purposes
diff --git a/src/librustc_mir/build/block.rs b/src/librustc_mir/build/block.rs
index f3d89a7..7d93e13 100644
--- a/src/librustc_mir/build/block.rs
+++ b/src/librustc_mir/build/block.rs
@@ -1,7 +1,7 @@
-use build::{BlockAnd, BlockAndExtension, BlockFrame, Builder};
-use build::ForGuard::OutsideGuard;
-use build::matches::ArmHasGuard;
-use hair::*;
+use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder};
+use crate::build::ForGuard::OutsideGuard;
+use crate::build::matches::ArmHasGuard;
+use crate::hair::*;
 use rustc::mir::*;
 use rustc::hir;
 use syntax_pos::Span;
diff --git a/src/librustc_mir/build/cfg.rs b/src/librustc_mir/build/cfg.rs
index a9e468d..778d1e7 100644
--- a/src/librustc_mir/build/cfg.rs
+++ b/src/librustc_mir/build/cfg.rs
@@ -1,6 +1,6 @@
 //! Routines for manipulating the control-flow graph.
 
-use build::CFG;
+use crate::build::CFG;
 use rustc::mir::*;
 
 impl<'tcx> CFG<'tcx> {
diff --git a/src/librustc_mir/build/expr/as_constant.rs b/src/librustc_mir/build/expr/as_constant.rs
index 31e0c0d..6146681 100644
--- a/src/librustc_mir/build/expr/as_constant.rs
+++ b/src/librustc_mir/build/expr/as_constant.rs
@@ -1,7 +1,7 @@
 //! See docs in build/expr/mod.rs
 
-use build::Builder;
-use hair::*;
+use crate::build::Builder;
+use crate::hair::*;
 use rustc::mir::*;
 use rustc::ty::CanonicalUserTypeAnnotation;
 
diff --git a/src/librustc_mir/build/expr/as_operand.rs b/src/librustc_mir/build/expr/as_operand.rs
index 1f65357..38fae85 100644
--- a/src/librustc_mir/build/expr/as_operand.rs
+++ b/src/librustc_mir/build/expr/as_operand.rs
@@ -1,8 +1,8 @@
 //! See docs in build/expr/mod.rs
 
-use build::expr::category::Category;
-use build::{BlockAnd, BlockAndExtension, Builder};
-use hair::*;
+use crate::build::expr::category::Category;
+use crate::build::{BlockAnd, BlockAndExtension, Builder};
+use crate::hair::*;
 use rustc::middle::region;
 use rustc::mir::*;
 
diff --git a/src/librustc_mir/build/expr/as_place.rs b/src/librustc_mir/build/expr/as_place.rs
index 6bd61ab..ed44419 100644
--- a/src/librustc_mir/build/expr/as_place.rs
+++ b/src/librustc_mir/build/expr/as_place.rs
@@ -1,9 +1,9 @@
 //! See docs in build/expr/mod.rs
 
-use build::expr::category::Category;
-use build::ForGuard::{OutsideGuard, RefWithinGuard};
-use build::{BlockAnd, BlockAndExtension, Builder};
-use hair::*;
+use crate::build::expr::category::Category;
+use crate::build::ForGuard::{OutsideGuard, RefWithinGuard};
+use crate::build::{BlockAnd, BlockAndExtension, Builder};
+use crate::hair::*;
 use rustc::mir::interpret::EvalErrorKind::BoundsCheck;
 use rustc::mir::*;
 use rustc::ty::{CanonicalUserTypeAnnotation, Variance};
diff --git a/src/librustc_mir/build/expr/as_rvalue.rs b/src/librustc_mir/build/expr/as_rvalue.rs
index 3de2f47..88dbd93 100644
--- a/src/librustc_mir/build/expr/as_rvalue.rs
+++ b/src/librustc_mir/build/expr/as_rvalue.rs
@@ -3,9 +3,9 @@
 use rustc_data_structures::fx::FxHashMap;
 use rustc_data_structures::indexed_vec::Idx;
 
-use build::expr::category::{Category, RvalueFunc};
-use build::{BlockAnd, BlockAndExtension, Builder};
-use hair::*;
+use crate::build::expr::category::{Category, RvalueFunc};
+use crate::build::{BlockAnd, BlockAndExtension, Builder};
+use crate::hair::*;
 use rustc::middle::region;
 use rustc::mir::interpret::EvalErrorKind;
 use rustc::mir::*;
@@ -268,7 +268,7 @@
                             span: expr_span,
                             ty: this.hir.tcx().types.u32,
                             user_ty: None,
-                            literal: this.hir.tcx().intern_lazy_const(ty::LazyConst::Evaluated(
+                            literal: this.hir.tcx().mk_lazy_const(ty::LazyConst::Evaluated(
                                 ty::Const::from_bits(
                                     this.hir.tcx(),
                                     0,
diff --git a/src/librustc_mir/build/expr/as_temp.rs b/src/librustc_mir/build/expr/as_temp.rs
index df271ff..efa1a48 100644
--- a/src/librustc_mir/build/expr/as_temp.rs
+++ b/src/librustc_mir/build/expr/as_temp.rs
@@ -1,7 +1,7 @@
 //! See docs in build/expr/mod.rs
 
-use build::{BlockAnd, BlockAndExtension, Builder};
-use hair::*;
+use crate::build::{BlockAnd, BlockAndExtension, Builder};
+use crate::hair::*;
 use rustc::middle::region;
 use rustc::mir::*;
 
diff --git a/src/librustc_mir/build/expr/category.rs b/src/librustc_mir/build/expr/category.rs
index 53f84a4..ca7d435 100644
--- a/src/librustc_mir/build/expr/category.rs
+++ b/src/librustc_mir/build/expr/category.rs
@@ -1,4 +1,4 @@
-use hair::*;
+use crate::hair::*;
 
 #[derive(Debug, PartialEq)]
 pub enum Category {
diff --git a/src/librustc_mir/build/expr/into.rs b/src/librustc_mir/build/expr/into.rs
index 2ffff68..05231bc 100644
--- a/src/librustc_mir/build/expr/into.rs
+++ b/src/librustc_mir/build/expr/into.rs
@@ -1,8 +1,8 @@
 //! See docs in build/expr/mod.rs
 
-use build::expr::category::{Category, RvalueFunc};
-use build::{BlockAnd, BlockAndExtension, BlockFrame, Builder};
-use hair::*;
+use crate::build::expr::category::{Category, RvalueFunc};
+use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder};
+use crate::hair::*;
 use rustc::mir::*;
 use rustc::ty;
 
diff --git a/src/librustc_mir/build/expr/stmt.rs b/src/librustc_mir/build/expr/stmt.rs
index 1cbc605..aadc236 100644
--- a/src/librustc_mir/build/expr/stmt.rs
+++ b/src/librustc_mir/build/expr/stmt.rs
@@ -1,6 +1,6 @@
-use build::scope::BreakableScope;
-use build::{BlockAnd, BlockAndExtension, BlockFrame, Builder};
-use hair::*;
+use crate::build::scope::BreakableScope;
+use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder};
+use crate::hair::*;
 use rustc::mir::*;
 
 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
diff --git a/src/librustc_mir/build/into.rs b/src/librustc_mir/build/into.rs
index 1b29126..67b6540 100644
--- a/src/librustc_mir/build/into.rs
+++ b/src/librustc_mir/build/into.rs
@@ -4,11 +4,11 @@
 //! wrapped up as expressions (e.g., blocks). To make this ergonomic, we use this
 //! latter `EvalInto` trait.
 
-use build::{BlockAnd, Builder};
-use hair::*;
+use crate::build::{BlockAnd, Builder};
+use crate::hair::*;
 use rustc::mir::*;
 
-pub(in build) trait EvalInto<'tcx> {
+pub(in crate::build) trait EvalInto<'tcx> {
     fn eval_into<'a, 'gcx>(self,
                            builder: &mut Builder<'a, 'gcx, 'tcx>,
                            destination: &Place<'tcx>,
diff --git a/src/librustc_mir/build/matches/mod.rs b/src/librustc_mir/build/matches/mod.rs
index 2f1e8c0..cf051ba 100644
--- a/src/librustc_mir/build/matches/mod.rs
+++ b/src/librustc_mir/build/matches/mod.rs
@@ -3,11 +3,11 @@
 //! includes the high-level algorithm, the submodules contain the
 //! details.
 
-use build::scope::{CachedBlock, DropKind};
-use build::ForGuard::{self, OutsideGuard, RefWithinGuard, ValWithinGuard};
-use build::{BlockAnd, BlockAndExtension, Builder};
-use build::{GuardFrame, GuardFrameLocal, LocalsForNode};
-use hair::*;
+use crate::build::scope::{CachedBlock, DropKind};
+use crate::build::ForGuard::{self, OutsideGuard, RefWithinGuard, ValWithinGuard};
+use crate::build::{BlockAnd, BlockAndExtension, Builder};
+use crate::build::{GuardFrame, GuardFrameLocal, LocalsForNode};
+use crate::hair::*;
 use rustc::mir::*;
 use rustc::ty::{self, CanonicalUserTypeAnnotation, Ty};
 use rustc::ty::layout::VariantIdx;
diff --git a/src/librustc_mir/build/matches/simplify.rs b/src/librustc_mir/build/matches/simplify.rs
index c219fd2..6be9ccb 100644
--- a/src/librustc_mir/build/matches/simplify.rs
+++ b/src/librustc_mir/build/matches/simplify.rs
@@ -12,9 +12,9 @@
 //! sort of test: for example, testing which variant an enum is, or
 //! testing a value against a constant.
 
-use build::Builder;
-use build::matches::{Ascription, Binding, MatchPair, Candidate};
-use hair::*;
+use crate::build::Builder;
+use crate::build::matches::{Ascription, Binding, MatchPair, Candidate};
+use crate::hair::*;
 use rustc::ty;
 use rustc::ty::layout::{Integer, IntegerExt, Size};
 use syntax::attr::{SignedInt, UnsignedInt};
diff --git a/src/librustc_mir/build/matches/test.rs b/src/librustc_mir/build/matches/test.rs
index 696c173..efac4457 100644
--- a/src/librustc_mir/build/matches/test.rs
+++ b/src/librustc_mir/build/matches/test.rs
@@ -5,10 +5,10 @@
 // identify what tests are needed, perform the tests, and then filter
 // the candidates based on the result.
 
-use build::Builder;
-use build::matches::{Candidate, MatchPair, Test, TestKind};
-use hair::*;
-use hair::pattern::compare_const_vals;
+use crate::build::Builder;
+use crate::build::matches::{Candidate, MatchPair, Test, TestKind};
+use crate::hair::*;
+use crate::hair::pattern::compare_const_vals;
 use rustc_data_structures::bit_set::BitSet;
 use rustc_data_structures::fx::FxHashMap;
 use rustc::ty::{self, Ty};
@@ -302,7 +302,7 @@
                     }
                     let eq_def_id = self.hir.tcx().lang_items().eq_trait().unwrap();
                     let (mty, method) = self.hir.trait_method(eq_def_id, "eq", ty, &[ty.into()]);
-                    let method = self.hir.tcx().intern_lazy_const(ty::LazyConst::Evaluated(method));
+                    let method = self.hir.tcx().mk_lazy_const(ty::LazyConst::Evaluated(method));
 
                     let re_erased = self.hir.tcx().types.re_erased;
                     // take the argument by reference
diff --git a/src/librustc_mir/build/matches/util.rs b/src/librustc_mir/build/matches/util.rs
index b5a1a38..ed12c1b 100644
--- a/src/librustc_mir/build/matches/util.rs
+++ b/src/librustc_mir/build/matches/util.rs
@@ -1,6 +1,6 @@
-use build::Builder;
-use build::matches::MatchPair;
-use hair::*;
+use crate::build::Builder;
+use crate::build::matches::MatchPair;
+use crate::hair::*;
 use rustc::mir::*;
 use std::u32;
 use std::convert::TryInto;
diff --git a/src/librustc_mir/build/misc.rs b/src/librustc_mir/build/misc.rs
index c849c02..096020b 100644
--- a/src/librustc_mir/build/misc.rs
+++ b/src/librustc_mir/build/misc.rs
@@ -1,7 +1,7 @@
 //! Miscellaneous builder routines that are not specific to building any particular
 //! kind of thing.
 
-use build::Builder;
+use crate::build::Builder;
 
 use rustc::ty::{self, Ty};
 
@@ -33,7 +33,7 @@
             span,
             ty,
             user_ty: None,
-            literal: self.hir.tcx().intern_lazy_const(ty::LazyConst::Evaluated(literal)),
+            literal: self.hir.tcx().mk_lazy_const(ty::LazyConst::Evaluated(literal)),
         };
         Operand::Constant(constant)
     }
diff --git a/src/librustc_mir/build/mod.rs b/src/librustc_mir/build/mod.rs
index f38648f..ed35fb2 100644
--- a/src/librustc_mir/build/mod.rs
+++ b/src/librustc_mir/build/mod.rs
@@ -1,7 +1,10 @@
-use build;
-use build::scope::{CachedBlock, DropKind};
-use hair::cx::Cx;
-use hair::{LintLevel, BindingMode, PatternKind};
+use crate::build;
+use crate::build::scope::{CachedBlock, DropKind};
+use crate::hair::cx::Cx;
+use crate::hair::{LintLevel, BindingMode, PatternKind};
+use crate::shim;
+use crate::transform::MirSource;
+use crate::util as mir_util;
 use rustc::hir;
 use rustc::hir::Node;
 use rustc::hir::def_id::DefId;
@@ -13,7 +16,6 @@
 use rustc::util::nodemap::NodeMap;
 use rustc_target::spec::PanicStrategy;
 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
-use shim;
 use std::mem;
 use std::u32;
 use rustc_target::spec::abi::Abi;
@@ -21,8 +23,6 @@
 use syntax::attr::{self, UnwindAttr};
 use syntax::symbol::keywords;
 use syntax_pos::Span;
-use transform::MirSource;
-use util as mir_util;
 
 use super::lints;
 
@@ -64,8 +64,8 @@
         ) => {
             (*body_id, ty.span)
         }
-        Node::AnonConst(hir::AnonConst { body, id, .. }) => {
-            (*body, tcx.hir().span(*id))
+        Node::AnonConst(hir::AnonConst { body, hir_id, .. }) => {
+            (*body, tcx.hir().span_by_hir_id(*hir_id))
         }
 
         _ => span_bug!(tcx.hir().span(id), "can't build MIR for {:?}", def_id),
@@ -114,7 +114,7 @@
                         let self_arg;
                         if let Some(ref fn_decl) = tcx.hir().fn_decl(owner_id) {
                             let ty_hir_id = fn_decl.inputs[index].hir_id;
-                            let ty_span = tcx.hir().span(tcx.hir().hir_to_node_id(ty_hir_id));
+                            let ty_span = tcx.hir().span_by_hir_id(ty_hir_id);
                             opt_ty_info = Some(ty_span);
                             self_arg = if index == 0 && fn_decl.implicit_self.has_implicit_self() {
                                 match fn_decl.implicit_self {
@@ -161,7 +161,7 @@
         };
         globalizer.visit_mir(&mut mir);
         let mir = unsafe {
-            mem::transmute::<Mir, Mir<'tcx>>(mir)
+            mem::transmute::<Mir<'_>, Mir<'tcx>>(mir)
         };
 
         mir_util::dump_mir(tcx, None, "mir_map", &0,
@@ -241,7 +241,7 @@
             };
             globalizer.visit_mir(&mut mir);
             let mir = unsafe {
-                mem::transmute::<Mir, Mir<'tcx>>(mir)
+                mem::transmute::<Mir<'_>, Mir<'tcx>>(mir)
             };
 
             mir_util::dump_mir(tcx, None, "mir_map", &0,
diff --git a/src/librustc_mir/build/scope.rs b/src/librustc_mir/build/scope.rs
index 78abba5..3872f5d 100644
--- a/src/librustc_mir/build/scope.rs
+++ b/src/librustc_mir/build/scope.rs
@@ -77,8 +77,8 @@
 
 */
 
-use build::{BlockAnd, BlockAndExtension, Builder, CFG};
-use hair::LintLevel;
+use crate::build::{BlockAnd, BlockAndExtension, Builder, CFG};
+use crate::hair::LintLevel;
 use rustc::middle::region;
 use rustc::ty::Ty;
 use rustc::hir;
diff --git a/src/librustc_mir/const_eval.rs b/src/librustc_mir/const_eval.rs
index f83a930..d1b4486 100644
--- a/src/librustc_mir/const_eval.rs
+++ b/src/librustc_mir/const_eval.rs
@@ -190,7 +190,7 @@
 }
 
 impl fmt::Display for ConstEvalError {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         use self::ConstEvalError::*;
         match *self {
             NeedsRfc(ref msg) => {
diff --git a/src/librustc_mir/dataflow/at_location.rs b/src/librustc_mir/dataflow/at_location.rs
index 375bc4f..d0b9fbc 100644
--- a/src/librustc_mir/dataflow/at_location.rs
+++ b/src/librustc_mir/dataflow/at_location.rs
@@ -4,8 +4,8 @@
 use rustc::mir::{BasicBlock, Location};
 use rustc_data_structures::bit_set::{BitIter, BitSet, HybridBitSet};
 
-use dataflow::{BitDenotation, BlockSets, DataflowResults};
-use dataflow::move_paths::{HasMoveData, MovePathIndex};
+use crate::dataflow::{BitDenotation, BlockSets, DataflowResults};
+use crate::dataflow::move_paths::{HasMoveData, MovePathIndex};
 
 use std::iter;
 
@@ -115,7 +115,7 @@
     }
 
     /// Returns an iterator over the elements present in the current state.
-    pub fn iter_incoming(&self) -> iter::Peekable<BitIter<BD::Idx>> {
+    pub fn iter_incoming(&self) -> iter::Peekable<BitIter<'_, BD::Idx>> {
         self.curr_state.iter().peekable()
     }
 
@@ -124,7 +124,7 @@
     /// Invokes `f` with an iterator over the resulting state.
     pub fn with_iter_outgoing<F>(&self, f: F)
     where
-        F: FnOnce(BitIter<BD::Idx>),
+        F: FnOnce(BitIter<'_, BD::Idx>),
     {
         let mut curr_state = self.curr_state.clone();
         curr_state.union(&self.stmt_gen);
diff --git a/src/librustc_mir/dataflow/drop_flag_effects.rs b/src/librustc_mir/dataflow/drop_flag_effects.rs
index 22fb7a3..49499cf 100644
--- a/src/librustc_mir/dataflow/drop_flag_effects.rs
+++ b/src/librustc_mir/dataflow/drop_flag_effects.rs
@@ -1,6 +1,6 @@
 use rustc::mir::{self, Mir, Location};
 use rustc::ty::{self, TyCtxt};
-use util::elaborate_drops::DropFlagState;
+use crate::util::elaborate_drops::DropFlagState;
 
 use super::{MoveDataParamEnv};
 use super::indexes::MovePathIndex;
diff --git a/src/librustc_mir/dataflow/graphviz.rs b/src/librustc_mir/dataflow/graphviz.rs
index 34752ba..9d9f18d 100644
--- a/src/librustc_mir/dataflow/graphviz.rs
+++ b/src/librustc_mir/dataflow/graphviz.rs
@@ -3,8 +3,6 @@
 use syntax::ast::NodeId;
 use rustc::mir::{BasicBlock, Mir};
 
-use dot;
-
 use std::fs;
 use std::io;
 use std::marker::PhantomData;
@@ -59,7 +57,7 @@
 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
 pub struct Edge { source: BasicBlock, index: usize }
 
-fn outgoing(mir: &Mir, bb: BasicBlock) -> Vec<Edge> {
+fn outgoing(mir: &Mir<'_>, bb: BasicBlock) -> Vec<Edge> {
     (0..mir[bb].terminator().successors().count())
         .map(|index| Edge { source: bb, index: index}).collect()
 }
@@ -70,18 +68,18 @@
 {
     type Node = Node;
     type Edge = Edge;
-    fn graph_id(&self) -> dot::Id {
+    fn graph_id(&self) -> dot::Id<'_> {
         dot::Id::new(format!("graph_for_node_{}",
                              self.mbcx.node_id()))
             .unwrap()
     }
 
-    fn node_id(&self, n: &Node) -> dot::Id {
+    fn node_id(&self, n: &Node) -> dot::Id<'_> {
         dot::Id::new(format!("bb_{}", n.index()))
             .unwrap()
     }
 
-    fn node_label(&self, n: &Node) -> dot::LabelText {
+    fn node_label(&self, n: &Node) -> dot::LabelText<'_> {
         // Node label is something like this:
         // +---------+----------------------------------+------------------+------------------+
         // | ENTRY   | MIR                              | GEN              | KILL             |
@@ -105,7 +103,7 @@
     }
 
 
-    fn node_shape(&self, _n: &Node) -> Option<dot::LabelText> {
+    fn node_shape(&self, _n: &Node) -> Option<dot::LabelText<'_>> {
         Some(dot::LabelText::label("none"))
     }
 
@@ -125,7 +123,7 @@
                                          n: &Node,
                                          w: &mut W,
                                          block: BasicBlock,
-                                         mir: &Mir) -> io::Result<()> {
+                                         mir: &Mir<'_>) -> io::Result<()> {
         // Header rows
         const HDRS: [&str; 4] = ["ENTRY", "MIR", "BLOCK GENS", "BLOCK KILLS"];
         const HDR_FMT: &str = "bgcolor=\"grey\"";
@@ -150,7 +148,7 @@
                                             n: &Node,
                                             w: &mut W,
                                             block: BasicBlock,
-                                            mir: &Mir)
+                                            mir: &Mir<'_>)
                                             -> io::Result<()> {
         let i = n.index();
 
@@ -200,7 +198,7 @@
                                           n: &Node,
                                           w: &mut W,
                                           block: BasicBlock,
-                                          mir: &Mir)
+                                          mir: &Mir<'_>)
                                           -> io::Result<()> {
         let i = n.index();
 
@@ -241,7 +239,7 @@
 {
     type Node = Node;
     type Edge = Edge;
-    fn nodes(&self) -> dot::Nodes<Node> {
+    fn nodes(&self) -> dot::Nodes<'_, Node> {
         self.mbcx.mir()
             .basic_blocks()
             .indices()
@@ -249,7 +247,7 @@
             .into()
     }
 
-    fn edges(&self) -> dot::Edges<Edge> {
+    fn edges(&self) -> dot::Edges<'_, Edge> {
         let mir = self.mbcx.mir();
 
         mir.basic_blocks()
diff --git a/src/librustc_mir/dataflow/impls/borrowed_locals.rs b/src/librustc_mir/dataflow/impls/borrowed_locals.rs
index 9d03e35..51d628c 100644
--- a/src/librustc_mir/dataflow/impls/borrowed_locals.rs
+++ b/src/librustc_mir/dataflow/impls/borrowed_locals.rs
@@ -2,7 +2,7 @@
 
 use rustc::mir::*;
 use rustc::mir::visit::Visitor;
-use dataflow::BitDenotation;
+use crate::dataflow::BitDenotation;
 
 /// This calculates if any part of a MIR local could have previously been borrowed.
 /// This means that once a local has been borrowed, its bit will be set
@@ -38,7 +38,7 @@
     }
 
     fn statement_effect(&self,
-                        sets: &mut BlockSets<Local>,
+                        sets: &mut BlockSets<'_, Local>,
                         loc: Location) {
         let stmt = &self.mir[loc.block].statements[loc.statement_index];
 
@@ -54,7 +54,7 @@
     }
 
     fn terminator_effect(&self,
-                         sets: &mut BlockSets<Local>,
+                         sets: &mut BlockSets<'_, Local>,
                          loc: Location) {
         BorrowedLocalsVisitor {
             sets,
diff --git a/src/librustc_mir/dataflow/impls/borrows.rs b/src/librustc_mir/dataflow/impls/borrows.rs
index 72218e2..beb0b31 100644
--- a/src/librustc_mir/dataflow/impls/borrows.rs
+++ b/src/librustc_mir/dataflow/impls/borrows.rs
@@ -1,5 +1,5 @@
-use borrow_check::borrow_set::{BorrowSet, BorrowData};
-use borrow_check::place_ext::PlaceExt;
+use crate::borrow_check::borrow_set::{BorrowSet, BorrowData};
+use crate::borrow_check::place_ext::PlaceExt;
 
 use rustc::mir::{self, Location, Place, Mir};
 use rustc::ty::TyCtxt;
@@ -9,11 +9,11 @@
 use rustc_data_structures::fx::FxHashMap;
 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
 
-use dataflow::{BitDenotation, BlockSets, InitialFlow};
-pub use dataflow::indexes::BorrowIndex;
-use borrow_check::nll::region_infer::RegionInferenceContext;
-use borrow_check::nll::ToRegionVid;
-use borrow_check::places_conflict;
+use crate::dataflow::{BitDenotation, BlockSets, InitialFlow};
+pub use crate::dataflow::indexes::BorrowIndex;
+use crate::borrow_check::nll::region_infer::RegionInferenceContext;
+use crate::borrow_check::nll::ToRegionVid;
+use crate::borrow_check::places_conflict;
 
 use std::rc::Rc;
 
@@ -163,7 +163,7 @@
     /// Add all borrows to the kill set, if those borrows are out of scope at `location`.
     /// That means they went out of a nonlexical scope
     fn kill_loans_out_of_scope_at_location(&self,
-                                           sets: &mut BlockSets<BorrowIndex>,
+                                           sets: &mut BlockSets<'_, BorrowIndex>,
                                            location: Location) {
         // NOTE: The state associated with a given `location`
         // reflects the dataflow on entry to the statement.
@@ -184,7 +184,7 @@
     /// Kill any borrows that conflict with `place`.
     fn kill_borrows_on_place(
         &self,
-        sets: &mut BlockSets<BorrowIndex>,
+        sets: &mut BlockSets<'_, BorrowIndex>,
         place: &Place<'tcx>
     ) {
         debug!("kill_borrows_on_place: place={:?}", place);
@@ -243,13 +243,13 @@
     }
 
     fn before_statement_effect(&self,
-                               sets: &mut BlockSets<BorrowIndex>,
+                               sets: &mut BlockSets<'_, BorrowIndex>,
                                location: Location) {
         debug!("Borrows::before_statement_effect sets: {:?} location: {:?}", sets, location);
         self.kill_loans_out_of_scope_at_location(sets, location);
     }
 
-    fn statement_effect(&self, sets: &mut BlockSets<BorrowIndex>, location: Location) {
+    fn statement_effect(&self, sets: &mut BlockSets<'_, BorrowIndex>, location: Location) {
         debug!("Borrows::statement_effect: sets={:?} location={:?}", sets, location);
 
         let block = &self.mir.basic_blocks().get(location.block).unwrap_or_else(|| {
@@ -307,13 +307,13 @@
     }
 
     fn before_terminator_effect(&self,
-                                sets: &mut BlockSets<BorrowIndex>,
+                                sets: &mut BlockSets<'_, BorrowIndex>,
                                 location: Location) {
         debug!("Borrows::before_terminator_effect sets: {:?} location: {:?}", sets, location);
         self.kill_loans_out_of_scope_at_location(sets, location);
     }
 
-    fn terminator_effect(&self, _: &mut BlockSets<BorrowIndex>, _: Location) {}
+    fn terminator_effect(&self, _: &mut BlockSets<'_, BorrowIndex>, _: Location) {}
 
     fn propagate_call_return(
         &self,
diff --git a/src/librustc_mir/dataflow/impls/mod.rs b/src/librustc_mir/dataflow/impls/mod.rs
index 1ccda3a..c8965b9 100644
--- a/src/librustc_mir/dataflow/impls/mod.rs
+++ b/src/librustc_mir/dataflow/impls/mod.rs
@@ -9,7 +9,7 @@
 
 use super::MoveDataParamEnv;
 
-use util::elaborate_drops::DropFlagState;
+use crate::util::elaborate_drops::DropFlagState;
 
 use super::move_paths::{HasMoveData, MoveData, MovePathIndex, InitIndex};
 use super::move_paths::{LookupResult, InitKind};
@@ -251,7 +251,7 @@
 
 
 impl<'a, 'gcx, 'tcx> MaybeInitializedPlaces<'a, 'gcx, 'tcx> {
-    fn update_bits(sets: &mut BlockSets<MovePathIndex>, path: MovePathIndex,
+    fn update_bits(sets: &mut BlockSets<'_, MovePathIndex>, path: MovePathIndex,
                    state: DropFlagState)
     {
         match state {
@@ -262,7 +262,7 @@
 }
 
 impl<'a, 'gcx, 'tcx> MaybeUninitializedPlaces<'a, 'gcx, 'tcx> {
-    fn update_bits(sets: &mut BlockSets<MovePathIndex>, path: MovePathIndex,
+    fn update_bits(sets: &mut BlockSets<'_, MovePathIndex>, path: MovePathIndex,
                    state: DropFlagState)
     {
         match state {
@@ -273,7 +273,7 @@
 }
 
 impl<'a, 'gcx, 'tcx> DefinitelyInitializedPlaces<'a, 'gcx, 'tcx> {
-    fn update_bits(sets: &mut BlockSets<MovePathIndex>, path: MovePathIndex,
+    fn update_bits(sets: &mut BlockSets<'_, MovePathIndex>, path: MovePathIndex,
                    state: DropFlagState)
     {
         match state {
@@ -300,7 +300,7 @@
     }
 
     fn statement_effect(&self,
-                        sets: &mut BlockSets<MovePathIndex>,
+                        sets: &mut BlockSets<'_, MovePathIndex>,
                         location: Location)
     {
         drop_flag_effects_for_location(
@@ -311,7 +311,7 @@
     }
 
     fn terminator_effect(&self,
-                         sets: &mut BlockSets<MovePathIndex>,
+                         sets: &mut BlockSets<'_, MovePathIndex>,
                          location: Location)
     {
         drop_flag_effects_for_location(
@@ -358,7 +358,7 @@
     }
 
     fn statement_effect(&self,
-                        sets: &mut BlockSets<MovePathIndex>,
+                        sets: &mut BlockSets<'_, MovePathIndex>,
                         location: Location)
     {
         drop_flag_effects_for_location(
@@ -369,7 +369,7 @@
     }
 
     fn terminator_effect(&self,
-                         sets: &mut BlockSets<MovePathIndex>,
+                         sets: &mut BlockSets<'_, MovePathIndex>,
                          location: Location)
     {
         drop_flag_effects_for_location(
@@ -414,7 +414,7 @@
     }
 
     fn statement_effect(&self,
-                        sets: &mut BlockSets<MovePathIndex>,
+                        sets: &mut BlockSets<'_, MovePathIndex>,
                         location: Location)
     {
         drop_flag_effects_for_location(
@@ -425,7 +425,7 @@
     }
 
     fn terminator_effect(&self,
-                         sets: &mut BlockSets<MovePathIndex>,
+                         sets: &mut BlockSets<'_, MovePathIndex>,
                          location: Location)
     {
         drop_flag_effects_for_location(
@@ -464,7 +464,7 @@
     }
 
     fn statement_effect(&self,
-                        sets: &mut BlockSets<InitIndex>,
+                        sets: &mut BlockSets<'_, InitIndex>,
                         location: Location) {
         let (_, mir, move_data) = (self.tcx, self.mir, self.move_data());
         let stmt = &mir[location.block].statements[location.statement_index];
@@ -511,7 +511,7 @@
     }
 
     fn terminator_effect(&self,
-                         sets: &mut BlockSets<InitIndex>,
+                         sets: &mut BlockSets<'_, InitIndex>,
                          location: Location)
     {
         let (mir, move_data) = (self.mir, self.move_data());
diff --git a/src/librustc_mir/dataflow/impls/storage_liveness.rs b/src/librustc_mir/dataflow/impls/storage_liveness.rs
index 9c17076..6b8eb6f 100644
--- a/src/librustc_mir/dataflow/impls/storage_liveness.rs
+++ b/src/librustc_mir/dataflow/impls/storage_liveness.rs
@@ -1,7 +1,7 @@
 pub use super::*;
 
 use rustc::mir::*;
-use dataflow::BitDenotation;
+use crate::dataflow::BitDenotation;
 
 #[derive(Copy, Clone)]
 pub struct MaybeStorageLive<'a, 'tcx: 'a> {
@@ -31,7 +31,7 @@
     }
 
     fn statement_effect(&self,
-                        sets: &mut BlockSets<Local>,
+                        sets: &mut BlockSets<'_, Local>,
                         loc: Location) {
         let stmt = &self.mir[loc.block].statements[loc.statement_index];
 
@@ -43,7 +43,7 @@
     }
 
     fn terminator_effect(&self,
-                         _sets: &mut BlockSets<Local>,
+                         _sets: &mut BlockSets<'_, Local>,
                          _loc: Location) {
         // Terminators have no effect
     }
diff --git a/src/librustc_mir/dataflow/mod.rs b/src/librustc_mir/dataflow/mod.rs
index f09db97..1853b60 100644
--- a/src/librustc_mir/dataflow/mod.rs
+++ b/src/librustc_mir/dataflow/mod.rs
@@ -58,7 +58,7 @@
 }
 
 impl fmt::Debug for DebugFormatted {
-    fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(w, "{}", self.0)
     }
 }
@@ -525,7 +525,7 @@
 
 impl<E:Idx> AllSets<E> {
     pub fn bits_per_block(&self) -> usize { self.bits_per_block }
-    pub fn for_block(&mut self, block_idx: usize) -> BlockSets<E> {
+    pub fn for_block(&mut self, block_idx: usize) -> BlockSets<'_, E> {
         BlockSets {
             on_entry: &mut self.on_entry_sets[block_idx],
             gen_set: &mut self.gen_sets[block_idx],
@@ -616,7 +616,7 @@
     /// applied, in that order, before moving for the next
     /// statement.
     fn before_statement_effect(&self,
-                               _sets: &mut BlockSets<Self::Idx>,
+                               _sets: &mut BlockSets<'_, Self::Idx>,
                                _location: Location) {}
 
     /// Mutates the block-sets (the flow sets for the given
@@ -630,7 +630,7 @@
     /// `bb_data` is the sequence of statements identified by `bb` in
     /// the MIR.
     fn statement_effect(&self,
-                        sets: &mut BlockSets<Self::Idx>,
+                        sets: &mut BlockSets<'_, Self::Idx>,
                         location: Location);
 
     /// Similar to `terminator_effect`, except it applies
@@ -645,7 +645,7 @@
     /// applied, in that order, before moving for the next
     /// terminator.
     fn before_terminator_effect(&self,
-                                _sets: &mut BlockSets<Self::Idx>,
+                                _sets: &mut BlockSets<'_, Self::Idx>,
                                 _location: Location) {}
 
     /// Mutates the block-sets (the flow sets for the given
@@ -659,7 +659,7 @@
     /// The effects applied here cannot depend on which branch the
     /// terminator took.
     fn terminator_effect(&self,
-                         sets: &mut BlockSets<Self::Idx>,
+                         sets: &mut BlockSets<'_, Self::Idx>,
                          location: Location);
 
     /// Mutates the block-sets according to the (flow-dependent)
diff --git a/src/librustc_mir/dataflow/move_paths/mod.rs b/src/librustc_mir/dataflow/move_paths/mod.rs
index d772162..efd979a 100644
--- a/src/librustc_mir/dataflow/move_paths/mod.rs
+++ b/src/librustc_mir/dataflow/move_paths/mod.rs
@@ -37,7 +37,7 @@
             }
 
             impl fmt::Debug for $Index {
-                fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+                fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
                     write!(fmt, "{}{}", $debug_name, self.index())
                 }
             }
@@ -62,7 +62,7 @@
 pub use self::indexes::InitIndex;
 
 impl MoveOutIndex {
-    pub fn move_path_index(&self, move_data: &MoveData) -> MovePathIndex {
+    pub fn move_path_index(&self, move_data: &MoveData<'_>) -> MovePathIndex {
         move_data.moves[*self].path
     }
 }
@@ -88,7 +88,10 @@
 }
 
 impl<'tcx> MovePath<'tcx> {
-    pub fn parents(&self, move_paths: &IndexVec<MovePathIndex, MovePath>) -> Vec<MovePathIndex> {
+    pub fn parents(
+        &self,
+        move_paths: &IndexVec<MovePathIndex, MovePath<'_>>,
+    ) -> Vec<MovePathIndex> {
         let mut parents = Vec::new();
 
         let mut curr_parent = self.parent;
@@ -102,7 +105,7 @@
 }
 
 impl<'tcx> fmt::Debug for MovePath<'tcx> {
-    fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(w, "MovePath {{")?;
         if let Some(parent) = self.parent {
             write!(w, " parent: {:?},", parent)?;
@@ -118,7 +121,7 @@
 }
 
 impl<'tcx> fmt::Display for MovePath<'tcx> {
-    fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(w, "{:?}", self.place)
     }
 }
@@ -166,7 +169,7 @@
 }
 
 impl<T> LocationMap<T> where T: Default + Clone {
-    fn new(mir: &Mir) -> Self {
+    fn new(mir: &Mir<'_>) -> Self {
         LocationMap {
             map: mir.basic_blocks().iter().map(|block| {
                 vec![T::default(); block.statements.len()+1]
@@ -190,7 +193,7 @@
 }
 
 impl fmt::Debug for MoveOut {
-    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(fmt, "{:?}@{:?}", self.path, self.source)
     }
 }
@@ -227,7 +230,7 @@
 }
 
 impl fmt::Debug for Init {
-    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(fmt, "{:?}@{:?} ({:?})", self.path, self.location, self.kind)
     }
 }
diff --git a/src/librustc_mir/hair/cx/block.rs b/src/librustc_mir/hair/cx/block.rs
index 518ae97..ed9f95f 100644
--- a/src/librustc_mir/hair/cx/block.rs
+++ b/src/librustc_mir/hair/cx/block.rs
@@ -1,6 +1,6 @@
-use hair::*;
-use hair::cx::Cx;
-use hair::cx::to_ref::ToRef;
+use crate::hair::*;
+use crate::hair::cx::Cx;
+use crate::hair::cx::to_ref::ToRef;
 use rustc::middle::region;
 use rustc::hir;
 use rustc::ty;
@@ -48,7 +48,7 @@
     for (index, stmt) in stmts.iter().enumerate() {
         let hir_id = stmt.hir_id;
         let opt_dxn_ext = cx.region_scope_tree.opt_destruction_scope(hir_id.local_id);
-        let stmt_span = StatementSpan(cx.tcx.hir().span(stmt.id));
+        let stmt_span = StatementSpan(cx.tcx.hir().span_by_hir_id(hir_id));
         match stmt.node {
             hir::StmtKind::Expr(ref expr) |
             hir::StmtKind::Semi(ref expr) => {
diff --git a/src/librustc_mir/hair/cx/expr.rs b/src/librustc_mir/hair/cx/expr.rs
index 8d64c9e..7e1365f 100644
--- a/src/librustc_mir/hair/cx/expr.rs
+++ b/src/librustc_mir/hair/cx/expr.rs
@@ -1,9 +1,9 @@
-use hair::*;
+use crate::hair::*;
+use crate::hair::cx::Cx;
+use crate::hair::cx::block;
+use crate::hair::cx::to_ref::ToRef;
+use crate::hair::util::UserAnnotatedTyHelpers;
 use rustc_data_structures::indexed_vec::Idx;
-use hair::cx::Cx;
-use hair::cx::block;
-use hair::cx::to_ref::ToRef;
-use hair::util::UserAnnotatedTyHelpers;
 use rustc::hir::def::{Def, CtorKind};
 use rustc::mir::interpret::{GlobalId, ErrorHandled};
 use rustc::ty::{self, AdtKind, Ty};
@@ -342,7 +342,7 @@
         }
 
         hir::ExprKind::Lit(ref lit) => ExprKind::Literal {
-            literal: cx.tcx.intern_lazy_const(ty::LazyConst::Evaluated(
+            literal: cx.tcx.mk_lazy_const(ty::LazyConst::Evaluated(
                 cx.const_eval_literal(&lit.node, expr_ty, lit.span, false)
             )),
             user_ty: None,
@@ -442,7 +442,7 @@
             } else {
                 if let hir::ExprKind::Lit(ref lit) = arg.node {
                     ExprKind::Literal {
-                        literal: cx.tcx.intern_lazy_const(ty::LazyConst::Evaluated(
+                        literal: cx.tcx.mk_lazy_const(ty::LazyConst::Evaluated(
                             cx.const_eval_literal(&lit.node, expr_ty, lit.span, true)
                         )),
                         user_ty: None,
@@ -702,7 +702,7 @@
                         ty: var_ty,
                         span: expr.span,
                         kind: ExprKind::Literal {
-                            literal: cx.tcx.intern_lazy_const(literal),
+                            literal: cx.tcx.mk_lazy_const(literal),
                             user_ty: None
                         },
                     }.to_ref();
@@ -856,7 +856,7 @@
         ty,
         span,
         kind: ExprKind::Literal {
-            literal: cx.tcx().intern_lazy_const(ty::LazyConst::Evaluated(
+            literal: cx.tcx().mk_lazy_const(ty::LazyConst::Evaluated(
                 ty::Const::zero_sized(ty)
             )),
             user_ty,
@@ -918,7 +918,7 @@
             let user_ty = user_substs_applied_to_def(cx, expr.hir_id, &def);
             debug!("convert_path_expr: user_ty={:?}", user_ty);
             ExprKind::Literal {
-                literal: cx.tcx.intern_lazy_const(ty::LazyConst::Evaluated(ty::Const::zero_sized(
+                literal: cx.tcx.mk_lazy_const(ty::LazyConst::Evaluated(ty::Const::zero_sized(
                     cx.tables().node_id_to_type(expr.hir_id),
                 ))),
                 user_ty,
@@ -930,7 +930,7 @@
             let user_ty = user_substs_applied_to_def(cx, expr.hir_id, &def);
             debug!("convert_path_expr: (const) user_ty={:?}", user_ty);
             ExprKind::Literal {
-                literal: cx.tcx.intern_lazy_const(ty::LazyConst::Unevaluated(def_id, substs)),
+                literal: cx.tcx.mk_lazy_const(ty::LazyConst::Unevaluated(def_id, substs)),
                 user_ty,
             }
         },
diff --git a/src/librustc_mir/hair/cx/mod.rs b/src/librustc_mir/hair/cx/mod.rs
index f514cac..47be822 100644
--- a/src/librustc_mir/hair/cx/mod.rs
+++ b/src/librustc_mir/hair/cx/mod.rs
@@ -4,8 +4,8 @@
 //! work.
 //!
 
-use hair::*;
-use hair::util::UserAnnotatedTyHelpers;
+use crate::hair::*;
+use crate::hair::util::UserAnnotatedTyHelpers;
 
 use rustc_data_structures::indexed_vec::Idx;
 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
@@ -21,7 +21,7 @@
 use syntax::symbol::Symbol;
 use rustc::hir;
 use rustc_data_structures::sync::Lrc;
-use hair::constant::{lit_to_const, LitToConstError};
+use crate::hair::constant::{lit_to_const, LitToConstError};
 
 #[derive(Clone)]
 pub struct Cx<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
@@ -110,7 +110,7 @@
     }
 
     pub fn usize_literal(&mut self, value: u64) -> &'tcx ty::LazyConst<'tcx> {
-        self.tcx.intern_lazy_const(ty::LazyConst::Evaluated(ty::Const::from_usize(self.tcx, value)))
+        self.tcx.mk_lazy_const(ty::LazyConst::Evaluated(ty::Const::from_usize(self.tcx, value)))
     }
 
     pub fn bool_ty(&mut self) -> Ty<'tcx> {
@@ -122,11 +122,11 @@
     }
 
     pub fn true_literal(&mut self) -> &'tcx ty::LazyConst<'tcx> {
-        self.tcx.intern_lazy_const(ty::LazyConst::Evaluated(ty::Const::from_bool(self.tcx, true)))
+        self.tcx.mk_lazy_const(ty::LazyConst::Evaluated(ty::Const::from_bool(self.tcx, true)))
     }
 
     pub fn false_literal(&mut self) -> &'tcx ty::LazyConst<'tcx> {
-        self.tcx.intern_lazy_const(ty::LazyConst::Evaluated(ty::Const::from_bool(self.tcx, false)))
+        self.tcx.mk_lazy_const(ty::LazyConst::Evaluated(ty::Const::from_bool(self.tcx, false)))
     }
 
     pub fn const_eval_literal(
@@ -239,7 +239,7 @@
     }
 }
 
-fn lint_level_for_hir_id(tcx: TyCtxt, mut id: ast::NodeId) -> ast::NodeId {
+fn lint_level_for_hir_id(tcx: TyCtxt<'_, '_, '_>, mut id: ast::NodeId) -> ast::NodeId {
     // Right now we insert a `with_ignore` node in the dep graph here to
     // ignore the fact that `lint_levels` below depends on the entire crate.
     // For now this'll prevent false positives of recompiling too much when
diff --git a/src/librustc_mir/hair/cx/to_ref.rs b/src/librustc_mir/hair/cx/to_ref.rs
index 1b87e44..a462c61 100644
--- a/src/librustc_mir/hair/cx/to_ref.rs
+++ b/src/librustc_mir/hair/cx/to_ref.rs
@@ -1,4 +1,4 @@
-use hair::*;
+use crate::hair::*;
 
 use rustc::hir;
 use syntax::ptr::P;
diff --git a/src/librustc_mir/hair/pattern/_match.rs b/src/librustc_mir/hair/pattern/_match.rs
index 7f5b1a7..5779a03 100644
--- a/src/librustc_mir/hair/pattern/_match.rs
+++ b/src/librustc_mir/hair/pattern/_match.rs
@@ -307,7 +307,7 @@
 /// + _     + [_, _, ..tail] +
 /// ++++++++++++++++++++++++++
 impl<'p, 'tcx> fmt::Debug for Matrix<'p, 'tcx> {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(f, "\n")?;
 
         let &Matrix(ref m) = self;
@@ -442,7 +442,7 @@
                 VariantIdx::new(0)
             }
             &ConstantValue(c) => {
-                ::const_eval::const_variant_index(
+                crate::const_eval::const_variant_index(
                     cx.tcx,
                     cx.param_env,
                     c,
@@ -1115,7 +1115,7 @@
     } else {
         debug!("is_useful - expanding wildcard");
 
-        let used_ctors: Vec<Constructor> = rows.iter().flat_map(|row| {
+        let used_ctors: Vec<Constructor<'_>> = rows.iter().flat_map(|row| {
             pat_constructors(cx, row[0], pcx).unwrap_or(vec![])
         }).collect();
         debug!("used_ctors = {:#?}", used_ctors);
@@ -1302,7 +1302,7 @@
 /// Returns None in case of a catch-all, which can't be specialized.
 fn pat_constructors<'tcx>(cx: &mut MatchCheckCtxt<'_, 'tcx>,
                           pat: &Pattern<'tcx>,
-                          pcx: PatternContext)
+                          pcx: PatternContext<'_>)
                           -> Option<Vec<Constructor<'tcx>>>
 {
     match *pat.kind {
diff --git a/src/librustc_mir/hair/pattern/check_match.rs b/src/librustc_mir/hair/pattern/check_match.rs
index a47d643..978051a 100644
--- a/src/librustc_mir/hair/pattern/check_match.rs
+++ b/src/librustc_mir/hair/pattern/check_match.rs
@@ -229,7 +229,7 @@
                 return;
             }
 
-            let matrix: Matrix = inlined_arms
+            let matrix: Matrix<'_, '_> = inlined_arms
                 .iter()
                 .filter(|&&(_, guard)| guard.is_none())
                 .flat_map(|arm| &arm.0)
@@ -248,7 +248,7 @@
                                                 self.tables);
             let pattern = patcx.lower_pattern(pat);
             let pattern_ty = pattern.ty;
-            let pats: Matrix = vec![smallvec![
+            let pats: Matrix<'_, '_> = vec![smallvec![
                 expand_pattern(cx, pattern)
             ]].into_iter().collect();
 
@@ -283,7 +283,7 @@
     }
 }
 
-fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor, pat: &Pat) {
+fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor<'_, '_>, pat: &Pat) {
     pat.walk(|p| {
         if let PatKind::Binding(_, _, _, ident, None) = p.node {
             if let Some(&bm) = cx.tables.pat_binding_modes().get(p.hir_id) {
@@ -462,7 +462,7 @@
 }
 
 // Legality of move bindings checking
-fn check_legality_of_move_bindings(cx: &MatchVisitor,
+fn check_legality_of_move_bindings(cx: &MatchVisitor<'_, '_>,
                                    has_guard: bool,
                                    pats: &[P<Pat>]) {
     let mut by_ref_span = None;
@@ -541,7 +541,7 @@
 /// assign.
 ///
 /// FIXME: this should be done by borrowck.
-fn check_for_mutation_in_guard(cx: &MatchVisitor, guard: &hir::Guard) {
+fn check_for_mutation_in_guard(cx: &MatchVisitor<'_, '_>, guard: &hir::Guard) {
     let mut checker = MutationChecker {
         cx,
     };
@@ -561,13 +561,13 @@
 }
 
 impl<'a, 'tcx> Delegate<'tcx> for MutationChecker<'a, 'tcx> {
-    fn matched_pat(&mut self, _: &Pat, _: &cmt_, _: euv::MatchMode) {}
-    fn consume(&mut self, _: ast::NodeId, _: Span, _: &cmt_, _: ConsumeMode) {}
-    fn consume_pat(&mut self, _: &Pat, _: &cmt_, _: ConsumeMode) {}
+    fn matched_pat(&mut self, _: &Pat, _: &cmt_<'_>, _: euv::MatchMode) {}
+    fn consume(&mut self, _: ast::NodeId, _: Span, _: &cmt_<'_>, _: ConsumeMode) {}
+    fn consume_pat(&mut self, _: &Pat, _: &cmt_<'_>, _: ConsumeMode) {}
     fn borrow(&mut self,
               _: ast::NodeId,
               span: Span,
-              _: &cmt_,
+              _: &cmt_<'_>,
               _: ty::Region<'tcx>,
               kind:ty:: BorrowKind,
               _: LoanCause) {
@@ -588,7 +588,7 @@
         }
     }
     fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {}
-    fn mutate(&mut self, _: ast::NodeId, span: Span, _: &cmt_, mode: MutateMode) {
+    fn mutate(&mut self, _: ast::NodeId, span: Span, _: &cmt_<'_>, mode: MutateMode) {
         match mode {
             MutateMode::JustWrite | MutateMode::WriteAndRead => {
                 struct_span_err!(self.cx.tcx.sess, span, E0302, "cannot assign in a pattern guard")
@@ -603,7 +603,7 @@
 /// Forbids bindings in `@` patterns. This is necessary for memory safety,
 /// because of the way rvalues are handled in the borrow check. (See issue
 /// #14587.)
-fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor, pat: &Pat) {
+fn check_legality_of_bindings_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat) {
     AtBindingPatternVisitor { cx: cx, bindings_allowed: true }.visit_pat(pat);
 }
 
diff --git a/src/librustc_mir/hair/pattern/mod.rs b/src/librustc_mir/hair/pattern/mod.rs
index 6b7e141..84d8f32 100644
--- a/src/librustc_mir/hair/pattern/mod.rs
+++ b/src/librustc_mir/hair/pattern/mod.rs
@@ -6,10 +6,10 @@
 pub use self::check_match::check_crate;
 pub(crate) use self::check_match::check_match;
 
-use const_eval::{const_field, const_variant_index};
+use crate::const_eval::{const_field, const_variant_index};
 
-use hair::util::UserAnnotatedTyHelpers;
-use hair::constant::*;
+use crate::hair::util::UserAnnotatedTyHelpers;
+use crate::hair::constant::*;
 
 use rustc::mir::{fmt_const_val, Field, BorrowKind, Mutability};
 use rustc::mir::{UserTypeProjection};
@@ -167,6 +167,17 @@
     },
 }
 
+impl<'tcx> PatternKind<'tcx> {
+    /// If this is a `PatternKind::AscribeUserType` then return the subpattern kind, otherwise
+    /// return this pattern kind.
+    fn with_user_type_ascription_subpattern(self) -> Self {
+        match self {
+            PatternKind::AscribeUserType { subpattern: Pattern { box kind, ..  }, ..  } => kind,
+            kind => kind,
+        }
+    }
+}
+
 #[derive(Clone, Copy, Debug, PartialEq)]
 pub struct PatternRange<'tcx> {
     pub lo: ty::Const<'tcx>,
@@ -176,7 +187,7 @@
 }
 
 impl<'tcx> fmt::Display for Pattern<'tcx> {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match *self.kind {
             PatternKind::Wild => write!(f, "_"),
             PatternKind::AscribeUserType { ref subpattern, .. } =>
@@ -403,9 +414,15 @@
             PatKind::Lit(ref value) => self.lower_lit(value),
 
             PatKind::Range(ref lo_expr, ref hi_expr, end) => {
-                match (self.lower_lit(lo_expr), self.lower_lit(hi_expr)) {
-                    (PatternKind::Constant { value: lo },
-                     PatternKind::Constant { value: hi }) => {
+                match (
+                    // Look for `PatternKind::Constant` patterns inside of any
+                    // `PatternKind::AscribeUserType` patterns. Type ascriptions can be safely
+                    // ignored for the purposes of lowering a range correctly - these are checked
+                    // elsewhere for well-formedness.
+                    self.lower_lit(lo_expr).with_user_type_ascription_subpattern(),
+                    self.lower_lit(hi_expr).with_user_type_ascription_subpattern(),
+                ) {
+                    (PatternKind::Constant { value: lo }, PatternKind::Constant { value: hi }) => {
                         use std::cmp::Ordering;
                         let cmp = compare_const_vals(
                             self.tcx,
@@ -454,7 +471,15 @@
                             }
                         }
                     }
-                    _ => PatternKind::Wild
+                    ref pats => {
+                        self.tcx.sess.delay_span_bug(
+                            pat.span,
+                            &format!("found bad range pattern `{:?}` outside of error recovery",
+                                     pats),
+                        );
+
+                        PatternKind::Wild
+                    }
                 }
             }
 
diff --git a/src/librustc_mir/interpret/eval_context.rs b/src/librustc_mir/interpret/eval_context.rs
index 1b976d8..c87338f 100644
--- a/src/librustc_mir/interpret/eval_context.rs
+++ b/src/librustc_mir/interpret/eval_context.rs
@@ -322,7 +322,7 @@
     ) -> EvalResult<'tcx, TyLayout<'tcx>> {
         match frame.locals[local].layout.get() {
             None => {
-                let layout = ::interpret::operand::from_known_layout(layout, || {
+                let layout = crate::interpret::operand::from_known_layout(layout, || {
                     let local_ty = frame.mir.local_decls[local].ty;
                     let local_ty = self.monomorphize_with_substs(local_ty, frame.instance.substs);
                     self.layout_of(local_ty)
diff --git a/src/librustc_mir/interpret/place.rs b/src/librustc_mir/interpret/place.rs
index 9ca7f9d..3d6fcae 100644
--- a/src/librustc_mir/interpret/place.rs
+++ b/src/librustc_mir/interpret/place.rs
@@ -823,6 +823,8 @@
         let src = match self.try_read_immediate(src)? {
             Ok(src_val) => {
                 // Yay, we got a value that we can write directly.
+                // FIXME: Add a check to make sure that if `src` is indirect,
+                // it does not overlap with `dest`.
                 return self.write_immediate_no_validate(src_val, dest);
             }
             Err(mplace) => mplace,
@@ -836,7 +838,8 @@
         self.memory.copy(
             src_ptr, src_align,
             dest_ptr, dest_align,
-            dest.layout.size, false
+            dest.layout.size,
+            /*nonoverlapping*/ true,
         )?;
 
         Ok(())
diff --git a/src/librustc_mir/interpret/snapshot.rs b/src/librustc_mir/interpret/snapshot.rs
index 5fae461..ee29511 100644
--- a/src/librustc_mir/interpret/snapshot.rs
+++ b/src/librustc_mir/interpret/snapshot.rs
@@ -25,7 +25,7 @@
 
 use super::eval_context::{LocalState, StackPopCleanup};
 use super::{Frame, Memory, Operand, MemPlace, Place, Immediate, ScalarMaybeUndef, LocalValue};
-use const_eval::CompileTimeInterpreter;
+use crate::const_eval::CompileTimeInterpreter;
 
 #[derive(Default)]
 pub(crate) struct InfiniteLoopDetector<'a, 'mir, 'tcx: 'a + 'mir> {
@@ -200,7 +200,7 @@
     Undef,
 });
 
-impl_stable_hash_for!(struct ::interpret::MemPlace {
+impl_stable_hash_for!(struct crate::interpret::MemPlace {
     ptr,
     align,
     meta,
@@ -211,7 +211,7 @@
     align -> *align, // just copy alignment verbatim
 });
 
-impl_stable_hash_for!(enum ::interpret::Place {
+impl_stable_hash_for!(enum crate::interpret::Place {
     Ptr(mem_place),
     Local { frame, local },
 });
@@ -232,7 +232,7 @@
     }
 }
 
-impl_stable_hash_for!(enum ::interpret::Immediate {
+impl_stable_hash_for!(enum crate::interpret::Immediate {
     Scalar(x),
     ScalarPair(x, y),
 });
@@ -241,7 +241,7 @@
     ScalarPair(s, t),
 });
 
-impl_stable_hash_for!(enum ::interpret::Operand {
+impl_stable_hash_for!(enum crate::interpret::Operand {
     Immediate(x),
     Indirect(x),
 });
@@ -250,7 +250,7 @@
     Indirect(m),
 });
 
-impl_stable_hash_for!(enum ::interpret::LocalValue {
+impl_stable_hash_for!(enum crate::interpret::LocalValue {
     Dead,
     Live(x),
 });
@@ -298,7 +298,7 @@
     }
 }
 
-impl_stable_hash_for!(enum ::interpret::eval_context::StackPopCleanup {
+impl_stable_hash_for!(enum crate::interpret::eval_context::StackPopCleanup {
     Goto(block),
     None { cleanup },
 });
diff --git a/src/librustc_mir/interpret/terminator.rs b/src/librustc_mir/interpret/terminator.rs
index 7e82352..be50daa 100644
--- a/src/librustc_mir/interpret/terminator.rs
+++ b/src/librustc_mir/interpret/terminator.rs
@@ -112,7 +112,7 @@
                 let ty = place.layout.ty;
                 trace!("TerminatorKind::drop: {:?}, type {}", location, ty);
 
-                let instance = ::monomorphize::resolve_drop_in_place(*self.tcx, ty);
+                let instance = crate::monomorphize::resolve_drop_in_place(*self.tcx, ty);
                 self.drop_in_place(
                     place,
                     instance,
@@ -326,7 +326,7 @@
                     // last incoming argument.  These two iterators do not have the same type,
                     // so to keep the code paths uniform we accept an allocation
                     // (for RustCall ABI only).
-                    let caller_args : Cow<[OpTy<'tcx, M::PointerTag>]> =
+                    let caller_args : Cow<'_, [OpTy<'tcx, M::PointerTag>]> =
                         if caller_abi == Abi::RustCall && !args.is_empty() {
                             // Untuple
                             let (&untuple_arg, args) = args.split_last().unwrap();
@@ -335,7 +335,7 @@
                                 .chain((0..untuple_arg.layout.fields.count()).into_iter()
                                     .map(|i| self.operand_field(untuple_arg, i as u64))
                                 )
-                                .collect::<EvalResult<Vec<OpTy<'tcx, M::PointerTag>>>>()?)
+                                .collect::<EvalResult<'_, Vec<OpTy<'tcx, M::PointerTag>>>>()?)
                         } else {
                             // Plain arg passing
                             Cow::from(args)
diff --git a/src/librustc_mir/interpret/traits.rs b/src/librustc_mir/interpret/traits.rs
index 642bbc1..63253ba 100644
--- a/src/librustc_mir/interpret/traits.rs
+++ b/src/librustc_mir/interpret/traits.rs
@@ -52,7 +52,7 @@
         ).with_default_tag();
         let tcx = &*self.tcx;
 
-        let drop = ::monomorphize::resolve_drop_in_place(*tcx, ty);
+        let drop = crate::monomorphize::resolve_drop_in_place(*tcx, ty);
         let drop = self.memory.create_fn_alloc(drop).with_default_tag();
         // no need to do any alignment checks on the memory accesses below, because we know the
         // allocation is correctly aligned as we created it above. Also we're only offsetting by
diff --git a/src/librustc_mir/interpret/visitor.rs b/src/librustc_mir/interpret/visitor.rs
index 4773f56..4ff5cde 100644
--- a/src/librustc_mir/interpret/visitor.rs
+++ b/src/librustc_mir/interpret/visitor.rs
@@ -26,7 +26,7 @@
     ) -> EvalResult<'tcx, OpTy<'tcx, M::PointerTag>>;
 
     /// Create this from an `MPlaceTy`.
-    fn from_mem_place(MPlaceTy<'tcx, M::PointerTag>) -> Self;
+    fn from_mem_place(mplace: MPlaceTy<'tcx, M::PointerTag>) -> Self;
 
     /// Project to the given enum variant.
     fn project_downcast(
@@ -125,14 +125,14 @@
 }
 
 macro_rules! make_value_visitor {
-    ($visitor_trait_name:ident, $($mutability:ident)*) => {
+    ($visitor_trait_name:ident, $($mutability:ident)?) => {
         // How to traverse a value and what to do when we are at the leaves.
         pub trait $visitor_trait_name<'a, 'mir, 'tcx: 'mir+'a, M: Machine<'a, 'mir, 'tcx>>: Sized {
             type V: Value<'a, 'mir, 'tcx, M>;
 
             /// The visitor must have an `EvalContext` in it.
-            fn ecx(&$($mutability)* self)
-                -> &$($mutability)* EvalContext<'a, 'mir, 'tcx, M>;
+            fn ecx(&$($mutability)? self)
+                -> &$($mutability)? EvalContext<'a, 'mir, 'tcx, M>;
 
             // Recursive actions, ready to be overloaded.
             /// Visit the given value, dispatching as appropriate to more specialized visitors.
diff --git a/src/librustc_mir/lib.rs b/src/librustc_mir/lib.rs
index ccfc15b..909f969 100644
--- a/src/librustc_mir/lib.rs
+++ b/src/librustc_mir/lib.rs
@@ -26,39 +26,21 @@
 #![feature(slice_concat_ext)]
 #![feature(try_from)]
 #![feature(reverse_bits)]
+#![feature(try_blocks)]
 
 #![recursion_limit="256"]
 
-extern crate arena;
+#![deny(rust_2018_idioms)]
+#![allow(explicit_outlives_requirements)]
 
-#[macro_use]
-extern crate bitflags;
 #[macro_use] extern crate log;
-extern crate either;
-extern crate graphviz as dot;
-extern crate polonius_engine;
 #[macro_use]
 extern crate rustc;
 #[macro_use] extern crate rustc_data_structures;
-extern crate serialize as rustc_serialize;
-extern crate rustc_errors;
+#[allow(unused_extern_crates)]
+extern crate serialize as rustc_serialize; // used by deriving
 #[macro_use]
 extern crate syntax;
-extern crate syntax_pos;
-extern crate rustc_target;
-extern crate log_settings;
-extern crate rustc_apfloat;
-extern crate byteorder;
-extern crate core;
-extern crate smallvec;
-
-// Once we can use edition 2018 in the compiler,
-// replace this with real try blocks.
-macro_rules! try_block {
-    ($($inside:tt)*) => (
-        (||{ ::std::ops::Try::from_ok({ $($inside)* }) })()
-    )
-}
 
 mod diagnostics;
 
@@ -77,7 +59,7 @@
 pub use hair::pattern::check_crate as matchck_crate;
 use rustc::ty::query::Providers;
 
-pub fn provide(providers: &mut Providers) {
+pub fn provide(providers: &mut Providers<'_>) {
     borrow_check::provide(providers);
     shim::provide(providers);
     transform::provide(providers);
diff --git a/src/librustc_mir/lints.rs b/src/librustc_mir/lints.rs
index 8ded31d..6b6e8fc 100644
--- a/src/librustc_mir/lints.rs
+++ b/src/librustc_mir/lints.rs
@@ -18,7 +18,7 @@
 }
 
 fn check_fn_for_unconditional_recursion(tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                                        fn_kind: FnKind,
+                                        fn_kind: FnKind<'_>,
                                         mir: &Mir<'tcx>,
                                         def_id: DefId) {
     if let FnKind::Closure(_) = fn_kind {
diff --git a/src/librustc_mir/monomorphize/collector.rs b/src/librustc_mir/monomorphize/collector.rs
index e713ab1..a76aa74 100644
--- a/src/librustc_mir/monomorphize/collector.rs
+++ b/src/librustc_mir/monomorphize/collector.rs
@@ -189,11 +189,11 @@
 use rustc::mir::mono::MonoItem;
 use rustc::mir::interpret::{Scalar, GlobalId, AllocKind, ErrorHandled};
 
-use monomorphize::{self, Instance};
+use crate::monomorphize::{self, Instance};
 use rustc::util::nodemap::{FxHashSet, FxHashMap, DefIdMap};
 use rustc::util::common::time;
 
-use monomorphize::item::{MonoItemExt, DefPathBasedNames, InstantiationMode};
+use crate::monomorphize::item::{MonoItemExt, DefPathBasedNames, InstantiationMode};
 
 use rustc_data_structures::bit_set::GrowableBitSet;
 use rustc_data_structures::sync::{MTRef, MTLock, ParallelIterator, par_iter};
@@ -450,8 +450,8 @@
     if recursion_depth > *tcx.sess.recursion_limit.get() {
         let error = format!("reached the recursion limit while instantiating `{}`",
                             instance);
-        if let Some(node_id) = tcx.hir().as_local_node_id(def_id) {
-            tcx.sess.span_fatal(tcx.hir().span(node_id), &error);
+        if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
+            tcx.sess.span_fatal(tcx.hir().span_by_hir_id(hir_id), &error);
         } else {
             tcx.sess.fatal(&error);
         }
@@ -482,8 +482,8 @@
         let instance_name = instance.to_string();
         let msg = format!("reached the type-length limit while instantiating `{:.64}...`",
                           instance_name);
-        let mut diag = if let Some(node_id) = tcx.hir().as_local_node_id(instance.def_id()) {
-            tcx.sess.struct_span_fatal(tcx.hir().span(node_id), &msg)
+        let mut diag = if let Some(hir_id) = tcx.hir().as_local_hir_id(instance.def_id()) {
+            tcx.sess.struct_span_fatal(tcx.hir().span_by_hir_id(hir_id), &msg)
         } else {
             tcx.sess.struct_fatal(&msg)
         };
diff --git a/src/librustc_mir/monomorphize/item.rs b/src/librustc_mir/monomorphize/item.rs
index 431cc0d..d3381f4 100644
--- a/src/librustc_mir/monomorphize/item.rs
+++ b/src/librustc_mir/monomorphize/item.rs
@@ -1,4 +1,4 @@
-use monomorphize::Instance;
+use crate::monomorphize::Instance;
 use rustc::hir;
 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
 use rustc::session::config::OptLevel;
diff --git a/src/librustc_mir/monomorphize/partitioning.rs b/src/librustc_mir/monomorphize/partitioning.rs
index 569e4c8..d4c7ebe 100644
--- a/src/librustc_mir/monomorphize/partitioning.rs
+++ b/src/librustc_mir/monomorphize/partitioning.rs
@@ -111,9 +111,9 @@
 use rustc::util::nodemap::{DefIdSet, FxHashMap, FxHashSet};
 use rustc::mir::mono::MonoItem;
 
-use monomorphize::collector::InliningMap;
-use monomorphize::collector::{self, MonoItemCollectionMode};
-use monomorphize::item::{MonoItemExt, InstantiationMode};
+use crate::monomorphize::collector::InliningMap;
+use crate::monomorphize::collector::{self, MonoItemCollectionMode};
+use crate::monomorphize::item::{MonoItemExt, InstantiationMode};
 
 pub use rustc::mir::mono::CodegenUnit;
 
@@ -146,7 +146,7 @@
         WorkProductId::from_cgu_name(&self.name().as_str())
     }
 
-    fn work_product(&self, tcx: TyCtxt) -> WorkProduct {
+    fn work_product(&self, tcx: TyCtxt<'_, '_, '_>) -> WorkProduct {
         let work_product_id = self.work_product_id();
         tcx.dep_graph
            .previous_work_product(&work_product_id)
@@ -213,7 +213,7 @@
 }
 
 // Anything we can't find a proper codegen unit for goes into this.
-fn fallback_cgu_name(name_builder: &mut CodegenUnitNameBuilder) -> InternedString {
+fn fallback_cgu_name(name_builder: &mut CodegenUnitNameBuilder<'_, '_, '_>) -> InternedString {
     name_builder.build_cgu_name(LOCAL_CRATE, &["fallback"], Some("cgu"))
 }
 
@@ -536,7 +536,7 @@
     }
 }
 
-fn default_visibility(tcx: TyCtxt, id: DefId, is_generic: bool) -> Visibility {
+fn default_visibility(tcx: TyCtxt<'_, '_, '_>, id: DefId, is_generic: bool) -> Visibility {
     if !tcx.sess.target.target.options.default_hidden_visibility {
         return Visibility::Default
     }
@@ -795,8 +795,8 @@
 
 type CguNameCache = FxHashMap<(DefId, bool), InternedString>;
 
-fn compute_codegen_unit_name(tcx: TyCtxt,
-                             name_builder: &mut CodegenUnitNameBuilder,
+fn compute_codegen_unit_name(tcx: TyCtxt<'_, '_, '_>,
+                             name_builder: &mut CodegenUnitNameBuilder<'_, '_, '_>,
                              def_id: DefId,
                              volatile: bool,
                              cache: &mut CguNameCache)
@@ -855,7 +855,7 @@
     }).clone()
 }
 
-fn numbered_codegen_unit_name(name_builder: &mut CodegenUnitNameBuilder,
+fn numbered_codegen_unit_name(name_builder: &mut CodegenUnitNameBuilder<'_, '_, '_>,
                               index: usize)
                               -> InternedString {
     name_builder.build_cgu_name_no_mangle(LOCAL_CRATE, &["cgu"], Some(index))
@@ -929,7 +929,7 @@
 
     tcx.sess.abort_if_errors();
 
-    ::monomorphize::assert_symbols_are_distinct(tcx, items.iter());
+    crate::monomorphize::assert_symbols_are_distinct(tcx, items.iter());
 
     let strategy = if tcx.sess.opts.incremental.is_some() {
         PartitioningStrategy::PerModule
@@ -1013,7 +1013,7 @@
     (Arc::new(mono_items), Arc::new(codegen_units))
 }
 
-pub fn provide(providers: &mut Providers) {
+pub fn provide(providers: &mut Providers<'_>) {
     providers.collect_and_partition_mono_items =
         collect_and_partition_mono_items;
 
diff --git a/src/librustc_mir/shim.rs b/src/librustc_mir/shim.rs
index 751815e..09b8165 100644
--- a/src/librustc_mir/shim.rs
+++ b/src/librustc_mir/shim.rs
@@ -16,12 +16,14 @@
 use std::fmt;
 use std::iter;
 
-use transform::{add_moves_for_packed_drops, add_call_guards};
-use transform::{remove_noop_landing_pads, no_landing_pads, simplify};
-use util::elaborate_drops::{self, DropElaborator, DropStyle, DropFlagMode};
-use util::patch::MirPatch;
+use crate::transform::{
+    add_moves_for_packed_drops, add_call_guards,
+    remove_noop_landing_pads, no_landing_pads, simplify, run_passes
+};
+use crate::util::elaborate_drops::{self, DropElaborator, DropStyle, DropFlagMode};
+use crate::util::patch::MirPatch;
 
-pub fn provide(providers: &mut Providers) {
+pub fn provide(providers: &mut Providers<'_>) {
     providers.mir_shims = make_shim;
 }
 
@@ -113,12 +115,15 @@
         }
     };
     debug!("make_shim({:?}) = untransformed {:?}", instance, result);
-    add_moves_for_packed_drops::add_moves_for_packed_drops(
-        tcx, &mut result, instance.def_id());
-    no_landing_pads::no_landing_pads(tcx, &mut result);
-    remove_noop_landing_pads::remove_noop_landing_pads(tcx, &mut result);
-    simplify::simplify_cfg(&mut result);
-    add_call_guards::CriticalCallEdges.add_call_guards(&mut result);
+
+    run_passes(tcx, &mut result, instance, MirPhase::Const, &[
+        &add_moves_for_packed_drops::AddMovesForPackedDrops,
+        &no_landing_pads::NoLandingPads,
+        &remove_noop_landing_pads::RemoveNoopLandingPads,
+        &simplify::SimplifyCfg::new("make_shim"),
+        &add_call_guards::CriticalCallEdges,
+    ]);
+
     debug!("make_shim({:?}) = {:?}", instance, result);
 
     tcx.alloc_mir(result)
@@ -138,7 +143,7 @@
     Direct(DefId),
 }
 
-fn temp_decl(mutability: Mutability, ty: Ty, span: Span) -> LocalDecl {
+fn temp_decl(mutability: Mutability, ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
     let source_info = SourceInfo { scope: OUTERMOST_SOURCE_SCOPE, span };
     LocalDecl {
         mutability,
@@ -259,7 +264,7 @@
 }
 
 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
-    fn fmt(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
+    fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
         Ok(())
     }
 }
@@ -459,7 +464,7 @@
             span: self.span,
             ty: func_ty,
             user_ty: None,
-            literal: tcx.intern_lazy_const(ty::LazyConst::Evaluated(
+            literal: tcx.mk_lazy_const(ty::LazyConst::Evaluated(
                 ty::Const::zero_sized(func_ty),
             )),
         });
@@ -521,7 +526,7 @@
             span: self.span,
             ty: self.tcx.types.usize,
             user_ty: None,
-            literal: self.tcx.intern_lazy_const(ty::LazyConst::Evaluated(
+            literal: self.tcx.mk_lazy_const(ty::LazyConst::Evaluated(
                 ty::Const::from_usize(self.tcx, value),
             )),
         }
@@ -759,7 +764,7 @@
                 span,
                 ty,
                 user_ty: None,
-                literal: tcx.intern_lazy_const(ty::LazyConst::Evaluated(
+                literal: tcx.mk_lazy_const(ty::LazyConst::Evaluated(
                     ty::Const::zero_sized(ty)
                 )),
              }),
diff --git a/src/librustc_mir/transform/add_call_guards.rs b/src/librustc_mir/transform/add_call_guards.rs
index 3ea1c8e..88042d6 100644
--- a/src/librustc_mir/transform/add_call_guards.rs
+++ b/src/librustc_mir/transform/add_call_guards.rs
@@ -1,7 +1,7 @@
 use rustc::ty::TyCtxt;
 use rustc::mir::*;
 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
-use transform::{MirPass, MirSource};
+use crate::transform::{MirPass, MirSource};
 
 #[derive(PartialEq)]
 pub enum AddCallGuards {
@@ -33,14 +33,14 @@
 impl MirPass for AddCallGuards {
     fn run_pass<'a, 'tcx>(&self,
                           _tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          _src: MirSource,
+                          _src: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>) {
         self.add_call_guards(mir);
     }
 }
 
 impl AddCallGuards {
-    pub fn add_call_guards(&self, mir: &mut Mir) {
+    pub fn add_call_guards(&self, mir: &mut Mir<'_>) {
         let pred_count: IndexVec<_, _> =
             mir.predecessors().iter().map(|ps| ps.len()).collect();
 
diff --git a/src/librustc_mir/transform/add_moves_for_packed_drops.rs b/src/librustc_mir/transform/add_moves_for_packed_drops.rs
index 8ec6902..4d4c89b 100644
--- a/src/librustc_mir/transform/add_moves_for_packed_drops.rs
+++ b/src/librustc_mir/transform/add_moves_for_packed_drops.rs
@@ -2,9 +2,9 @@
 use rustc::mir::*;
 use rustc::ty::TyCtxt;
 
-use transform::{MirPass, MirSource};
-use util::patch::MirPatch;
-use util;
+use crate::transform::{MirPass, MirSource};
+use crate::util::patch::MirPatch;
+use crate::util;
 
 // This pass moves values being dropped that are within a packed
 // struct to a separate local before dropping them, to ensure that
@@ -42,11 +42,11 @@
 impl MirPass for AddMovesForPackedDrops {
     fn run_pass<'a, 'tcx>(&self,
                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          src: MirSource,
+                          src: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>)
     {
         debug!("add_moves_for_packed_drops({:?} @ {:?})", src, mir.span);
-        add_moves_for_packed_drops(tcx, mir, src.def_id);
+        add_moves_for_packed_drops(tcx, mir, src.def_id());
     }
 }
 
diff --git a/src/librustc_mir/transform/add_retag.rs b/src/librustc_mir/transform/add_retag.rs
index 3d5897b..e66c11a 100644
--- a/src/librustc_mir/transform/add_retag.rs
+++ b/src/librustc_mir/transform/add_retag.rs
@@ -6,7 +6,7 @@
 
 use rustc::ty::{self, Ty, TyCtxt};
 use rustc::mir::*;
-use transform::{MirPass, MirSource};
+use crate::transform::{MirPass, MirSource};
 
 pub struct AddRetag;
 
@@ -77,7 +77,7 @@
 impl MirPass for AddRetag {
     fn run_pass<'a, 'tcx>(&self,
                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          _src: MirSource,
+                          _src: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>)
     {
         if !tcx.sess.opts.debugging_opts.mir_emit_retag {
diff --git a/src/librustc_mir/transform/check_unsafety.rs b/src/librustc_mir/transform/check_unsafety.rs
index ab8da2f..b2e1afc 100644
--- a/src/librustc_mir/transform/check_unsafety.rs
+++ b/src/librustc_mir/transform/check_unsafety.rs
@@ -17,7 +17,7 @@
 
 use std::ops::Bound;
 
-use util;
+use crate::util;
 
 pub struct UnsafetyChecker<'a, 'tcx: 'a> {
     mir: &'a Mir<'tcx>,
@@ -458,7 +458,7 @@
     }
 }
 
-pub(crate) fn provide(providers: &mut Providers) {
+pub(crate) fn provide(providers: &mut Providers<'_>) {
     *providers = Providers {
         unsafety_check_result,
         unsafe_derive_on_repr_packed,
@@ -575,7 +575,7 @@
 }
 
 /// Return the NodeId for an enclosing scope that is also `unsafe`
-fn is_enclosed(tcx: TyCtxt,
+fn is_enclosed(tcx: TyCtxt<'_, '_, '_>,
                used_unsafe: &FxHashSet<ast::NodeId>,
                id: ast::NodeId) -> Option<(String, ast::NodeId)> {
     let parent_id = tcx.hir().get_parent_node(id);
@@ -598,7 +598,9 @@
     }
 }
 
-fn report_unused_unsafe(tcx: TyCtxt, used_unsafe: &FxHashSet<ast::NodeId>, id: ast::NodeId) {
+fn report_unused_unsafe(tcx: TyCtxt<'_, '_, '_>,
+                        used_unsafe: &FxHashSet<ast::NodeId>,
+                        id: ast::NodeId) {
     let span = tcx.sess.source_map().def_span(tcx.hir().span(id));
     let msg = "unnecessary `unsafe` block";
     let mut db = tcx.struct_span_lint_node(UNUSED_UNSAFE, id, span, msg);
diff --git a/src/librustc_mir/transform/cleanup_post_borrowck.rs b/src/librustc_mir/transform/cleanup_post_borrowck.rs
index e6df6b7..890d2c56 100644
--- a/src/librustc_mir/transform/cleanup_post_borrowck.rs
+++ b/src/librustc_mir/transform/cleanup_post_borrowck.rs
@@ -26,7 +26,7 @@
 use rustc::mir::{Statement, StatementKind};
 use rustc::mir::visit::MutVisitor;
 use rustc::ty::TyCtxt;
-use transform::{MirPass, MirSource};
+use crate::transform::{MirPass, MirSource};
 
 pub struct CleanAscribeUserType;
 
@@ -35,7 +35,7 @@
 impl MirPass for CleanAscribeUserType {
     fn run_pass<'a, 'tcx>(&self,
                           _tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          _source: MirSource,
+                          _source: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>) {
         let mut delete = DeleteAscribeUserType;
         delete.visit_mir(mir);
@@ -69,7 +69,7 @@
 impl MirPass for CleanFakeReadsAndBorrows {
     fn run_pass<'a, 'tcx>(&self,
                           _tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          _source: MirSource,
+                          _source: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>) {
         let mut delete_reads = DeleteAndRecordFakeReads::default();
         delete_reads.visit_mir(mir);
diff --git a/src/librustc_mir/transform/const_prop.rs b/src/librustc_mir/transform/const_prop.rs
index dc556a1..018f71c 100644
--- a/src/librustc_mir/transform/const_prop.rs
+++ b/src/librustc_mir/transform/const_prop.rs
@@ -18,19 +18,19 @@
     HasTyCtxt, TargetDataLayout, HasDataLayout,
 };
 
-use interpret::{self, EvalContext, ScalarMaybeUndef, Immediate, OpTy, MemoryKind};
-use const_eval::{
+use crate::interpret::{self, EvalContext, ScalarMaybeUndef, Immediate, OpTy, MemoryKind};
+use crate::const_eval::{
     CompileTimeInterpreter, error_to_const_error, eval_promoted, mk_eval_cx,
     lazy_const_to_op,
 };
-use transform::{MirPass, MirSource};
+use crate::transform::{MirPass, MirSource};
 
 pub struct ConstProp;
 
 impl MirPass for ConstProp {
     fn run_pass<'a, 'tcx>(&self,
                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          source: MirSource,
+                          source: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>) {
         // will be evaluated by miri and produce its errors there
         if source.promoted.is_some() {
@@ -38,11 +38,11 @@
         }
 
         use rustc::hir::map::blocks::FnLikeNode;
-        let node_id = tcx.hir().as_local_node_id(source.def_id)
+        let node_id = tcx.hir().as_local_node_id(source.def_id())
                              .expect("Non-local call to local provider is_const_fn");
 
         let is_fn_like = FnLikeNode::from_node(tcx.hir().get(node_id)).is_some();
-        let is_assoc_const = match tcx.describe_def(source.def_id) {
+        let is_assoc_const = match tcx.describe_def(source.def_id()) {
             Some(Def::AssociatedConst(_)) => true,
             _ => false,
         };
@@ -50,11 +50,11 @@
         // Only run const prop on functions, methods, closures and associated constants
         if !is_fn_like && !is_assoc_const  {
             // skip anon_const/statics/consts because they'll be evaluated by miri anyway
-            trace!("ConstProp skipped for {:?}", source.def_id);
+            trace!("ConstProp skipped for {:?}", source.def_id());
             return
         }
 
-        trace!("ConstProp starting for {:?}", source.def_id);
+        trace!("ConstProp starting for {:?}", source.def_id());
 
         // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
         // constants, instead of just checking for const-folding succeeding.
@@ -63,7 +63,7 @@
         let mut optimization_finder = ConstPropagator::new(mir, tcx, source);
         optimization_finder.visit_mir(mir);
 
-        trace!("ConstProp done for {:?}", source.def_id);
+        trace!("ConstProp done for {:?}", source.def_id());
     }
 }
 
@@ -74,7 +74,7 @@
     ecx: EvalContext<'a, 'mir, 'tcx, CompileTimeInterpreter<'a, 'mir, 'tcx>>,
     mir: &'mir Mir<'tcx>,
     tcx: TyCtxt<'a, 'tcx, 'tcx>,
-    source: MirSource,
+    source: MirSource<'tcx>,
     places: IndexVec<Local, Option<Const<'tcx>>>,
     can_const_prop: IndexVec<Local, bool>,
     param_env: ParamEnv<'tcx>,
@@ -107,10 +107,10 @@
     fn new(
         mir: &'mir Mir<'tcx>,
         tcx: TyCtxt<'a, 'tcx, 'tcx>,
-        source: MirSource,
+        source: MirSource<'tcx>,
     ) -> ConstPropagator<'a, 'mir, 'tcx> {
-        let param_env = tcx.param_env(source.def_id);
-        let ecx = mk_eval_cx(tcx, tcx.def_span(source.def_id), param_env);
+        let param_env = tcx.param_env(source.def_id());
+        let ecx = mk_eval_cx(tcx, tcx.def_span(source.def_id()), param_env);
         ConstPropagator {
             ecx,
             mir,
@@ -284,13 +284,13 @@
                 _ => None,
             },
             Place::Promoted(ref promoted) => {
-                let generics = self.tcx.generics_of(self.source.def_id);
+                let generics = self.tcx.generics_of(self.source.def_id());
                 if generics.requires_monomorphization(self.tcx) {
                     // FIXME: can't handle code with generics
                     return None;
                 }
-                let substs = Substs::identity_for_item(self.tcx, self.source.def_id);
-                let instance = Instance::new(self.source.def_id, substs);
+                let substs = Substs::identity_for_item(self.tcx, self.source.def_id());
+                let instance = Instance::new(self.source.def_id(), substs);
                 let cid = GlobalId {
                     instance,
                     promoted: Some(promoted.0),
@@ -358,10 +358,10 @@
                 )))
             }
             Rvalue::UnaryOp(op, ref arg) => {
-                let def_id = if self.tcx.is_closure(self.source.def_id) {
-                    self.tcx.closure_base_def_id(self.source.def_id)
+                let def_id = if self.tcx.is_closure(self.source.def_id()) {
+                    self.tcx.closure_base_def_id(self.source.def_id())
                 } else {
-                    self.source.def_id
+                    self.source.def_id()
                 };
                 let generics = self.tcx.generics_of(def_id);
                 if generics.requires_monomorphization(self.tcx) {
@@ -398,10 +398,10 @@
             Rvalue::BinaryOp(op, ref left, ref right) => {
                 trace!("rvalue binop {:?} for {:?} and {:?}", op, left, right);
                 let right = self.eval_operand(right, source_info)?;
-                let def_id = if self.tcx.is_closure(self.source.def_id) {
-                    self.tcx.closure_base_def_id(self.source.def_id)
+                let def_id = if self.tcx.is_closure(self.source.def_id()) {
+                    self.tcx.closure_base_def_id(self.source.def_id())
                 } else {
-                    self.source.def_id
+                    self.source.def_id()
                 };
                 let generics = self.tcx.generics_of(def_id);
                 if generics.requires_monomorphization(self.tcx) {
@@ -486,7 +486,7 @@
 
 impl CanConstProp {
     /// returns true if `local` can be propagated
-    fn check(mir: &Mir) -> IndexVec<Local, bool> {
+    fn check(mir: &Mir<'_>) -> IndexVec<Local, bool> {
         let mut cpv = CanConstProp {
             can_const_prop: IndexVec::from_elem(true, &mir.local_decls),
             found_assignment: IndexVec::from_elem(false, &mir.local_decls),
@@ -608,7 +608,7 @@
                     let node_id = self
                         .tcx
                         .hir()
-                        .as_local_node_id(self.source.def_id)
+                        .as_local_node_id(self.source.def_id())
                         .expect("some part of a failing const eval must be local");
                     use rustc::mir::interpret::EvalErrorKind::*;
                     let msg = match msg {
diff --git a/src/librustc_mir/transform/copy_prop.rs b/src/librustc_mir/transform/copy_prop.rs
index 55e1407..7d907ca 100644
--- a/src/librustc_mir/transform/copy_prop.rs
+++ b/src/librustc_mir/transform/copy_prop.rs
@@ -22,15 +22,15 @@
 use rustc::mir::{Constant, Local, LocalKind, Location, Place, Mir, Operand, Rvalue, StatementKind};
 use rustc::mir::visit::MutVisitor;
 use rustc::ty::TyCtxt;
-use transform::{MirPass, MirSource};
-use util::def_use::DefUseAnalysis;
+use crate::transform::{MirPass, MirSource};
+use crate::util::def_use::DefUseAnalysis;
 
 pub struct CopyPropagation;
 
 impl MirPass for CopyPropagation {
     fn run_pass<'a, 'tcx>(&self,
                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          _source: MirSource,
+                          _source: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>) {
         // We only run when the MIR optimization level is > 1.
         // This avoids a slow pass, and messing up debug info.
@@ -173,7 +173,7 @@
 }
 
 impl<'tcx> Action<'tcx> {
-    fn local_copy(mir: &Mir<'tcx>, def_use_analysis: &DefUseAnalysis, src_place: &Place<'tcx>)
+    fn local_copy(mir: &Mir<'tcx>, def_use_analysis: &DefUseAnalysis<'_>, src_place: &Place<'tcx>)
                   -> Option<Action<'tcx>> {
         // The source must be a local.
         let src_local = if let Place::Local(local) = *src_place {
diff --git a/src/librustc_mir/transform/deaggregator.rs b/src/librustc_mir/transform/deaggregator.rs
index a2fe9de..9061dff 100644
--- a/src/librustc_mir/transform/deaggregator.rs
+++ b/src/librustc_mir/transform/deaggregator.rs
@@ -1,14 +1,14 @@
 use rustc::ty::TyCtxt;
 use rustc::mir::*;
 use rustc_data_structures::indexed_vec::Idx;
-use transform::{MirPass, MirSource};
+use crate::transform::{MirPass, MirSource};
 
 pub struct Deaggregator;
 
 impl MirPass for Deaggregator {
     fn run_pass<'a, 'tcx>(&self,
                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          _source: MirSource,
+                          _source: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>) {
         let (basic_blocks, local_decls) = mir.basic_blocks_and_local_decls_mut();
         let local_decls = &*local_decls;
diff --git a/src/librustc_mir/transform/dump_mir.rs b/src/librustc_mir/transform/dump_mir.rs
index 8fabb2d..81e48fe 100644
--- a/src/librustc_mir/transform/dump_mir.rs
+++ b/src/librustc_mir/transform/dump_mir.rs
@@ -8,8 +8,8 @@
 use rustc::mir::Mir;
 use rustc::session::config::{OutputFilenames, OutputType};
 use rustc::ty::TyCtxt;
-use transform::{MirPass, MirSource};
-use util as mir_util;
+use crate::transform::{MirPass, MirSource};
+use crate::util as mir_util;
 
 pub struct Marker(pub &'static str);
 
@@ -20,7 +20,7 @@
 
     fn run_pass<'a, 'tcx>(&self,
                           _tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          _source: MirSource,
+                          _source: MirSource<'tcx>,
                           _mir: &mut Mir<'tcx>)
     {
     }
@@ -31,7 +31,7 @@
 }
 
 impl fmt::Display for Disambiguator {
-    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
         let title = if self.is_after { "after" } else { "before" };
         write!(formatter, "{}", title)
     }
@@ -41,7 +41,7 @@
 pub fn on_mir_pass<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                              pass_num: &dyn fmt::Display,
                              pass_name: &str,
-                             source: MirSource,
+                             source: MirSource<'tcx>,
                              mir: &Mir<'tcx>,
                              is_after: bool) {
     if mir_util::dump_enabled(tcx, pass_name, source) {
diff --git a/src/librustc_mir/transform/elaborate_drops.rs b/src/librustc_mir/transform/elaborate_drops.rs
index 06e16de..c56acba 100644
--- a/src/librustc_mir/transform/elaborate_drops.rs
+++ b/src/librustc_mir/transform/elaborate_drops.rs
@@ -1,10 +1,14 @@
-use dataflow::move_paths::{HasMoveData, MoveData, MovePathIndex, LookupResult};
-use dataflow::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
-use dataflow::{DataflowResults};
-use dataflow::{on_all_children_bits, on_all_drop_children_bits};
-use dataflow::{drop_flag_effects_for_location, on_lookup_result_bits};
-use dataflow::MoveDataParamEnv;
-use dataflow::{self, do_dataflow, DebugFormatted};
+use crate::dataflow::move_paths::{HasMoveData, MoveData, MovePathIndex, LookupResult};
+use crate::dataflow::{MaybeInitializedPlaces, MaybeUninitializedPlaces};
+use crate::dataflow::{DataflowResults};
+use crate::dataflow::{on_all_children_bits, on_all_drop_children_bits};
+use crate::dataflow::{drop_flag_effects_for_location, on_lookup_result_bits};
+use crate::dataflow::MoveDataParamEnv;
+use crate::dataflow::{self, do_dataflow, DebugFormatted};
+use crate::transform::{MirPass, MirSource};
+use crate::util::patch::MirPatch;
+use crate::util::elaborate_drops::{DropFlagState, Unwind, elaborate_drop};
+use crate::util::elaborate_drops::{DropElaborator, DropStyle, DropFlagMode};
 use rustc::ty::{self, TyCtxt};
 use rustc::ty::layout::VariantIdx;
 use rustc::mir::*;
@@ -13,23 +17,19 @@
 use std::fmt;
 use syntax::ast;
 use syntax_pos::Span;
-use transform::{MirPass, MirSource};
-use util::patch::MirPatch;
-use util::elaborate_drops::{DropFlagState, Unwind, elaborate_drop};
-use util::elaborate_drops::{DropElaborator, DropStyle, DropFlagMode};
 
 pub struct ElaborateDrops;
 
 impl MirPass for ElaborateDrops {
     fn run_pass<'a, 'tcx>(&self,
                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          src: MirSource,
+                          src: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>)
     {
         debug!("elaborate_drops({:?} @ {:?})", src, mir.span);
 
-        let id = tcx.hir().as_local_node_id(src.def_id).unwrap();
-        let param_env = tcx.param_env(src.def_id).with_reveal_all();
+        let id = tcx.hir().as_local_node_id(src.def_id()).unwrap();
+        let param_env = tcx.param_env(src.def_id()).with_reveal_all();
         let move_data = match MoveData::gather_moves(mir, tcx) {
             Ok(move_data) => move_data,
             Err((move_data, _move_errors)) => {
@@ -174,7 +174,7 @@
 }
 
 impl<'a, 'b, 'tcx> fmt::Debug for Elaborator<'a, 'b, 'tcx> {
-    fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
         Ok(())
     }
 }
@@ -533,7 +533,7 @@
             span,
             ty: self.tcx.types.bool,
             user_ty: None,
-            literal: self.tcx.intern_lazy_const(ty::LazyConst::Evaluated(
+            literal: self.tcx.mk_lazy_const(ty::LazyConst::Evaluated(
                 ty::Const::from_bool(self.tcx, val),
             )),
         })))
diff --git a/src/librustc_mir/transform/erase_regions.rs b/src/librustc_mir/transform/erase_regions.rs
index b464b7d..d59bb3e 100644
--- a/src/librustc_mir/transform/erase_regions.rs
+++ b/src/librustc_mir/transform/erase_regions.rs
@@ -8,7 +8,7 @@
 use rustc::ty::{self, Ty, TyCtxt};
 use rustc::mir::*;
 use rustc::mir::visit::{MutVisitor, TyContext};
-use transform::{MirPass, MirSource};
+use crate::transform::{MirPass, MirSource};
 
 struct EraseRegionsVisitor<'a, 'tcx: 'a> {
     tcx: TyCtxt<'a, 'tcx, 'tcx>,
@@ -53,7 +53,7 @@
 impl MirPass for EraseRegions {
     fn run_pass<'a, 'tcx>(&self,
                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          _: MirSource,
+                          _: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>) {
         EraseRegionsVisitor::new(tcx).visit_mir(mir);
     }
diff --git a/src/librustc_mir/transform/generator.rs b/src/librustc_mir/transform/generator.rs
index f5cc6a4..0866b87 100644
--- a/src/librustc_mir/transform/generator.rs
+++ b/src/librustc_mir/transform/generator.rs
@@ -56,19 +56,19 @@
 use rustc::ty::{self, TyCtxt, AdtDef, Ty};
 use rustc::ty::layout::VariantIdx;
 use rustc::ty::subst::Substs;
-use util::dump_mir;
-use util::liveness::{self, IdentityMap};
 use rustc_data_structures::fx::FxHashMap;
 use rustc_data_structures::indexed_vec::Idx;
 use rustc_data_structures::bit_set::BitSet;
 use std::borrow::Cow;
 use std::iter::once;
 use std::mem;
-use transform::{MirPass, MirSource};
-use transform::simplify;
-use transform::no_landing_pads::no_landing_pads;
-use dataflow::{do_dataflow, DebugFormatted, state_for_location};
-use dataflow::{MaybeStorageLive, HaveBeenBorrowedLocals};
+use crate::transform::{MirPass, MirSource};
+use crate::transform::simplify;
+use crate::transform::no_landing_pads::no_landing_pads;
+use crate::dataflow::{do_dataflow, DebugFormatted, state_for_location};
+use crate::dataflow::{MaybeStorageLive, HaveBeenBorrowedLocals};
+use crate::util::dump_mir;
+use crate::util::liveness::{self, IdentityMap};
 
 pub struct StateTransform;
 
@@ -198,7 +198,7 @@
             span: source_info.span,
             ty: self.tcx.types.u32,
             user_ty: None,
-            literal: self.tcx.intern_lazy_const(ty::LazyConst::Evaluated(ty::Const::from_bits(
+            literal: self.tcx.mk_lazy_const(ty::LazyConst::Evaluated(ty::Const::from_bits(
                 self.tcx,
                 state_disc.into(),
                 ty::ParamEnv::empty().and(self.tcx.types.u32)
@@ -376,14 +376,14 @@
 fn locals_live_across_suspend_points(
     tcx: TyCtxt<'a, 'tcx, 'tcx>,
     mir: &Mir<'tcx>,
-    source: MirSource,
+    source: MirSource<'tcx>,
     movable: bool,
 ) -> (
     liveness::LiveVarSet<Local>,
     FxHashMap<BasicBlock, liveness::LiveVarSet<Local>>,
 ) {
     let dead_unwinds = BitSet::new_empty(mir.basic_blocks().len());
-    let node_id = tcx.hir().as_local_node_id(source.def_id).unwrap();
+    let node_id = tcx.hir().as_local_node_id(source.def_id()).unwrap();
 
     // Calculate when MIR locals have live storage. This gives us an upper bound of their
     // lifetimes.
@@ -484,7 +484,7 @@
 }
 
 fn compute_layout<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                            source: MirSource,
+                            source: MirSource<'tcx>,
                             upvars: Vec<Ty<'tcx>>,
                             interior: Ty<'tcx>,
                             movable: bool,
@@ -581,9 +581,9 @@
 fn elaborate_generator_drops<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                        def_id: DefId,
                                        mir: &mut Mir<'tcx>) {
-    use util::elaborate_drops::{elaborate_drop, Unwind};
-    use util::patch::MirPatch;
-    use shim::DropShimElaborator;
+    use crate::util::elaborate_drops::{elaborate_drop, Unwind};
+    use crate::util::patch::MirPatch;
+    use crate::shim::DropShimElaborator;
 
     // Note that `elaborate_drops` only drops the upvars of a generator, and
     // this is ok because `open_drop` can only be reached within that own
@@ -635,7 +635,7 @@
                 tcx: TyCtxt<'a, 'tcx, 'tcx>,
                 transform: &TransformVisitor<'a, 'tcx>,
                 def_id: DefId,
-                source: MirSource,
+                source: MirSource<'tcx>,
                 gen_ty: Ty<'tcx>,
                 mir: &Mir<'tcx>,
                 drop_clean: BasicBlock) -> Mir<'tcx> {
@@ -731,7 +731,7 @@
             span: mir.span,
             ty: tcx.types.bool,
             user_ty: None,
-            literal: tcx.intern_lazy_const(ty::LazyConst::Evaluated(
+            literal: tcx.mk_lazy_const(ty::LazyConst::Evaluated(
                 ty::Const::from_bool(tcx, false),
             )),
         }),
@@ -758,7 +758,7 @@
         tcx: TyCtxt<'a, 'tcx, 'tcx>,
         transform: TransformVisitor<'a, 'tcx>,
         def_id: DefId,
-        source: MirSource,
+        source: MirSource<'tcx>,
         mir: &mut Mir<'tcx>) {
     // Poison the generator when it unwinds
     for block in mir.basic_blocks_mut() {
@@ -869,7 +869,7 @@
 impl MirPass for StateTransform {
     fn run_pass<'a, 'tcx>(&self,
                     tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                    source: MirSource,
+                    source: MirSource<'tcx>,
                     mir: &mut Mir<'tcx>) {
         let yield_ty = if let Some(yield_ty) = mir.yield_ty {
             yield_ty
@@ -880,7 +880,7 @@
 
         assert!(mir.generator_drop.is_none());
 
-        let def_id = source.def_id;
+        let def_id = source.def_id();
 
         // The first argument is the generator type passed by value
         let gen_ty = mir.local_decls.raw[1].ty;
diff --git a/src/librustc_mir/transform/inline.rs b/src/librustc_mir/transform/inline.rs
index 9f0907a..4cb7826 100644
--- a/src/librustc_mir/transform/inline.rs
+++ b/src/librustc_mir/transform/inline.rs
@@ -13,10 +13,10 @@
 
 use std::collections::VecDeque;
 use std::iter;
-use transform::{MirPass, MirSource};
+use crate::transform::{MirPass, MirSource};
 use super::simplify::{remove_dead_blocks, CfgSimplifier};
 
-use syntax::{attr};
+use syntax::attr;
 use rustc_target::spec::abi::Abi;
 
 const DEFAULT_THRESHOLD: usize = 50;
@@ -40,7 +40,7 @@
 impl MirPass for Inline {
     fn run_pass<'a, 'tcx>(&self,
                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          source: MirSource,
+                          source: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>) {
         if tcx.sess.opts.debugging_opts.mir_opt_level >= 2 {
             Inliner { tcx, source }.run_pass(mir);
@@ -50,7 +50,7 @@
 
 struct Inliner<'a, 'tcx: 'a> {
     tcx: TyCtxt<'a, 'tcx, 'tcx>,
-    source: MirSource,
+    source: MirSource<'tcx>,
 }
 
 impl<'a, 'tcx> Inliner<'a, 'tcx> {
@@ -69,10 +69,10 @@
 
         let mut callsites = VecDeque::new();
 
-        let param_env = self.tcx.param_env(self.source.def_id);
+        let param_env = self.tcx.param_env(self.source.def_id());
 
         // Only do inlining into fn bodies.
-        let id = self.tcx.hir().as_local_node_id(self.source.def_id).unwrap();
+        let id = self.tcx.hir().as_local_node_id(self.source.def_id()).unwrap();
         if self.tcx.hir().body_owner_kind(id).is_fn_or_closure() && self.source.promoted.is_none() {
             for (bb, bb_data) in caller_mir.basic_blocks().iter_enumerated() {
                 if let Some(callsite) = self.get_valid_function_call(bb,
@@ -274,7 +274,7 @@
 
         // FIXME: Give a bonus to functions with only a single caller
 
-        let param_env = tcx.param_env(self.source.def_id);
+        let param_env = tcx.param_env(self.source.def_id());
 
         let mut first_block = true;
         let mut cost = 0;
@@ -426,7 +426,7 @@
                 // Place could result in two different locations if `f`
                 // writes to `i`. To prevent this we need to create a temporary
                 // borrow of the place and pass the destination as `*temp` instead.
-                fn dest_needs_borrow(place: &Place) -> bool {
+                fn dest_needs_borrow(place: &Place<'_>) -> bool {
                     match *place {
                         Place::Projection(ref p) => {
                             match p.elem {
diff --git a/src/librustc_mir/transform/instcombine.rs b/src/librustc_mir/transform/instcombine.rs
index 2b5e761..2909157 100644
--- a/src/librustc_mir/transform/instcombine.rs
+++ b/src/librustc_mir/transform/instcombine.rs
@@ -6,14 +6,14 @@
 use rustc::util::nodemap::{FxHashMap, FxHashSet};
 use rustc_data_structures::indexed_vec::Idx;
 use std::mem;
-use transform::{MirPass, MirSource};
+use crate::transform::{MirPass, MirSource};
 
 pub struct InstCombine;
 
 impl MirPass for InstCombine {
     fn run_pass<'a, 'tcx>(&self,
                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          _: MirSource,
+                          _: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>) {
         // We only run when optimizing MIR (at any level).
         if tcx.sess.opts.debugging_opts.mir_opt_level == 0 {
diff --git a/src/librustc_mir/transform/lower_128bit.rs b/src/librustc_mir/transform/lower_128bit.rs
index d14e0f0..3d1f55e 100644
--- a/src/librustc_mir/transform/lower_128bit.rs
+++ b/src/librustc_mir/transform/lower_128bit.rs
@@ -5,15 +5,14 @@
 use rustc::mir::*;
 use rustc::ty::{List, Ty, TyCtxt, TyKind};
 use rustc_data_structures::indexed_vec::{Idx};
-use transform::{MirPass, MirSource};
-use syntax;
+use crate::transform::{MirPass, MirSource};
 
 pub struct Lower128Bit;
 
 impl MirPass for Lower128Bit {
     fn run_pass<'a, 'tcx>(&self,
                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          _src: MirSource,
+                          _src: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>) {
         let debugging_override = tcx.sess.opts.debugging_opts.lower_128bit_ops;
         let target_default = tcx.sess.host.options.i128_lowering;
@@ -182,7 +181,7 @@
     }
 }
 
-fn sign_of_128bit(ty: Ty) -> Option<bool> {
+fn sign_of_128bit(ty: Ty<'_>) -> Option<bool> {
     match ty.sty {
         TyKind::Int(syntax::ast::IntTy::I128) => Some(true),
         TyKind::Uint(syntax::ast::UintTy::U128) => Some(false),
diff --git a/src/librustc_mir/transform/mod.rs b/src/librustc_mir/transform/mod.rs
index a4f011b..44061e6 100644
--- a/src/librustc_mir/transform/mod.rs
+++ b/src/librustc_mir/transform/mod.rs
@@ -1,8 +1,8 @@
-use borrow_check::nll::type_check;
-use build;
+use crate::borrow_check::nll::type_check;
+use crate::build;
 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
 use rustc::mir::{Mir, MirPhase, Promoted};
-use rustc::ty::TyCtxt;
+use rustc::ty::{TyCtxt, InstanceDef};
 use rustc::ty::query::Providers;
 use rustc::ty::steal::Steal;
 use rustc::hir;
@@ -38,7 +38,7 @@
 pub mod lower_128bit;
 pub mod uniform_array_move_out;
 
-pub(crate) fn provide(providers: &mut Providers) {
+pub(crate) fn provide(providers: &mut Providers<'_>) {
     self::qualify_consts::provide(providers);
     self::check_unsafety::provide(providers);
     *providers = Providers {
@@ -104,20 +104,25 @@
 
 /// Where a specific Mir comes from.
 #[derive(Debug, Copy, Clone)]
-pub struct MirSource {
-    pub def_id: DefId,
+pub struct MirSource<'tcx> {
+    pub instance: InstanceDef<'tcx>,
 
     /// If `Some`, this is a promoted rvalue within the parent function.
     pub promoted: Option<Promoted>,
 }
 
-impl MirSource {
+impl<'tcx> MirSource<'tcx> {
     pub fn item(def_id: DefId) -> Self {
         MirSource {
-            def_id,
+            instance: InstanceDef::Item(def_id),
             promoted: None
         }
     }
+
+    #[inline]
+    pub fn def_id(&self) -> DefId {
+        self.instance.def_id()
+    }
 }
 
 /// Generates a default name for the pass based on the name of the
@@ -141,14 +146,14 @@
 
     fn run_pass<'a, 'tcx>(&self,
                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          source: MirSource,
+                          source: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>);
 }
 
 pub fn run_passes(
     tcx: TyCtxt<'a, 'tcx, 'tcx>,
     mir: &mut Mir<'tcx>,
-    def_id: DefId,
+    instance: InstanceDef<'tcx>,
     mir_phase: MirPhase,
     passes: &[&dyn MirPass],
 ) {
@@ -160,7 +165,7 @@
         }
 
         let source = MirSource {
-            def_id,
+            instance,
             promoted,
         };
         let mut index = 0;
@@ -198,7 +203,7 @@
     let _ = tcx.unsafety_check_result(def_id);
 
     let mut mir = tcx.mir_built(def_id).steal();
-    run_passes(tcx, &mut mir, def_id, MirPhase::Const, &[
+    run_passes(tcx, &mut mir, InstanceDef::Item(def_id), MirPhase::Const, &[
         // What we need to do constant evaluation.
         &simplify::SimplifyCfg::new("initial"),
         &type_check::TypeckMir,
@@ -217,7 +222,7 @@
     }
 
     let mut mir = tcx.mir_const(def_id).steal();
-    run_passes(tcx, &mut mir, def_id, MirPhase::Validated, &[
+    run_passes(tcx, &mut mir, InstanceDef::Item(def_id), MirPhase::Validated, &[
         // What we need to run borrowck etc.
         &qualify_consts::QualifyAndPromoteConstants,
         &simplify::SimplifyCfg::new("qualify-consts"),
@@ -235,7 +240,7 @@
     }
 
     let mut mir = tcx.mir_validated(def_id).steal();
-    run_passes(tcx, &mut mir, def_id, MirPhase::Optimized, &[
+    run_passes(tcx, &mut mir, InstanceDef::Item(def_id), MirPhase::Optimized, &[
         // Remove all things not needed by analysis
         &no_landing_pads::NoLandingPads,
         &simplify_branches::SimplifyBranches::new("initial"),
diff --git a/src/librustc_mir/transform/no_landing_pads.rs b/src/librustc_mir/transform/no_landing_pads.rs
index 2d13b06..089d9b9 100644
--- a/src/librustc_mir/transform/no_landing_pads.rs
+++ b/src/librustc_mir/transform/no_landing_pads.rs
@@ -4,14 +4,14 @@
 use rustc::ty::TyCtxt;
 use rustc::mir::*;
 use rustc::mir::visit::MutVisitor;
-use transform::{MirPass, MirSource};
+use crate::transform::{MirPass, MirSource};
 
 pub struct NoLandingPads;
 
 impl MirPass for NoLandingPads {
     fn run_pass<'a, 'tcx>(&self,
                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          _: MirSource,
+                          _: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>) {
         no_landing_pads(tcx, mir)
     }
diff --git a/src/librustc_mir/transform/promote_consts.rs b/src/librustc_mir/transform/promote_consts.rs
index 1602fc3..d1dc5cf 100644
--- a/src/librustc_mir/transform/promote_consts.rs
+++ b/src/librustc_mir/transform/promote_consts.rs
@@ -130,7 +130,8 @@
     }
 }
 
-pub fn collect_temps(mir: &Mir, rpo: &mut ReversePostorder) -> IndexVec<Local, TempState> {
+pub fn collect_temps(mir: &Mir<'_>,
+                     rpo: &mut ReversePostorder<'_, '_>) -> IndexVec<Local, TempState> {
     let mut collector = TempCollector {
         temps: IndexVec::from_elem(TempState::Undefined, &mir.local_decls),
         span: mir.span,
diff --git a/src/librustc_mir/transform/qualify_consts.rs b/src/librustc_mir/transform/qualify_consts.rs
index 7d1943e..76b8b83 100644
--- a/src/librustc_mir/transform/qualify_consts.rs
+++ b/src/librustc_mir/transform/qualify_consts.rs
@@ -27,10 +27,10 @@
 use std::fmt;
 use std::usize;
 
-use transform::{MirPass, MirSource};
+use crate::transform::{MirPass, MirSource};
 use super::promote_consts::{self, Candidate, TempState};
 
-bitflags! {
+bitflags::bitflags! {
     // Borrows of temporaries can be promoted only if
     // they have none of these qualifications, with
     // the exception of `STATIC_REF` (in statics only).
@@ -84,7 +84,7 @@
 }
 
 impl fmt::Display for Mode {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match *self {
             Mode::Const => write!(f, "constant"),
             Mode::Static | Mode::StaticMut => write!(f, "static"),
@@ -1128,7 +1128,7 @@
     }
 }
 
-pub fn provide(providers: &mut Providers) {
+pub fn provide(providers: &mut Providers<'_>) {
     *providers = Providers {
         mir_const_qualif,
         ..*providers
@@ -1159,7 +1159,7 @@
 impl MirPass for QualifyAndPromoteConstants {
     fn run_pass<'a, 'tcx>(&self,
                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          src: MirSource,
+                          src: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>) {
         // There's not really any point in promoting errorful MIR.
         if mir.return_ty().references_error() {
@@ -1171,7 +1171,7 @@
             return;
         }
 
-        let def_id = src.def_id;
+        let def_id = src.def_id();
         let id = tcx.hir().as_local_node_id(def_id).unwrap();
         let mut const_promoted_temps = None;
         let mode = match tcx.hir().body_owner_kind(id) {
@@ -1317,7 +1317,7 @@
     }
 }
 
-fn args_required_const(tcx: TyCtxt, def_id: DefId) -> Option<FxHashSet<usize>> {
+fn args_required_const(tcx: TyCtxt<'_, '_, '_>, def_id: DefId) -> Option<FxHashSet<usize>> {
     let attrs = tcx.get_attrs(def_id);
     let attr = attrs.iter().find(|a| a.check_name("rustc_args_required_const"))?;
     let mut ret = FxHashSet::default();
diff --git a/src/librustc_mir/transform/remove_noop_landing_pads.rs b/src/librustc_mir/transform/remove_noop_landing_pads.rs
index c8ef2de..68832b7 100644
--- a/src/librustc_mir/transform/remove_noop_landing_pads.rs
+++ b/src/librustc_mir/transform/remove_noop_landing_pads.rs
@@ -1,8 +1,8 @@
 use rustc::ty::TyCtxt;
 use rustc::mir::*;
 use rustc_data_structures::bit_set::BitSet;
-use transform::{MirPass, MirSource};
-use util::patch::MirPatch;
+use crate::transform::{MirPass, MirSource};
+use crate::util::patch::MirPatch;
 
 /// A pass that removes no-op landing pads and replaces jumps to them with
 /// `None`. This is important because otherwise LLVM generates terrible
@@ -24,7 +24,7 @@
 impl MirPass for RemoveNoopLandingPads {
     fn run_pass<'a, 'tcx>(&self,
                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          _src: MirSource,
+                          _src: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>) {
         remove_noop_landing_pads(tcx, mir);
     }
@@ -34,7 +34,7 @@
     fn is_nop_landing_pad(
         &self,
         bb: BasicBlock,
-        mir: &Mir,
+        mir: &Mir<'_>,
         nop_landing_pads: &BitSet<BasicBlock>,
     ) -> bool {
         for stmt in &mir[bb].statements {
@@ -86,7 +86,7 @@
         }
     }
 
-    fn remove_nop_landing_pads(&self, mir: &mut Mir) {
+    fn remove_nop_landing_pads(&self, mir: &mut Mir<'_>) {
         // make sure there's a single resume block
         let resume_block = {
             let patch = MirPatch::new(mir);
diff --git a/src/librustc_mir/transform/rustc_peek.rs b/src/librustc_mir/transform/rustc_peek.rs
index 36a6279..40e02e7 100644
--- a/src/librustc_mir/transform/rustc_peek.rs
+++ b/src/librustc_mir/transform/rustc_peek.rs
@@ -5,25 +5,27 @@
 use rustc::ty::{self, TyCtxt};
 use rustc::mir::{self, Mir, Location};
 use rustc_data_structures::bit_set::BitSet;
-use transform::{MirPass, MirSource};
+use crate::transform::{MirPass, MirSource};
 
-use dataflow::{do_dataflow, DebugFormatted};
-use dataflow::MoveDataParamEnv;
-use dataflow::BitDenotation;
-use dataflow::DataflowResults;
-use dataflow::{DefinitelyInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces};
-use dataflow::move_paths::{MovePathIndex, LookupResult};
-use dataflow::move_paths::{HasMoveData, MoveData};
-use dataflow;
+use crate::dataflow::{do_dataflow, DebugFormatted};
+use crate::dataflow::MoveDataParamEnv;
+use crate::dataflow::BitDenotation;
+use crate::dataflow::DataflowResults;
+use crate::dataflow::{
+    DefinitelyInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces
+};
+use crate::dataflow::move_paths::{MovePathIndex, LookupResult};
+use crate::dataflow::move_paths::{HasMoveData, MoveData};
+use crate::dataflow;
 
-use dataflow::has_rustc_mir_with;
+use crate::dataflow::has_rustc_mir_with;
 
 pub struct SanityCheck;
 
 impl MirPass for SanityCheck {
     fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          src: MirSource, mir: &mut Mir<'tcx>) {
-        let def_id = src.def_id;
+                          src: MirSource<'tcx>, mir: &mut Mir<'tcx>) {
+        let def_id = src.def_id();
         let id = tcx.hir().as_local_node_id(def_id).unwrap();
         if !tcx.has_attr(def_id, "rustc_mir") {
             debug!("skipping rustc_peek::SanityCheck on {}", tcx.item_path_str(def_id));
diff --git a/src/librustc_mir/transform/simplify.rs b/src/librustc_mir/transform/simplify.rs
index ed2da98..14e7895 100644
--- a/src/librustc_mir/transform/simplify.rs
+++ b/src/librustc_mir/transform/simplify.rs
@@ -34,7 +34,7 @@
 use rustc::mir::visit::{MutVisitor, Visitor, PlaceContext};
 use rustc::session::config::DebugInfo;
 use std::borrow::Cow;
-use transform::{MirPass, MirSource};
+use crate::transform::{MirPass, MirSource};
 
 pub struct SimplifyCfg { label: String }
 
@@ -44,7 +44,7 @@
     }
 }
 
-pub fn simplify_cfg(mir: &mut Mir) {
+pub fn simplify_cfg(mir: &mut Mir<'_>) {
     CfgSimplifier::new(mir).simplify();
     remove_dead_blocks(mir);
 
@@ -59,7 +59,7 @@
 
     fn run_pass<'a, 'tcx>(&self,
                           _tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          _src: MirSource,
+                          _src: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>) {
         debug!("SimplifyCfg({:?}) - simplifying {:?}", self.label, mir);
         simplify_cfg(mir);
@@ -263,7 +263,7 @@
     }
 }
 
-pub fn remove_dead_blocks(mir: &mut Mir) {
+pub fn remove_dead_blocks(mir: &mut Mir<'_>) {
     let mut seen = BitSet::new_empty(mir.basic_blocks().len());
     for (bb, _) in traversal::preorder(mir) {
         seen.insert(bb.index());
@@ -298,7 +298,7 @@
 impl MirPass for SimplifyLocals {
     fn run_pass<'a, 'tcx>(&self,
                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          _: MirSource,
+                          _: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>) {
         let mut marker = DeclMarker { locals: BitSet::new_empty(mir.local_decls.len()) };
         marker.visit_mir(mir);
diff --git a/src/librustc_mir/transform/simplify_branches.rs b/src/librustc_mir/transform/simplify_branches.rs
index abaea70..3c4d122 100644
--- a/src/librustc_mir/transform/simplify_branches.rs
+++ b/src/librustc_mir/transform/simplify_branches.rs
@@ -2,7 +2,7 @@
 
 use rustc::ty::{TyCtxt, ParamEnv};
 use rustc::mir::*;
-use transform::{MirPass, MirSource};
+use crate::transform::{MirPass, MirSource};
 
 use std::borrow::Cow;
 
@@ -21,7 +21,7 @@
 
     fn run_pass<'a, 'tcx>(&self,
                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          _src: MirSource,
+                          _src: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>) {
         for block in mir.basic_blocks_mut() {
             let terminator = block.terminator_mut();
diff --git a/src/librustc_mir/transform/uniform_array_move_out.rs b/src/librustc_mir/transform/uniform_array_move_out.rs
index 5ab9669..fd8d68a 100644
--- a/src/librustc_mir/transform/uniform_array_move_out.rs
+++ b/src/librustc_mir/transform/uniform_array_move_out.rs
@@ -30,16 +30,16 @@
 use rustc::ty::TyCtxt;
 use rustc::mir::*;
 use rustc::mir::visit::{Visitor, PlaceContext, NonUseContext};
-use transform::{MirPass, MirSource};
-use util::patch::MirPatch;
 use rustc_data_structures::indexed_vec::{IndexVec};
+use crate::transform::{MirPass, MirSource};
+use crate::util::patch::MirPatch;
 
 pub struct UniformArrayMoveOut;
 
 impl MirPass for UniformArrayMoveOut {
     fn run_pass<'a, 'tcx>(&self,
                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          _src: MirSource,
+                          _src: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>) {
         let mut patch = MirPatch::new(mir);
         {
@@ -161,7 +161,7 @@
 impl MirPass for RestoreSubsliceArrayMoveOut {
     fn run_pass<'a, 'tcx>(&self,
                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
-                          _src: MirSource,
+                          _src: MirSource<'tcx>,
                           mir: &mut Mir<'tcx>) {
         let mut patch = MirPatch::new(mir);
         {
diff --git a/src/librustc_mir/util/borrowck_errors.rs b/src/librustc_mir/util/borrowck_errors.rs
index 7ad73aa..fd694dd 100644
--- a/src/librustc_mir/util/borrowck_errors.rs
+++ b/src/librustc_mir/util/borrowck_errors.rs
@@ -12,7 +12,7 @@
 }
 
 impl fmt::Display for Origin {
-    fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, w: &mut fmt::Formatter<'_>) -> fmt::Result {
         // If the user passed `-Z borrowck=compare`, then include
         // origin info as part of the error report,
         // otherwise
@@ -437,7 +437,7 @@
     fn cannot_move_out_of_interior_noncopy(
         self,
         move_from_span: Span,
-        ty: ty::Ty,
+        ty: ty::Ty<'_>,
         is_index: Option<bool>,
         o: Origin,
     ) -> DiagnosticBuilder<'cx> {
@@ -464,7 +464,7 @@
     fn cannot_move_out_of_interior_of_drop(
         self,
         move_from_span: Span,
-        container_ty: ty::Ty,
+        container_ty: ty::Ty<'_>,
         o: Origin,
     ) -> DiagnosticBuilder<'cx> {
         let mut err = struct_span_err!(
diff --git a/src/librustc_mir/util/def_use.rs b/src/librustc_mir/util/def_use.rs
index 057a7c8..3b9d7c3 100644
--- a/src/librustc_mir/util/def_use.rs
+++ b/src/librustc_mir/util/def_use.rs
@@ -107,7 +107,7 @@
 
     pub fn defs_not_including_drop(
         &self,
-    ) -> iter::Filter<slice::Iter<Use<'tcx>>, fn(&&Use<'tcx>) -> bool> {
+    ) -> iter::Filter<slice::Iter<'_, Use<'tcx>>, fn(&&Use<'tcx>) -> bool> {
         self.defs_and_uses.iter().filter(|place_use| {
             place_use.context.is_mutating_use() && !place_use.context.is_drop()
         })
diff --git a/src/librustc_mir/util/elaborate_drops.rs b/src/librustc_mir/util/elaborate_drops.rs
index 8b55a44..1bc956e 100644
--- a/src/librustc_mir/util/elaborate_drops.rs
+++ b/src/librustc_mir/util/elaborate_drops.rs
@@ -8,7 +8,7 @@
 use rustc::ty::subst::Substs;
 use rustc::ty::util::IntTypeExt;
 use rustc_data_structures::indexed_vec::Idx;
-use util::patch::MirPatch;
+use crate::util::patch::MirPatch;
 
 use std::u32;
 
@@ -963,7 +963,7 @@
             span: self.source_info.span,
             ty: self.tcx().types.usize,
             user_ty: None,
-            literal: self.tcx().intern_lazy_const(ty::LazyConst::Evaluated(
+            literal: self.tcx().mk_lazy_const(ty::LazyConst::Evaluated(
                 ty::Const::from_usize(self.tcx(), val.into())
             )),
         })
diff --git a/src/librustc_mir/util/graphviz.rs b/src/librustc_mir/util/graphviz.rs
index b68898f..e93b96c 100644
--- a/src/librustc_mir/util/graphviz.rs
+++ b/src/librustc_mir/util/graphviz.rs
@@ -1,4 +1,3 @@
-use dot;
 use rustc::hir::def_id::DefId;
 use rustc::mir::*;
 use rustc::ty::TyCtxt;
@@ -24,7 +23,7 @@
 /// Write a graphviz DOT graph of the MIR.
 pub fn write_mir_fn_graphviz<'tcx, W>(tcx: TyCtxt<'_, '_, 'tcx>,
                                       def_id: DefId,
-                                      mir: &Mir,
+                                      mir: &Mir<'_>,
                                       w: &mut W) -> io::Result<()>
     where W: Write
 {
@@ -58,7 +57,7 @@
 /// `init` and `fini` are callbacks for emitting additional rows of
 /// data (using HTML enclosed with `<tr>` in the emitted text).
 pub fn write_node_label<W: Write, INIT, FINI>(block: BasicBlock,
-                                              mir: &Mir,
+                                              mir: &Mir<'_>,
                                               w: &mut W,
                                               num_cols: u32,
                                               init: INIT,
@@ -100,7 +99,7 @@
 }
 
 /// Write a graphviz DOT node for the given basic block.
-fn write_node<W: Write>(block: BasicBlock, mir: &Mir, w: &mut W) -> io::Result<()> {
+fn write_node<W: Write>(block: BasicBlock, mir: &Mir<'_>, w: &mut W) -> io::Result<()> {
     // Start a new node with the label to follow, in one of DOT's pseudo-HTML tables.
     write!(w, r#"    {} [shape="none", label=<"#, node(block))?;
     write_node_label(block, mir, w, 1, |_| Ok(()), |_| Ok(()))?;
@@ -109,7 +108,7 @@
 }
 
 /// Write graphviz DOT edges with labels between the given basic block and all of its successors.
-fn write_edges<W: Write>(source: BasicBlock, mir: &Mir, w: &mut W) -> io::Result<()> {
+fn write_edges<W: Write>(source: BasicBlock, mir: &Mir<'_>, w: &mut W) -> io::Result<()> {
     let terminator = mir[source].terminator();
     let labels = terminator.kind.fmt_successor_labels();
 
@@ -125,7 +124,7 @@
 /// all the variables and temporaries.
 fn write_graph_label<'a, 'gcx, 'tcx, W: Write>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
                                                def_id: DefId,
-                                               mir: &Mir,
+                                               mir: &Mir<'_>,
                                                w: &mut W)
                                                -> io::Result<()> {
     write!(w, "    label=<fn {}(", dot::escape_html(&tcx.item_path_str(def_id)))?;
diff --git a/src/librustc_mir/util/liveness.rs b/src/librustc_mir/util/liveness.rs
index b68c6f8..847699c 100644
--- a/src/librustc_mir/util/liveness.rs
+++ b/src/librustc_mir/util/liveness.rs
@@ -35,8 +35,8 @@
 use std::fs;
 use std::io::{self, Write};
 use std::path::{Path, PathBuf};
-use transform::MirSource;
-use util::pretty::{dump_enabled, write_basic_block, write_mir_intro};
+use crate::transform::MirSource;
+use crate::util::pretty::{dump_enabled, write_basic_block, write_mir_intro};
 
 pub type LiveVarSet<V> = BitSet<V>;
 
@@ -307,7 +307,7 @@
 pub fn dump_mir<'a, 'tcx, V: Idx>(
     tcx: TyCtxt<'a, 'tcx, 'tcx>,
     pass_name: &str,
-    source: MirSource,
+    source: MirSource<'tcx>,
     mir: &Mir<'tcx>,
     map: &impl LiveVariableMap<LiveVar = V>,
     result: &LivenessResult<V>,
@@ -317,7 +317,7 @@
     }
     let node_path = item_path::with_forced_impl_filename_line(|| {
         // see notes on #41697 below
-        tcx.item_path_str(source.def_id)
+        tcx.item_path_str(source.def_id())
     });
     dump_matched_mir_node(tcx, pass_name, &node_path, source, mir, map, result);
 }
@@ -326,14 +326,14 @@
     tcx: TyCtxt<'a, 'tcx, 'tcx>,
     pass_name: &str,
     node_path: &str,
-    source: MirSource,
+    source: MirSource<'tcx>,
     mir: &Mir<'tcx>,
     map: &dyn LiveVariableMap<LiveVar = V>,
     result: &LivenessResult<V>,
 ) {
     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_node_id(source.def_id).unwrap();
+    let item_id = tcx.hir().as_local_node_id(source.def_id()).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(|mut file| {
@@ -348,7 +348,7 @@
 
 pub fn write_mir_fn<'a, 'tcx, V: Idx>(
     tcx: TyCtxt<'a, 'tcx, 'tcx>,
-    src: MirSource,
+    src: MirSource<'tcx>,
     mir: &Mir<'tcx>,
     map: &dyn LiveVariableMap<LiveVar = V>,
     w: &mut dyn Write,
diff --git a/src/librustc_mir/util/patch.rs b/src/librustc_mir/util/patch.rs
index 5a1f946..366cd71 100644
--- a/src/librustc_mir/util/patch.rs
+++ b/src/librustc_mir/util/patch.rs
@@ -170,14 +170,14 @@
         }
     }
 
-    pub fn source_info_for_index(data: &BasicBlockData, loc: Location) -> SourceInfo {
+    pub fn source_info_for_index(data: &BasicBlockData<'_>, loc: Location) -> SourceInfo {
         match data.statements.get(loc.statement_index) {
             Some(stmt) => stmt.source_info,
             None => data.terminator().source_info
         }
     }
 
-    pub fn source_info_for_location(&self, mir: &Mir, loc: Location) -> SourceInfo {
+    pub fn source_info_for_location(&self, mir: &Mir<'_>, loc: Location) -> SourceInfo {
         let data = match loc.block.index().checked_sub(mir.basic_blocks().len()) {
             Some(new) => &self.new_blocks[new],
             None => &mir[loc.block]
diff --git a/src/librustc_mir/util/pretty.rs b/src/librustc_mir/util/pretty.rs
index 3a15356..1357f8f 100644
--- a/src/librustc_mir/util/pretty.rs
+++ b/src/librustc_mir/util/pretty.rs
@@ -1,4 +1,3 @@
-use rustc::hir;
 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
 use rustc::mir::*;
 use rustc::mir::visit::Visitor;
@@ -12,7 +11,7 @@
 use std::io::{self, Write};
 use std::path::{Path, PathBuf};
 use super::graphviz::write_mir_fn_graphviz;
-use transform::MirSource;
+use crate::transform::MirSource;
 
 const INDENT: &str = "    ";
 /// Alignment for lining up comments following MIR statements
@@ -69,7 +68,7 @@
     pass_num: Option<&dyn Display>,
     pass_name: &str,
     disambiguator: &dyn Display,
-    source: MirSource,
+    source: MirSource<'tcx>,
     mir: &Mir<'tcx>,
     extra_data: F,
 ) where
@@ -81,7 +80,7 @@
 
     let node_path = item_path::with_forced_impl_filename_line(|| {
         // see notes on #41697 below
-        tcx.item_path_str(source.def_id)
+        tcx.item_path_str(source.def_id())
     });
     dump_matched_mir_node(
         tcx,
@@ -98,7 +97,7 @@
 pub fn dump_enabled<'a, 'gcx, 'tcx>(
     tcx: TyCtxt<'a, 'gcx, 'tcx>,
     pass_name: &str,
-    source: MirSource,
+    source: MirSource<'tcx>,
 ) -> bool {
     let filters = match tcx.sess.opts.debugging_opts.dump_mir {
         None => return false,
@@ -106,7 +105,7 @@
     };
     let node_path = item_path::with_forced_impl_filename_line(|| {
         // see notes on #41697 below
-        tcx.item_path_str(source.def_id)
+        tcx.item_path_str(source.def_id())
     });
     filters.split('|').any(|or_filter| {
         or_filter.split('&').all(|and_filter| {
@@ -125,13 +124,13 @@
     pass_name: &str,
     node_path: &str,
     disambiguator: &dyn Display,
-    source: MirSource,
+    source: MirSource<'tcx>,
     mir: &Mir<'tcx>,
     mut extra_data: F,
 ) where
     F: FnMut(PassWhere, &mut dyn Write) -> io::Result<()>,
 {
-    let _: io::Result<()> = try_block! {
+    let _: io::Result<()> = try {
         let mut file = create_dump_file(tcx, "mir", pass_num, pass_name, disambiguator, source)?;
         writeln!(file, "// MIR for `{}`", node_path)?;
         writeln!(file, "// source = {:?}", source)?;
@@ -148,10 +147,10 @@
     };
 
     if tcx.sess.opts.debugging_opts.dump_mir_graphviz {
-        let _: io::Result<()> = try_block! {
+        let _: io::Result<()> = try {
             let mut file =
                 create_dump_file(tcx, "dot", pass_num, pass_name, disambiguator, source)?;
-            write_mir_fn_graphviz(tcx, source.def_id, mir, &mut file)?;
+            write_mir_fn_graphviz(tcx, source.def_id(), mir, &mut file)?;
         };
     }
 }
@@ -165,7 +164,7 @@
     pass_num: Option<&dyn Display>,
     pass_name: &str,
     disambiguator: &dyn Display,
-    source: MirSource,
+    source: MirSource<'tcx>,
 ) -> PathBuf {
     let promotion_id = match source.promoted {
         Some(id) => format!("-{:?}", id),
@@ -184,13 +183,32 @@
     let mut file_path = PathBuf::new();
     file_path.push(Path::new(&tcx.sess.opts.debugging_opts.dump_mir_dir));
 
-    let item_name = tcx.hir()
-        .def_path(source.def_id)
+    let item_name = tcx
+        .def_path(source.def_id())
         .to_filename_friendly_no_crate();
+    // All drop shims have the same DefId, so we have to add the type
+    // to get unique file names.
+    let shim_disambiguator = match source.instance {
+        ty::InstanceDef::DropGlue(_, Some(ty)) => {
+            // Unfortunately, pretty-printed typed are not very filename-friendly.
+            // We dome some filtering.
+            let mut s = ".".to_owned();
+            s.extend(ty.to_string()
+                .chars()
+                .filter_map(|c| match c {
+                    ' ' => None,
+                    ':' => Some('_'),
+                    c => Some(c)
+                }));
+            s
+        }
+        _ => String::new(),
+    };
 
     let file_name = format!(
-        "rustc.{}{}{}.{}.{}.{}",
+        "rustc.{}{}{}{}.{}.{}.{}",
         item_name,
+        shim_disambiguator,
         promotion_id,
         pass_num,
         pass_name,
@@ -213,7 +231,7 @@
     pass_num: Option<&dyn Display>,
     pass_name: &str,
     disambiguator: &dyn Display,
-    source: MirSource,
+    source: MirSource<'tcx>,
 ) -> io::Result<fs::File> {
     let file_path = dump_path(tcx, extension, pass_num, pass_name, disambiguator, source);
     if let Some(parent) = file_path.parent() {
@@ -253,7 +271,7 @@
         for (i, mir) in mir.promoted.iter_enumerated() {
             writeln!(w, "")?;
             let src = MirSource {
-                def_id,
+                instance: ty::InstanceDef::Item(def_id),
                 promoted: Some(i),
             };
             write_mir_fn(tcx, src, mir, &mut |_, _| Ok(()), w)?;
@@ -264,7 +282,7 @@
 
 pub fn write_mir_fn<'a, 'gcx, 'tcx, F>(
     tcx: TyCtxt<'a, 'gcx, 'tcx>,
-    src: MirSource,
+    src: MirSource<'tcx>,
     mir: &Mir<'tcx>,
     extra_data: &mut F,
     w: &mut dyn Write,
@@ -446,7 +464,7 @@
     }
 }
 
-fn comment(tcx: TyCtxt, SourceInfo { span, scope }: SourceInfo) -> String {
+fn comment(tcx: TyCtxt<'_, '_, '_>, SourceInfo { span, scope }: SourceInfo) -> String {
     format!(
         "scope {} at {}",
         scope.index(),
@@ -458,8 +476,8 @@
 ///
 /// Returns the total number of variables printed.
 fn write_scope_tree(
-    tcx: TyCtxt,
-    mir: &Mir,
+    tcx: TyCtxt<'_, '_, '_>,
+    mir: &Mir<'_>,
     scope_tree: &FxHashMap<SourceScope, Vec<SourceScope>>,
     w: &mut dyn Write,
     parent: SourceScope,
@@ -528,8 +546,8 @@
 /// local variables (both user-defined bindings and compiler temporaries).
 pub fn write_mir_intro<'a, 'gcx, 'tcx>(
     tcx: TyCtxt<'a, 'gcx, 'tcx>,
-    src: MirSource,
-    mir: &Mir,
+    src: MirSource<'tcx>,
+    mir: &Mir<'_>,
     w: &mut dyn Write,
 ) -> io::Result<()> {
     write_mir_sig(tcx, src, mir, w)?;
@@ -568,42 +586,51 @@
     Ok(())
 }
 
-fn write_mir_sig(tcx: TyCtxt, src: MirSource, mir: &Mir, w: &mut dyn Write) -> io::Result<()> {
-    let id = tcx.hir().as_local_node_id(src.def_id).unwrap();
-    let body_owner_kind = tcx.hir().body_owner_kind(id);
-    match (body_owner_kind, src.promoted) {
-        (_, Some(i)) => write!(w, "{:?} in", i)?,
-        (hir::BodyOwnerKind::Closure, _) |
-        (hir::BodyOwnerKind::Fn, _) => write!(w, "fn")?,
-        (hir::BodyOwnerKind::Const, _) => write!(w, "const")?,
-        (hir::BodyOwnerKind::Static(hir::MutImmutable), _) => write!(w, "static")?,
-        (hir::BodyOwnerKind::Static(hir::MutMutable), _) => write!(w, "static mut")?,
+fn write_mir_sig(
+    tcx: TyCtxt<'_, '_, '_>,
+    src: MirSource<'tcx>,
+    mir: &Mir<'_>,
+    w: &mut dyn Write,
+) -> io::Result<()> {
+    use rustc::hir::def::Def;
+
+    trace!("write_mir_sig: {:?}", src.instance);
+    let descr = tcx.describe_def(src.def_id());
+    let is_function = match descr {
+        Some(Def::Fn(_)) | Some(Def::Method(_)) | Some(Def::StructCtor(..)) => true,
+        _ => tcx.is_closure(src.def_id()),
+    };
+    match (descr, src.promoted) {
+        (_, Some(i)) => write!(w, "{:?} in ", i)?,
+        (Some(Def::StructCtor(..)), _) => write!(w, "struct ")?,
+        (Some(Def::Const(_)), _) => write!(w, "const ")?,
+        (Some(Def::Static(_, /*is_mutbl*/false)), _) => write!(w, "static ")?,
+        (Some(Def::Static(_, /*is_mutbl*/true)), _) => write!(w, "static mut ")?,
+        (_, _) if is_function => write!(w, "fn ")?,
+        (None, _) => {}, // things like anon const, not an item
+        _ => bug!("Unexpected def description {:?}", descr),
     }
 
     item_path::with_forced_impl_filename_line(|| {
         // see notes on #41697 elsewhere
-        write!(w, " {}", tcx.item_path_str(src.def_id))
+        write!(w, "{}", tcx.item_path_str(src.def_id()))
     })?;
 
-    match (body_owner_kind, src.promoted) {
-        (hir::BodyOwnerKind::Closure, None) |
-        (hir::BodyOwnerKind::Fn, None) => {
-            write!(w, "(")?;
+    if src.promoted.is_none() && is_function {
+        write!(w, "(")?;
 
-            // fn argument types.
-            for (i, arg) in mir.args_iter().enumerate() {
-                if i != 0 {
-                    write!(w, ", ")?;
-                }
-                write!(w, "{:?}: {}", Place::Local(arg), mir.local_decls[arg].ty)?;
+        // fn argument types.
+        for (i, arg) in mir.args_iter().enumerate() {
+            if i != 0 {
+                write!(w, ", ")?;
             }
+            write!(w, "{:?}: {}", Place::Local(arg), mir.local_decls[arg].ty)?;
+        }
 
-            write!(w, ") -> {}", mir.return_ty())?;
-        }
-        (hir::BodyOwnerKind::Const, _) | (hir::BodyOwnerKind::Static(_), _) | (_, Some(_)) => {
-            assert_eq!(mir.arg_count, 0);
-            write!(w, ": {} =", mir.return_ty())?;
-        }
+        write!(w, ") -> {}", mir.return_ty())?;
+    } else {
+        assert_eq!(mir.arg_count, 0);
+        write!(w, ": {} =", mir.return_ty())?;
     }
 
     if let Some(yield_ty) = mir.yield_ty {
@@ -611,10 +638,13 @@
         writeln!(w, "yields {}", yield_ty)?;
     }
 
+    write!(w, " ")?;
+    // Next thing that gets printed is the opening {
+
     Ok(())
 }
 
-fn write_temp_decls(mir: &Mir, w: &mut dyn Write) -> io::Result<()> {
+fn write_temp_decls(mir: &Mir<'_>, w: &mut dyn Write) -> io::Result<()> {
     // Compiler-introduced temporary types.
     for temp in mir.temps_iter() {
         writeln!(
@@ -630,7 +660,7 @@
     Ok(())
 }
 
-fn write_user_type_annotations(mir: &Mir, w: &mut dyn Write) -> io::Result<()> {
+fn write_user_type_annotations(mir: &Mir<'_>, w: &mut dyn Write) -> io::Result<()> {
     if !mir.user_type_annotations.is_empty() {
         writeln!(w, "| User Type Annotations")?;
     }
@@ -643,7 +673,7 @@
     Ok(())
 }
 
-pub fn dump_mir_def_ids(tcx: TyCtxt, single: Option<DefId>) -> Vec<DefId> {
+pub fn dump_mir_def_ids(tcx: TyCtxt<'_, '_, '_>, single: Option<DefId>) -> Vec<DefId> {
     if let Some(i) = single {
         vec![i]
     } else {
diff --git a/src/librustc_passes/Cargo.toml b/src/librustc_passes/Cargo.toml
index f5154a0..00bdcdc 100644
--- a/src/librustc_passes/Cargo.toml
+++ b/src/librustc_passes/Cargo.toml
@@ -2,6 +2,7 @@
 authors = ["The Rust Project Developers"]
 name = "rustc_passes"
 version = "0.0.0"
+edition = "2018"
 
 [lib]
 name = "rustc_passes"
@@ -16,4 +17,4 @@
 syntax = { path = "../libsyntax" }
 syntax_ext = { path = "../libsyntax_ext" }
 syntax_pos = { path = "../libsyntax_pos" }
-rustc_errors = { path = "../librustc_errors" }
+errors = { path = "../librustc_errors", package = "rustc_errors" }
diff --git a/src/librustc_passes/ast_validation.rs b/src/librustc_passes/ast_validation.rs
index 3deb2ff..a391a31 100644
--- a/src/librustc_passes/ast_validation.rs
+++ b/src/librustc_passes/ast_validation.rs
@@ -7,18 +7,21 @@
 // or type checking or some other kind of complex analysis.
 
 use std::mem;
+use syntax::print::pprust;
 use rustc::lint;
 use rustc::session::Session;
+use rustc_data_structures::fx::FxHashMap;
 use syntax::ast::*;
 use syntax::attr;
 use syntax::source_map::Spanned;
 use syntax::symbol::keywords;
 use syntax::ptr::P;
 use syntax::visit::{self, Visitor};
+use syntax::{span_err, struct_span_err, walk_list};
 use syntax_ext::proc_macro_decls::is_proc_macro_attr;
 use syntax_pos::Span;
-use errors;
 use errors::Applicability;
+use log::debug;
 
 struct AstValidator<'a> {
     session: &'a Session,
@@ -271,7 +274,74 @@
             _ => None,
         }
     }
+}
 
+enum GenericPosition {
+    Param,
+    Arg,
+}
+
+fn validate_generics_order<'a>(
+    handler: &errors::Handler,
+    generics: impl Iterator<Item = (ParamKindOrd, Span, Option<String>)>,
+    pos: GenericPosition,
+    span: Span,
+) {
+    let mut max_param: Option<ParamKindOrd> = None;
+    let mut out_of_order = FxHashMap::default();
+    let mut param_idents = vec![];
+
+    for (kind, span, ident) in generics {
+        if let Some(ident) = ident {
+            param_idents.push((kind, param_idents.len(), ident));
+        }
+        let max_param = &mut max_param;
+        match max_param {
+            Some(max_param) if *max_param > kind => {
+                let entry = out_of_order.entry(kind).or_insert((*max_param, vec![]));
+                entry.1.push(span);
+            }
+            Some(_) | None => *max_param = Some(kind),
+        };
+    }
+
+    let mut ordered_params = "<".to_string();
+    if !out_of_order.is_empty() {
+        param_idents.sort_by_key(|&(po, i, _)| (po, i));
+        let mut first = true;
+        for (_, _, ident) in param_idents {
+            if !first {
+                ordered_params += ", ";
+            }
+            ordered_params += &ident;
+            first = false;
+        }
+    }
+    ordered_params += ">";
+
+    let pos_str = match pos {
+        GenericPosition::Param => "parameter",
+        GenericPosition::Arg => "argument",
+    };
+
+    for (param_ord, (max_param, spans)) in out_of_order {
+        let mut err = handler.struct_span_err(spans,
+            &format!(
+                "{} {pos}s must be declared prior to {} {pos}s",
+                param_ord,
+                max_param,
+                pos = pos_str,
+            ));
+        if let GenericPosition::Param = pos {
+            err.span_suggestion(
+                span,
+                &format!("reorder the {}s: lifetimes, then types, then consts", pos_str),
+                ordered_params.clone(),
+                Applicability::MachineApplicable,
+            );
+        }
+        err.emit();
+    }
 }
 
 impl<'a> Visitor<'a> for AstValidator<'a> {
@@ -412,6 +482,26 @@
                         .note("only trait implementations may be annotated with default").emit();
                 }
             }
+            ItemKind::Fn(_, header, ref generics, _) => {
+                // We currently do not permit const generics in `const fn`, as
+                // this is tantamount to allowing compile-time dependent typing.
+                if header.constness.node == Constness::Const {
+                    // Look for const generics and error if we find any.
+                    for param in &generics.params {
+                        match param.kind {
+                            GenericParamKind::Const { .. } => {
+                                self.err_handler()
+                                    .struct_span_err(
+                                        item.span,
+                                        "const parameters are not permitted in `const fn`",
+                                    )
+                                    .emit();
+                            }
+                            _ => {}
+                        }
+                    }
+                }
+            }
             ItemKind::ForeignMod(..) => {
                 self.invalid_visibility(
                     &item.vis,
@@ -508,6 +598,13 @@
         match *generic_args {
             GenericArgs::AngleBracketed(ref data) => {
                 walk_list!(self, visit_generic_arg, &data.args);
+                validate_generics_order(self.err_handler(), data.args.iter().map(|arg| {
+                    (match arg {
+                        GenericArg::Lifetime(..) => ParamKindOrd::Lifetime,
+                        GenericArg::Type(..) => ParamKindOrd::Type,
+                        GenericArg::Const(..) => ParamKindOrd::Const,
+                    }, arg.span(), None)
+                }), GenericPosition::Arg, generic_args.span());
                 // Type bindings such as `Item=impl Debug` in `Iterator<Item=Debug>`
                 // are allowed to contain nested `impl Trait`.
                 self.with_impl_trait(None, |this| {
@@ -526,27 +623,32 @@
     }
 
     fn visit_generics(&mut self, generics: &'a Generics) {
-        let mut seen_non_lifetime_param = false;
-        let mut seen_default = None;
+        let mut prev_ty_default = None;
         for param in &generics.params {
-            match (&param.kind, seen_non_lifetime_param) {
-                (GenericParamKind::Lifetime { .. }, true) => {
+            if let GenericParamKind::Type { ref default, .. } = param.kind {
+                if default.is_some() {
+                    prev_ty_default = Some(param.ident.span);
+                } else if let Some(span) = prev_ty_default {
                     self.err_handler()
-                        .span_err(param.ident.span, "lifetime parameters must be leading");
-                },
-                (GenericParamKind::Lifetime { .. }, false) => {}
-                (GenericParamKind::Type { ref default, .. }, _) => {
-                    seen_non_lifetime_param = true;
-                    if default.is_some() {
-                        seen_default = Some(param.ident.span);
-                    } else if let Some(span) = seen_default {
-                        self.err_handler()
-                            .span_err(span, "type parameters with a default must be trailing");
-                        break;
-                    }
+                        .span_err(span, "type parameters with a default must be trailing");
+                    break;
                 }
             }
         }
+
+        validate_generics_order(self.err_handler(), generics.params.iter().map(|param| {
+            let span = param.ident.span;
+            let ident = Some(param.ident.to_string());
+            match &param.kind {
+                GenericParamKind::Lifetime { .. } => (ParamKindOrd::Lifetime, span, ident),
+                GenericParamKind::Type { .. } => (ParamKindOrd::Type, span, ident),
+                GenericParamKind::Const { ref ty } => {
+                    let ty = pprust::ty_to_string(ty);
+                    (ParamKindOrd::Const, span, Some(format!("const {}: {}", param.ident, ty)))
+                }
+            }
+        }), GenericPosition::Param, generics.span);
+
         for predicate in &generics.where_clause.predicates {
             if let WherePredicate::EqPredicate(ref predicate) = *predicate {
                 self.err_handler()
@@ -554,6 +656,7 @@
                                                supported in where clauses (see #20041)");
             }
         }
+
         visit::walk_generics(self, generics)
     }
 
diff --git a/src/librustc_passes/diagnostics.rs b/src/librustc_passes/diagnostics.rs
index 037227a..19d4d3a 100644
--- a/src/librustc_passes/diagnostics.rs
+++ b/src/librustc_passes/diagnostics.rs
@@ -1,5 +1,7 @@
 #![allow(non_snake_case)]
 
+use syntax::{register_diagnostic, register_diagnostics, register_long_diagnostics};
+
 register_long_diagnostics! {
 /*
 E0014: r##"
diff --git a/src/librustc_passes/hir_stats.rs b/src/librustc_passes/hir_stats.rs
index 74d6d75..2427aba 100644
--- a/src/librustc_passes/hir_stats.rs
+++ b/src/librustc_passes/hir_stats.rs
@@ -61,7 +61,7 @@
         });
 
         entry.count += 1;
-        entry.size = ::std::mem::size_of_val(node);
+        entry.size = std::mem::size_of_val(node);
     }
 
     fn print(&self, title: &str) {
diff --git a/src/librustc_passes/lib.rs b/src/librustc_passes/lib.rs
index 76605c5..ff2e345 100644
--- a/src/librustc_passes/lib.rs
+++ b/src/librustc_passes/lib.rs
@@ -4,27 +4,17 @@
 //!
 //! This API is completely unstable and subject to change.
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 
 #![feature(nll)]
 #![feature(rustc_diagnostic_macros)]
 
 #![recursion_limit="256"]
 
-#[macro_use]
-extern crate rustc;
-extern crate rustc_mir;
-extern crate rustc_data_structures;
+#![deny(rust_2018_idioms)]
 
 #[macro_use]
-extern crate log;
-#[macro_use]
-extern crate syntax;
-extern crate syntax_ext;
-extern crate syntax_pos;
-extern crate rustc_errors as errors;
+extern crate rustc;
 
 use rustc::ty::query::Providers;
 
@@ -38,7 +28,7 @@
 
 __build_diagnostic_array! { librustc_passes, DIAGNOSTICS }
 
-pub fn provide(providers: &mut Providers) {
+pub fn provide(providers: &mut Providers<'_>) {
     rvalue_promotion::provide(providers);
     loops::provide(providers);
 }
diff --git a/src/librustc_passes/loops.rs b/src/librustc_passes/loops.rs
index f05a7be..533e043 100644
--- a/src/librustc_passes/loops.rs
+++ b/src/librustc_passes/loops.rs
@@ -1,4 +1,4 @@
-use self::Context::*;
+use Context::*;
 
 use rustc::session::Session;
 
@@ -9,6 +9,7 @@
 use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
 use rustc::hir::{self, Node, Destination};
 use syntax::ast;
+use syntax::struct_span_err;
 use syntax_pos::Span;
 use errors::Applicability;
 
@@ -59,7 +60,7 @@
     }.as_deep_visitor());
 }
 
-pub(crate) fn provide(providers: &mut Providers) {
+pub(crate) fn provide(providers: &mut Providers<'_>) {
     *providers = Providers {
         check_mod_loops,
         ..*providers
diff --git a/src/librustc_passes/rvalue_promotion.rs b/src/librustc_passes/rvalue_promotion.rs
index 739c969..8d33fef 100644
--- a/src/librustc_passes/rvalue_promotion.rs
+++ b/src/librustc_passes/rvalue_promotion.rs
@@ -28,10 +28,11 @@
 use rustc_data_structures::sync::Lrc;
 use syntax::ast;
 use syntax_pos::{Span, DUMMY_SP};
-use self::Promotability::*;
+use log::debug;
+use Promotability::*;
 use std::ops::{BitAnd, BitAndAssign, BitOr};
 
-pub fn provide(providers: &mut Providers) {
+pub fn provide(providers: &mut Providers<'_>) {
     *providers = Providers {
         rvalue_promotable_map,
         const_is_rvalue_promotable_to_static,
@@ -621,7 +622,7 @@
     fn consume(&mut self,
                _consume_id: ast::NodeId,
                _consume_span: Span,
-               _cmt: &mc::cmt_,
+               _cmt: &mc::cmt_<'_>,
                _mode: euv::ConsumeMode) {}
 
     fn borrow(&mut self,
@@ -680,11 +681,14 @@
     fn mutate(&mut self,
               _assignment_id: ast::NodeId,
               _assignment_span: Span,
-              _assignee_cmt: &mc::cmt_,
+              _assignee_cmt: &mc::cmt_<'_>,
               _mode: euv::MutateMode) {
     }
 
-    fn matched_pat(&mut self, _: &hir::Pat, _: &mc::cmt_, _: euv::MatchMode) {}
+    fn matched_pat(&mut self, _: &hir::Pat, _: &mc::cmt_<'_>, _: euv::MatchMode) {}
 
-    fn consume_pat(&mut self, _consume_pat: &hir::Pat, _cmt: &mc::cmt_, _mode: euv::ConsumeMode) {}
+    fn consume_pat(&mut self,
+                   _consume_pat: &hir::Pat,
+                   _cmt: &mc::cmt_<'_>,
+                   _mode: euv::ConsumeMode) {}
 }
diff --git a/src/librustc_plugin/lib.rs b/src/librustc_plugin/lib.rs
index 9a31bdd..32e003f 100644
--- a/src/librustc_plugin/lib.rs
+++ b/src/librustc_plugin/lib.rs
@@ -50,9 +50,7 @@
 //! See the [`plugin` feature](../unstable-book/language-features/plugin.html) of
 //! the Unstable Book for more examples.
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 
 #![feature(rustc_diagnostic_macros)]
 
diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs
index 000c6bb..14a0922 100644
--- a/src/librustc_privacy/lib.rs
+++ b/src/librustc_privacy/lib.rs
@@ -1,6 +1,4 @@
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 
 #![deny(rust_2018_idioms)]
 
diff --git a/src/librustc_resolve/check_unused.rs b/src/librustc_resolve/check_unused.rs
index 6399608..3b6179f 100644
--- a/src/librustc_resolve/check_unused.rs
+++ b/src/librustc_resolve/check_unused.rs
@@ -7,23 +7,52 @@
 //
 // Unused trait imports can't be checked until the method resolution. We save
 // candidates here, and do the actual check in librustc_typeck/check_unused.rs.
+//
+// Checking for unused imports is split into three steps:
+//
+//  - `UnusedImportCheckVisitor` walks the AST to find all the unused imports
+//    inside of `UseTree`s, recording their `NodeId`s and grouping them by
+//    the parent `use` item
+//
+//  - `calc_unused_spans` then walks over all the `use` items marked in the
+//    previous step to collect the spans associated with the `NodeId`s and to
+//    calculate the spans that can be removed by rustfix; This is done in a
+//    separate step to be able to collapse the adjacent spans that rustfix
+//    will remove
+//
+//  - `check_crate` finally emits the diagnostics based on the data generated
+//    in the last step
 
 use std::ops::{Deref, DerefMut};
 
 use crate::Resolver;
 use crate::resolve_imports::ImportDirectiveSubclass;
 
-use rustc::{lint, ty};
 use rustc::util::nodemap::NodeMap;
+use rustc::{lint, ty};
+use rustc_data_structures::fx::FxHashSet;
 use syntax::ast;
 use syntax::visit::{self, Visitor};
 use syntax_pos::{Span, MultiSpan, DUMMY_SP};
 
+struct UnusedImport<'a> {
+    use_tree: &'a ast::UseTree,
+    use_tree_id: ast::NodeId,
+    item_span: Span,
+    unused: FxHashSet<ast::NodeId>,
+}
+
+impl<'a> UnusedImport<'a> {
+    fn add(&mut self, id: ast::NodeId) {
+        self.unused.insert(id);
+    }
+}
 
 struct UnusedImportCheckVisitor<'a, 'b: 'a> {
     resolver: &'a mut Resolver<'b>,
     /// All the (so far) unused imports, grouped path list
-    unused_imports: NodeMap<NodeMap<Span>>,
+    unused_imports: NodeMap<UnusedImport<'a>>,
+    base_use_tree: Option<&'a ast::UseTree>,
     base_id: ast::NodeId,
     item_span: Span,
 }
@@ -46,7 +75,7 @@
 impl<'a, 'b> UnusedImportCheckVisitor<'a, 'b> {
     // We have information about whether `use` (import) directives are actually
     // used now. If an import is not used at all, we signal a lint error.
-    fn check_import(&mut self, item_id: ast::NodeId, id: ast::NodeId, span: Span) {
+    fn check_import(&mut self, id: ast::NodeId) {
         let mut used = false;
         self.per_ns(|this, ns| used |= this.used_imports.contains(&(id, ns)));
         if !used {
@@ -54,16 +83,31 @@
                 // Check later.
                 return;
             }
-            self.unused_imports.entry(item_id).or_default().insert(id, span);
+            self.unused_import(self.base_id).add(id);
         } else {
             // This trait import is definitely used, in a way other than
             // method resolution.
             self.maybe_unused_trait_imports.remove(&id);
-            if let Some(i) = self.unused_imports.get_mut(&item_id) {
-                i.remove(&id);
+            if let Some(i) = self.unused_imports.get_mut(&self.base_id) {
+                i.unused.remove(&id);
             }
         }
     }
+
+    fn unused_import(&mut self, id: ast::NodeId) -> &mut UnusedImport<'a> {
+        let use_tree_id = self.base_id;
+        let use_tree = self.base_use_tree.unwrap();
+        let item_span = self.item_span;
+
+        self.unused_imports
+            .entry(id)
+            .or_insert_with(|| UnusedImport {
+                use_tree,
+                use_tree_id,
+                item_span,
+                unused: FxHashSet::default(),
+            })
+    }
 }
 
 impl<'a, 'b> Visitor<'a> for UnusedImportCheckVisitor<'a, 'b> {
@@ -88,31 +132,112 @@
         // This allows the grouping of all the lints in the same item
         if !nested {
             self.base_id = id;
+            self.base_use_tree = Some(use_tree);
         }
 
         if let ast::UseTreeKind::Nested(ref items) = use_tree.kind {
-            // If it's the parent group, cover the entire use item
-            let span = if nested {
-                use_tree.span
-            } else {
-                self.item_span
-            };
-
             if items.is_empty() {
-                self.unused_imports
-                    .entry(self.base_id)
-                    .or_default()
-                    .insert(id, span);
+                self.unused_import(self.base_id).add(id);
             }
         } else {
-            let base_id = self.base_id;
-            self.check_import(base_id, id, use_tree.span);
+            self.check_import(id);
         }
 
         visit::walk_use_tree(self, use_tree, id);
     }
 }
 
+enum UnusedSpanResult {
+    Used,
+    FlatUnused(Span, Span),
+    NestedFullUnused(Vec<Span>, Span),
+    NestedPartialUnused(Vec<Span>, Vec<Span>),
+}
+
+fn calc_unused_spans(
+    unused_import: &UnusedImport<'_>,
+    use_tree: &ast::UseTree,
+    use_tree_id: ast::NodeId,
+) -> UnusedSpanResult {
+    // The full span is the whole item's span if this current tree is not nested inside another
+    // This tells rustfix to remove the whole item if all the imports are unused
+    let full_span = if unused_import.use_tree.span == use_tree.span {
+        unused_import.item_span
+    } else {
+        use_tree.span
+    };
+    match use_tree.kind {
+        ast::UseTreeKind::Simple(..) | ast::UseTreeKind::Glob => {
+            if unused_import.unused.contains(&use_tree_id) {
+                UnusedSpanResult::FlatUnused(use_tree.span, full_span)
+            } else {
+                UnusedSpanResult::Used
+            }
+        }
+        ast::UseTreeKind::Nested(ref nested) => {
+            if nested.len() == 0 {
+                return UnusedSpanResult::FlatUnused(use_tree.span, full_span);
+            }
+
+            let mut unused_spans = Vec::new();
+            let mut to_remove = Vec::new();
+            let mut all_nested_unused = true;
+            let mut previous_unused = false;
+            for (pos, (use_tree, use_tree_id)) in nested.iter().enumerate() {
+                let remove = match calc_unused_spans(unused_import, use_tree, *use_tree_id) {
+                    UnusedSpanResult::Used => {
+                        all_nested_unused = false;
+                        None
+                    }
+                    UnusedSpanResult::FlatUnused(span, remove) => {
+                        unused_spans.push(span);
+                        Some(remove)
+                    }
+                    UnusedSpanResult::NestedFullUnused(mut spans, remove) => {
+                        unused_spans.append(&mut spans);
+                        Some(remove)
+                    }
+                    UnusedSpanResult::NestedPartialUnused(mut spans, mut to_remove_extra) => {
+                        all_nested_unused = false;
+                        unused_spans.append(&mut spans);
+                        to_remove.append(&mut to_remove_extra);
+                        None
+                    }
+                };
+                if let Some(remove) = remove {
+                    let remove_span = if nested.len() == 1 {
+                        remove
+                    } else if pos == nested.len() - 1 || !all_nested_unused {
+                        // Delete everything from the end of the last import, to delete the
+                        // previous comma
+                        nested[pos - 1].0.span.shrink_to_hi().to(use_tree.span)
+                    } else {
+                        // Delete everything until the next import, to delete the trailing commas
+                        use_tree.span.to(nested[pos + 1].0.span.shrink_to_lo())
+                    };
+
+                    // Try to collapse adjacent spans into a single one. This prevents all cases of
+                    // overlapping removals, which are not supported by rustfix
+                    if previous_unused && !to_remove.is_empty() {
+                        let previous = to_remove.pop().unwrap();
+                        to_remove.push(previous.to(remove_span));
+                    } else {
+                        to_remove.push(remove_span);
+                    }
+                }
+                previous_unused = remove.is_some();
+            }
+            if unused_spans.is_empty() {
+                UnusedSpanResult::Used
+            } else if all_nested_unused {
+                UnusedSpanResult::NestedFullUnused(unused_spans, full_span)
+            } else {
+                UnusedSpanResult::NestedPartialUnused(unused_spans, to_remove)
+            }
+        }
+    }
+}
+
 pub fn check_crate(resolver: &mut Resolver<'_>, krate: &ast::Crate) {
     for directive in resolver.potentially_unused_imports.iter() {
         match directive.subclass {
@@ -152,14 +277,33 @@
     let mut visitor = UnusedImportCheckVisitor {
         resolver,
         unused_imports: Default::default(),
+        base_use_tree: None,
         base_id: ast::DUMMY_NODE_ID,
         item_span: DUMMY_SP,
     };
     visit::walk_crate(&mut visitor, krate);
 
-    for (id, spans) in &visitor.unused_imports {
+    for unused in visitor.unused_imports.values() {
+        let mut fixes = Vec::new();
+        let mut spans = match calc_unused_spans(unused, unused.use_tree, unused.use_tree_id) {
+            UnusedSpanResult::Used => continue,
+            UnusedSpanResult::FlatUnused(span, remove) => {
+                fixes.push((remove, String::new()));
+                vec![span]
+            }
+            UnusedSpanResult::NestedFullUnused(spans, remove) => {
+                fixes.push((remove, String::new()));
+                spans
+            }
+            UnusedSpanResult::NestedPartialUnused(spans, remove) => {
+                for fix in &remove {
+                    fixes.push((*fix, String::new()));
+                }
+                spans
+            }
+        };
+
         let len = spans.len();
-        let mut spans = spans.values().cloned().collect::<Vec<Span>>();
         spans.sort();
         let ms = MultiSpan::from_spans(spans.clone());
         let mut span_snippets = spans.iter()
@@ -177,6 +321,21 @@
                           } else {
                               String::new()
                           });
-        visitor.session.buffer_lint(lint::builtin::UNUSED_IMPORTS, *id, ms, &msg);
+
+        let fix_msg = if fixes.len() == 1 && fixes[0].0 == unused.item_span {
+            "remove the whole `use` item"
+        } else if spans.len() > 1 {
+            "remove the unused imports"
+        } else {
+            "remove the unused import"
+        };
+
+        visitor.session.buffer_lint_with_diagnostic(
+            lint::builtin::UNUSED_IMPORTS,
+            unused.use_tree_id,
+            ms,
+            &msg,
+            lint::builtin::BuiltinLintDiagnostics::UnusedImports(fix_msg.into(), fixes),
+        );
     }
 }
diff --git a/src/librustc_resolve/diagnostics.rs b/src/librustc_resolve/diagnostics.rs
index 0db8689..5c09599 100644
--- a/src/librustc_resolve/diagnostics.rs
+++ b/src/librustc_resolve/diagnostics.rs
@@ -414,8 +414,8 @@
 "##,
 
 E0401: r##"
-Inner items do not inherit type parameters from the functions they are embedded
-in.
+Inner items do not inherit type or const parameters from the functions
+they are embedded in.
 
 Erroneous code example:
 
diff --git a/src/librustc_resolve/error_reporting.rs b/src/librustc_resolve/error_reporting.rs
index b131a6b..8300e69 100644
--- a/src/librustc_resolve/error_reporting.rs
+++ b/src/librustc_resolve/error_reporting.rs
@@ -1,16 +1,423 @@
-use crate::{CrateLint, PathResult, Segment};
-use crate::macros::ParentScope;
-use crate::resolve_imports::ImportResolver;
+use std::cmp::Reverse;
 
+use log::debug;
+use rustc::hir::def::*;
+use rustc::hir::def::Namespace::*;
+use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
+use rustc::session::config::nightly_options;
+use syntax::ast::{ExprKind};
 use syntax::symbol::keywords;
 use syntax_pos::Span;
 
-use log::debug;
+use crate::errors::{Applicability, DiagnosticBuilder, DiagnosticId};
+use crate::macros::ParentScope;
+use crate::resolve_imports::ImportResolver;
+use crate::{import_candidate_to_enum_paths, is_self_type, is_self_value, path_names_to_string};
+use crate::{AssocSuggestion, CrateLint, ImportSuggestion, ModuleOrUniformRoot, PathResult,
+            PathSource, Resolver, Segment};
 
-use std::cmp::Reverse;
+impl<'a> Resolver<'a> {
+    /// Handles error reporting for `smart_resolve_path_fragment` function.
+    /// Creates base error and amends it with one short label and possibly some longer helps/notes.
+    pub(crate) fn smart_resolve_report_errors(
+        &mut self,
+        path: &[Segment],
+        span: Span,
+        source: PathSource<'_>,
+        def: Option<Def>,
+    ) -> (DiagnosticBuilder<'a>, Vec<ImportSuggestion>) {
+        let ident_span = path.last().map_or(span, |ident| ident.ident.span);
+        let ns = source.namespace();
+        let is_expected = &|def| source.is_expected(def);
+        let is_enum_variant = &|def| if let Def::Variant(..) = def { true } else { false };
+
+        // Make the base error.
+        let expected = source.descr_expected();
+        let path_str = Segment::names_to_string(path);
+        let item_str = path.last().unwrap().ident;
+        let code = source.error_code(def.is_some());
+        let (base_msg, fallback_label, base_span) = if let Some(def) = def {
+            (format!("expected {}, found {} `{}`", expected, def.kind_name(), path_str),
+                format!("not a {}", expected),
+                span)
+        } else {
+            let item_span = path.last().unwrap().ident.span;
+            let (mod_prefix, mod_str) = if path.len() == 1 {
+                (String::new(), "this scope".to_string())
+            } else if path.len() == 2 && path[0].ident.name == keywords::PathRoot.name() {
+                (String::new(), "the crate root".to_string())
+            } else {
+                let mod_path = &path[..path.len() - 1];
+                let mod_prefix = match self.resolve_path_without_parent_scope(
+                    mod_path, Some(TypeNS), false, span, CrateLint::No
+                ) {
+                    PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
+                        module.def(),
+                    _ => None,
+                }.map_or(String::new(), |def| format!("{} ", def.kind_name()));
+                (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
+            };
+            (format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
+                format!("not found in {}", mod_str),
+                item_span)
+        };
+
+        let code = DiagnosticId::Error(code.into());
+        let mut err = self.session.struct_span_err_with_code(base_span, &base_msg, code);
+
+        // Emit help message for fake-self from other languages (e.g., `this` in Javascript).
+        if ["this", "my"].contains(&&*item_str.as_str())
+            && self.self_value_is_available(path[0].ident.span, span) {
+            err.span_suggestion(
+                span,
+                "did you mean",
+                "self".to_string(),
+                Applicability::MaybeIncorrect,
+            );
+        }
+
+        // Emit special messages for unresolved `Self` and `self`.
+        if is_self_type(path, ns) {
+            __diagnostic_used!(E0411);
+            err.code(DiagnosticId::Error("E0411".into()));
+            err.span_label(span, format!("`Self` is only available in impls, traits, \
+                                          and type definitions"));
+            return (err, Vec::new());
+        }
+        if is_self_value(path, ns) {
+            debug!("smart_resolve_path_fragment: E0424, source={:?}", source);
+
+            __diagnostic_used!(E0424);
+            err.code(DiagnosticId::Error("E0424".into()));
+            err.span_label(span, match source {
+                PathSource::Pat => {
+                    format!("`self` value is a keyword \
+                             and may not be bound to \
+                             variables or shadowed")
+                }
+                _ => {
+                    format!("`self` value is a keyword \
+                             only available in methods \
+                             with `self` parameter")
+                }
+            });
+            return (err, Vec::new());
+        }
+
+        // Try to lookup name in more relaxed fashion for better error reporting.
+        let ident = path.last().unwrap().ident;
+        let candidates = self.lookup_import_candidates(ident, ns, is_expected);
+        if candidates.is_empty() && is_expected(Def::Enum(DefId::local(CRATE_DEF_INDEX))) {
+            let enum_candidates =
+                self.lookup_import_candidates(ident, ns, is_enum_variant);
+            let mut enum_candidates = enum_candidates.iter()
+                .map(|suggestion| {
+                    import_candidate_to_enum_paths(&suggestion)
+                }).collect::<Vec<_>>();
+            enum_candidates.sort();
+
+            if !enum_candidates.is_empty() {
+                // Contextualize for E0412 "cannot find type", but don't belabor the point
+                // (that it's a variant) for E0573 "expected type, found variant".
+                let preamble = if def.is_none() {
+                    let others = match enum_candidates.len() {
+                        1 => String::new(),
+                        2 => " and 1 other".to_owned(),
+                        n => format!(" and {} others", n)
+                    };
+                    format!("there is an enum variant `{}`{}; ",
+                            enum_candidates[0].0, others)
+                } else {
+                    String::new()
+                };
+                let msg = format!("{}try using the variant's enum", preamble);
+
+                err.span_suggestions(
+                    span,
+                    &msg,
+                    enum_candidates.into_iter()
+                        .map(|(_variant_path, enum_ty_path)| enum_ty_path)
+                        // Variants re-exported in prelude doesn't mean `prelude::v1` is the
+                        // type name!
+                        // FIXME: is there a more principled way to do this that
+                        // would work for other re-exports?
+                        .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1")
+                        // Also write `Option` rather than `std::prelude::v1::Option`.
+                        .map(|enum_ty_path| {
+                            // FIXME #56861: DRY-er prelude filtering.
+                            enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned()
+                        }),
+                    Applicability::MachineApplicable,
+                );
+            }
+        }
+        if path.len() == 1 && self.self_type_is_available(span) {
+            if let Some(candidate) = self.lookup_assoc_candidate(ident, ns, is_expected) {
+                let self_is_available = self.self_value_is_available(path[0].ident.span, span);
+                match candidate {
+                    AssocSuggestion::Field => {
+                        err.span_suggestion(
+                            span,
+                            "try",
+                            format!("self.{}", path_str),
+                            Applicability::MachineApplicable,
+                        );
+                        if !self_is_available {
+                            err.span_label(span, format!("`self` value is a keyword \
+                                                         only available in \
+                                                         methods with `self` parameter"));
+                        }
+                    }
+                    AssocSuggestion::MethodWithSelf if self_is_available => {
+                        err.span_suggestion(
+                            span,
+                            "try",
+                            format!("self.{}", path_str),
+                            Applicability::MachineApplicable,
+                        );
+                    }
+                    AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
+                        err.span_suggestion(
+                            span,
+                            "try",
+                            format!("Self::{}", path_str),
+                            Applicability::MachineApplicable,
+                        );
+                    }
+                }
+                return (err, candidates);
+            }
+        }
+
+        let mut levenshtein_worked = false;
+
+        // Try Levenshtein algorithm.
+        let suggestion = self.lookup_typo_candidate(path, ns, is_expected, span);
+        if let Some(suggestion) = suggestion {
+            let msg = format!(
+                "{} {} with a similar name exists",
+                suggestion.article, suggestion.kind
+            );
+            err.span_suggestion(
+                ident_span,
+                &msg,
+                suggestion.candidate.to_string(),
+                Applicability::MaybeIncorrect,
+            );
+
+            levenshtein_worked = true;
+        }
+
+        // Try context-dependent help if relaxed lookup didn't work.
+        if let Some(def) = def {
+            if self.smart_resolve_context_dependent_help(&mut err,
+                                                         span,
+                                                         source,
+                                                         def,
+                                                         &path_str,
+                                                         &fallback_label) {
+                return (err, candidates);
+            }
+        }
+
+        // Fallback label.
+        if !levenshtein_worked {
+            err.span_label(base_span, fallback_label);
+            self.type_ascription_suggestion(&mut err, base_span);
+        }
+        (err, candidates)
+    }
+
+    /// Provides context-dependent help for errors reported by the `smart_resolve_path_fragment`
+    /// function.
+    /// Returns `true` if able to provide context-dependent help.
+    fn smart_resolve_context_dependent_help(
+        &mut self,
+        err: &mut DiagnosticBuilder<'a>,
+        span: Span,
+        source: PathSource<'_>,
+        def: Def,
+        path_str: &str,
+        fallback_label: &str,
+    ) -> bool {
+        let ns = source.namespace();
+        let is_expected = &|def| source.is_expected(def);
+
+        match (def, source) {
+            (Def::Macro(..), _) => {
+                err.span_suggestion(
+                    span,
+                    "use `!` to invoke the macro",
+                    format!("{}!", path_str),
+                    Applicability::MaybeIncorrect,
+                );
+            }
+            (Def::TyAlias(..), PathSource::Trait(_)) => {
+                err.span_label(span, "type aliases cannot be used as traits");
+                if nightly_options::is_nightly_build() {
+                    err.note("did you mean to use a trait alias?");
+                }
+            }
+            (Def::Mod(..), PathSource::Expr(Some(parent))) => match parent.node {
+                ExprKind::Field(_, ident) => {
+                    err.span_suggestion(
+                        parent.span,
+                        "use the path separator to refer to an item",
+                        format!("{}::{}", path_str, ident),
+                        Applicability::MaybeIncorrect,
+                    );
+                }
+                ExprKind::MethodCall(ref segment, ..) => {
+                    let span = parent.span.with_hi(segment.ident.span.hi());
+                    err.span_suggestion(
+                        span,
+                        "use the path separator to refer to an item",
+                        format!("{}::{}", path_str, segment.ident),
+                        Applicability::MaybeIncorrect,
+                    );
+                }
+                _ => return false,
+            },
+            (Def::Enum(..), PathSource::TupleStruct)
+                | (Def::Enum(..), PathSource::Expr(..))  => {
+                if let Some(variants) = self.collect_enum_variants(def) {
+                    err.note(&format!("did you mean to use one \
+                                       of the following variants?\n{}",
+                        variants.iter()
+                            .map(|suggestion| path_names_to_string(suggestion))
+                            .map(|suggestion| format!("- `{}`", suggestion))
+                            .collect::<Vec<_>>()
+                            .join("\n")));
+                } else {
+                    err.note("did you mean to use one of the enum's variants?");
+                }
+            },
+            (Def::Struct(def_id), _) if ns == ValueNS => {
+                if let Some((ctor_def, ctor_vis))
+                        = self.struct_constructors.get(&def_id).cloned() {
+                    let accessible_ctor = self.is_accessible(ctor_vis);
+                    if is_expected(ctor_def) && !accessible_ctor {
+                        err.span_label(span, format!("constructor is not visible \
+                                                      here due to private fields"));
+                    }
+                } else {
+                    // HACK(estebank): find a better way to figure out that this was a
+                    // parser issue where a struct literal is being used on an expression
+                    // where a brace being opened means a block is being started. Look
+                    // ahead for the next text to see if `span` is followed by a `{`.
+                    let sm = self.session.source_map();
+                    let mut sp = span;
+                    loop {
+                        sp = sm.next_point(sp);
+                        match sm.span_to_snippet(sp) {
+                            Ok(ref snippet) => {
+                                if snippet.chars().any(|c| { !c.is_whitespace() }) {
+                                    break;
+                                }
+                            }
+                            _ => break,
+                        }
+                    }
+                    let followed_by_brace = match sm.span_to_snippet(sp) {
+                        Ok(ref snippet) if snippet == "{" => true,
+                        _ => false,
+                    };
+                    // In case this could be a struct literal that needs to be surrounded
+                    // by parenthesis, find the appropriate span.
+                    let mut i = 0;
+                    let mut closing_brace = None;
+                    loop {
+                        sp = sm.next_point(sp);
+                        match sm.span_to_snippet(sp) {
+                            Ok(ref snippet) => {
+                                if snippet == "}" {
+                                    let sp = span.to(sp);
+                                    if let Ok(snippet) = sm.span_to_snippet(sp) {
+                                        closing_brace = Some((sp, snippet));
+                                    }
+                                    break;
+                                }
+                            }
+                            _ => break,
+                        }
+                        i += 1;
+                        // The bigger the span, the more likely we're incorrect --
+                        // bound it to 100 chars long.
+                        if i > 100 {
+                            break;
+                        }
+                    }
+                    match source {
+                        PathSource::Expr(Some(parent)) => {
+                            match parent.node {
+                                ExprKind::MethodCall(ref path_assignment, _)  => {
+                                    err.span_suggestion(
+                                        sm.start_point(parent.span)
+                                            .to(path_assignment.ident.span),
+                                        "use `::` to access an associated function",
+                                        format!("{}::{}",
+                                                path_str,
+                                                path_assignment.ident),
+                                        Applicability::MaybeIncorrect
+                                    );
+                                },
+                                _ => {
+                                    err.span_label(
+                                        span,
+                                        format!("did you mean `{} {{ /* fields */ }}`?",
+                                                path_str),
+                                    );
+                                },
+                            }
+                        },
+                        PathSource::Expr(None) if followed_by_brace == true => {
+                            if let Some((sp, snippet)) = closing_brace {
+                                err.span_suggestion(
+                                    sp,
+                                    "surround the struct literal with parenthesis",
+                                    format!("({})", snippet),
+                                    Applicability::MaybeIncorrect,
+                                );
+                            } else {
+                                err.span_label(
+                                    span,
+                                    format!("did you mean `({} {{ /* fields */ }})`?",
+                                            path_str),
+                                );
+                            }
+                        },
+                        _ => {
+                            err.span_label(
+                                span,
+                                format!("did you mean `{} {{ /* fields */ }}`?",
+                                        path_str),
+                            );
+                        },
+                    }
+                }
+            }
+            (Def::Union(..), _) |
+            (Def::Variant(..), _) |
+            (Def::VariantCtor(_, CtorKind::Fictive), _) if ns == ValueNS => {
+                err.span_label(span, format!("did you mean `{} {{ /* fields */ }}`?",
+                                             path_str));
+            }
+            (Def::SelfTy(..), _) if ns == ValueNS => {
+                err.span_label(span, fallback_label);
+                err.note("can't use `Self` as a constructor, you must use the \
+                          implemented struct");
+            }
+            (Def::TyAlias(_), _) | (Def::AssociatedTy(..), _) if ns == ValueNS => {
+                err.note("can't use a type alias as a constructor");
+            }
+            _ => return false,
+        }
+        true
+    }
+}
 
 impl<'a, 'b:'a> ImportResolver<'a, 'b> {
-    /// Add suggestions for a path that cannot be resolved.
+    /// Adds suggestions for a path that cannot be resolved.
     pub(crate) fn make_path_suggestion(
         &mut self,
         span: Span,
@@ -24,7 +431,7 @@
             // On 2015 `{{root}}` is usually added implicitly.
             (Some(fst), Some(snd)) if fst.ident.name == keywords::PathRoot.name() &&
                                       !snd.ident.is_path_segment_keyword() => {}
-            // `ident::...` on 2018
+            // `ident::...` on 2018.
             (Some(fst), _) if fst.ident.span.rust_2018() &&
                               !fst.ident.is_path_segment_keyword() => {
                 // Insert a placeholder that's later replaced by `self`/`super`/etc.
@@ -63,7 +470,7 @@
         }
     }
 
-    /// Suggest a missing `crate::` if that resolves to an correct module.
+    /// Suggests a missing `crate::` if that resolves to an correct module.
     ///
     /// ```
     ///    |
@@ -94,7 +501,7 @@
         }
     }
 
-    /// Suggest a missing `super::` if that resolves to an correct module.
+    /// Suggests a missing `super::` if that resolves to an correct module.
     ///
     /// ```
     ///    |
@@ -118,7 +525,7 @@
         }
     }
 
-    /// Suggest a missing external crate name if that resolves to an correct module.
+    /// Suggests a missing external crate name if that resolves to an correct module.
     ///
     /// ```
     ///    |
@@ -139,7 +546,7 @@
         }
 
         // Sort extern crate names in reverse order to get
-        // 1) some consistent ordering for emitted dignostics and
+        // 1) some consistent ordering for emitted dignostics, and
         // 2) `std` suggestions before `core` suggestions.
         let mut extern_crate_names =
             self.resolver.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs
index b166b1b..ecbfcec 100644
--- a/src/librustc_resolve/lib.rs
+++ b/src/librustc_resolve/lib.rs
@@ -1,6 +1,4 @@
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 
 #![feature(crate_visibility_modifier)]
 #![feature(label_break_value)]
@@ -15,7 +13,7 @@
 
 pub use rustc::hir::def::{Namespace, PerNS};
 
-use TypeParameters::*;
+use GenericParameters::*;
 use RibKind::*;
 
 use rustc::hir::map::{Definitions, DefCollector};
@@ -27,7 +25,6 @@
 use rustc::hir::def::Namespace::*;
 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
 use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
-use rustc::session::config::nightly_options;
 use rustc::ty;
 use rustc::util::nodemap::{NodeMap, NodeSet, FxHashMap, FxHashSet, DefIdMap};
 use rustc::{bug, span_bug};
@@ -142,10 +139,11 @@
 }
 
 enum ResolutionError<'a> {
-    /// error E0401: can't use type parameters from outer function
-    TypeParametersFromOuterFunction(Def),
-    /// error E0403: the name is already used for a type parameter in this type parameter list
-    NameAlreadyUsedInTypeParameterList(Name, &'a Span),
+    /// error E0401: can't use type or const parameters from outer function
+    GenericParamsFromOuterFunction(Def),
+    /// error E0403: the name is already used for a type/const parameter in this list of
+    /// generic parameters
+    NameAlreadyUsedInParameterList(Name, &'a Span),
     /// error E0407: method is not a member of trait
     MethodNotMemberOfTrait(Name, &'a str),
     /// error E0437: type is not a member of trait
@@ -177,7 +175,7 @@
     /// error E0530: X bindings cannot shadow Ys
     BindingShadowsSomethingUnacceptable(&'a str, Name, &'a NameBinding<'a>),
     /// error E0128: type parameters with a default cannot use forward declared identifiers
-    ForwardDeclaredTyParam,
+    ForwardDeclaredTyParam, // FIXME(const_generics:defaults)
 }
 
 /// Combines an error with provided span and emits it
@@ -195,12 +193,13 @@
                                    resolution_error: ResolutionError<'a>)
                                    -> DiagnosticBuilder<'sess> {
     match resolution_error {
-        ResolutionError::TypeParametersFromOuterFunction(outer_def) => {
+        ResolutionError::GenericParamsFromOuterFunction(outer_def) => {
             let mut err = struct_span_err!(resolver.session,
-                                           span,
-                                           E0401,
-                                           "can't use type parameters from outer function");
-            err.span_label(span, "use of type variable from outer function");
+                span,
+                E0401,
+                "can't use generic parameters from outer function",
+            );
+            err.span_label(span, format!("use of generic parameter from outer function"));
 
             let cm = resolver.session.source_map();
             match outer_def {
@@ -224,20 +223,25 @@
                     }
                     return err;
                 },
-                Def::TyParam(typaram_defid) => {
-                    if let Some(typaram_span) = resolver.definitions.opt_span(typaram_defid) {
-                        err.span_label(typaram_span, "type variable from outer function");
+                Def::TyParam(def_id) => {
+                    if let Some(span) = resolver.definitions.opt_span(def_id) {
+                        err.span_label(span, "type variable from outer function");
                     }
-                },
+                }
+                Def::ConstParam(def_id) => {
+                    if let Some(span) = resolver.definitions.opt_span(def_id) {
+                        err.span_label(span, "const variable from outer function");
+                    }
+                }
                 _ => {
-                    bug!("TypeParametersFromOuterFunction should only be used with Def::SelfTy or \
-                         Def::TyParam")
+                    bug!("GenericParamsFromOuterFunction should only be used with Def::SelfTy, \
+                         Def::TyParam");
                 }
             }
 
             // Try to retrieve the span of the function signature and generate a new message with
-            // a local type parameter
-            let sugg_msg = "try using a local type parameter instead";
+            // a local type or const parameter.
+            let sugg_msg = &format!("try using a local generic parameter instead");
             if let Some((sugg_span, new_snippet)) = cm.generate_local_type_param_snippet(span) {
                 // Suggest the modification to the user
                 err.span_suggestion(
@@ -247,19 +251,20 @@
                     Applicability::MachineApplicable,
                 );
             } else if let Some(sp) = cm.generate_fn_name_span(span) {
-                err.span_label(sp, "try adding a local type parameter in this method instead");
+                err.span_label(sp,
+                    format!("try adding a local generic parameter in this method instead"));
             } else {
-                err.help("try using a local type parameter instead");
+                err.help(&format!("try using a local generic parameter instead"));
             }
 
             err
         }
-        ResolutionError::NameAlreadyUsedInTypeParameterList(name, first_use_span) => {
+        ResolutionError::NameAlreadyUsedInParameterList(name, first_use_span) => {
              let mut err = struct_span_err!(resolver.session,
                                             span,
                                             E0403,
-                                            "the name `{}` is already used for a type parameter \
-                                            in this type parameter list",
+                                            "the name `{}` is already used for a generic \
+                                            parameter in this list of generic parameters",
                                             name);
              err.span_label(span, "already used");
              err.span_label(first_use_span.clone(), format!("first use of `{}`", name));
@@ -546,8 +551,7 @@
                 Def::Struct(..) | Def::Union(..) | Def::Enum(..) |
                 Def::Trait(..) | Def::TraitAlias(..) | Def::TyAlias(..) |
                 Def::AssociatedTy(..) | Def::PrimTy(..) | Def::TyParam(..) |
-                Def::SelfTy(..) | Def::Existential(..) |
-                Def::ForeignTy(..) => true,
+                Def::SelfTy(..) | Def::Existential(..) | Def::ForeignTy(..) => true,
                 _ => false,
             },
             PathSource::Trait(AliasPossibility::No) => match def {
@@ -564,7 +568,7 @@
                 Def::VariantCtor(_, CtorKind::Const) | Def::VariantCtor(_, CtorKind::Fn) |
                 Def::Const(..) | Def::Static(..) | Def::Local(..) | Def::Upvar(..) |
                 Def::Fn(..) | Def::Method(..) | Def::AssociatedConst(..) |
-                Def::SelfCtor(..) => true,
+                Def::SelfCtor(..) | Def::ConstParam(..) => true,
                 _ => false,
             },
             PathSource::Pat => match def {
@@ -748,6 +752,7 @@
         self.resolve_block(block);
     }
     fn visit_anon_const(&mut self, constant: &'tcx ast::AnonConst) {
+        debug!("visit_anon_const {:?}", constant);
         self.with_constant_rib(|this| {
             visit::walk_anon_const(this, constant);
         });
@@ -781,15 +786,15 @@
         visit::walk_poly_trait_ref(self, tref, m);
     }
     fn visit_foreign_item(&mut self, foreign_item: &'tcx ForeignItem) {
-        let type_parameters = match foreign_item.node {
+        let generic_params = match foreign_item.node {
             ForeignItemKind::Fn(_, ref generics) => {
-                HasTypeParameters(generics, ItemRibKind)
+                HasGenericParams(generics, ItemRibKind)
             }
-            ForeignItemKind::Static(..) => NoTypeParameters,
-            ForeignItemKind::Ty => NoTypeParameters,
-            ForeignItemKind::Macro(..) => NoTypeParameters,
+            ForeignItemKind::Static(..) => NoGenericParams,
+            ForeignItemKind::Ty => NoGenericParams,
+            ForeignItemKind::Macro(..) => NoGenericParams,
         };
-        self.with_type_parameter_rib(type_parameters, |this| {
+        self.with_generic_param_rib(generic_params, |this| {
             visit::walk_foreign_item(this, foreign_item);
         });
     }
@@ -799,6 +804,7 @@
                 _: Span,
                 node_id: NodeId)
     {
+        debug!("(resolving function) entering function");
         let (rib_kind, asyncness) = match function_kind {
             FnKind::ItemFn(_, ref header, ..) =>
                 (ItemRibKind, header.asyncness),
@@ -855,6 +861,7 @@
         self.label_ribs.pop();
         self.ribs[ValueNS].pop();
     }
+
     fn visit_generics(&mut self, generics: &'tcx Generics) {
         // For type parameter defaults, we have to ban access
         // to following type parameters, as the Substs can only
@@ -865,6 +872,7 @@
         let mut found_default = false;
         default_ban_rib.bindings.extend(generics.params.iter()
             .filter_map(|param| match param.kind {
+                GenericParamKind::Const { .. } |
                 GenericParamKind::Lifetime { .. } => None,
                 GenericParamKind::Type { ref default, .. } => {
                     found_default |= default.is_some();
@@ -893,6 +901,13 @@
                     // Allow all following defaults to refer to this type parameter.
                     default_ban_rib.bindings.remove(&Ident::with_empty_ctxt(param.ident.name));
                 }
+                GenericParamKind::Const { ref ty } => {
+                    for bound in &param.bounds {
+                        self.visit_param_bound(bound);
+                    }
+
+                    self.visit_ty(ty);
+                }
             }
         }
         for p in &generics.where_clause.predicates {
@@ -902,9 +917,9 @@
 }
 
 #[derive(Copy, Clone)]
-enum TypeParameters<'a, 'b> {
-    NoTypeParameters,
-    HasTypeParameters(// Type parameters.
+enum GenericParameters<'a, 'b> {
+    NoGenericParams,
+    HasGenericParams(// Type parameters.
                       &'b Generics,
 
                       // The kind of the rib used for type parameters.
@@ -1740,7 +1755,7 @@
         }
     }
 
-    /// resolve_hir_path, but takes a callback in case there was an error
+    /// Like `resolve_hir_path`, but takes a callback in case there was an error.
     fn resolve_hir_path_cb<F>(
         &mut self,
         path: &ast::Path,
@@ -1753,7 +1768,7 @@
         let span = path.span;
         let segments = &path.segments;
         let path = Segment::from_path(&path);
-        // FIXME (Manishearth): Intra doc links won't get warned of epoch changes
+        // FIXME(Manishearth): intra-doc links won't get warned of epoch changes.
         let def = match self.resolve_path_without_parent_scope(&path, Some(namespace), true,
                                                                span, CrateLint::No) {
             PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
@@ -2040,6 +2055,7 @@
         let record_used = record_used_id.is_some();
         let mut module = self.graph_root;
         for i in (0 .. self.ribs[ns].len()).rev() {
+            debug!("walk rib\n{:?}", self.ribs[ns][i].bindings);
             if let Some(def) = self.ribs[ns][i].bindings.get(&ident).cloned() {
                 // The ident resolves to a type parameter or local variable.
                 return Some(LexicalScopeBinding::Def(
@@ -2361,8 +2377,9 @@
     }
 
     fn resolve_adt(&mut self, item: &Item, generics: &Generics) {
+        debug!("resolve_adt");
         self.with_current_self_item(item, |this| {
-            this.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
+            this.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
                 let item_def_id = this.definitions.local_def_id(item.id);
                 this.with_self_rib(Def::SelfTy(None, Some(item_def_id)), |this| {
                     visit::walk_item(this, item);
@@ -2415,13 +2432,13 @@
 
     fn resolve_item(&mut self, item: &Item) {
         let name = item.ident.name;
-        debug!("(resolving item) resolving {}", name);
+        debug!("(resolving item) resolving {} ({:?})", name, item.node);
 
         match item.node {
             ItemKind::Ty(_, ref generics) |
             ItemKind::Fn(_, _, ref generics, _) |
             ItemKind::Existential(_, ref generics) => {
-                self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind),
+                self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind),
                                              |this| visit::walk_item(this, item));
             }
 
@@ -2440,16 +2457,16 @@
 
             ItemKind::Trait(.., ref generics, ref bounds, ref trait_items) => {
                 // Create a new rib for the trait-wide type parameters.
-                self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
+                self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
                     let local_def_id = this.definitions.local_def_id(item.id);
                     this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
                         this.visit_generics(generics);
                         walk_list!(this, visit_param_bound, bounds);
 
                         for trait_item in trait_items {
-                            let type_parameters = HasTypeParameters(&trait_item.generics,
+                            let generic_params = HasGenericParams(&trait_item.generics,
                                                                     TraitOrImplItemRibKind);
-                            this.with_type_parameter_rib(type_parameters, |this| {
+                            this.with_generic_param_rib(generic_params, |this| {
                                 match trait_item.node {
                                     TraitItemKind::Const(ref ty, ref default) => {
                                         this.visit_ty(ty);
@@ -2481,7 +2498,7 @@
 
             ItemKind::TraitAlias(ref generics, ref bounds) => {
                 // Create a new rib for the trait-wide type parameters.
-                self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
+                self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
                     let local_def_id = this.definitions.local_def_id(item.id);
                     this.with_self_rib(Def::SelfTy(Some(local_def_id), None), |this| {
                         this.visit_generics(generics);
@@ -2498,6 +2515,7 @@
 
             ItemKind::Static(ref ty, _, ref expr) |
             ItemKind::Const(ref ty, ref expr) => {
+                debug!("resolve_item ItemKind::Const");
                 self.with_item_rib(|this| {
                     this.visit_ty(ty);
                     this.with_constant_rib(|this| {
@@ -2519,23 +2537,25 @@
         }
     }
 
-    fn with_type_parameter_rib<'b, F>(&'b mut self, type_parameters: TypeParameters<'a, 'b>, f: F)
+    fn with_generic_param_rib<'b, F>(&'b mut self, generic_params: GenericParameters<'a, 'b>, f: F)
         where F: FnOnce(&mut Resolver<'_>)
     {
-        match type_parameters {
-            HasTypeParameters(generics, rib_kind) => {
+        debug!("with_generic_param_rib");
+        match generic_params {
+            HasGenericParams(generics, rib_kind) => {
                 let mut function_type_rib = Rib::new(rib_kind);
+                let mut function_value_rib = Rib::new(rib_kind);
                 let mut seen_bindings = FxHashMap::default();
                 for param in &generics.params {
                     match param.kind {
                         GenericParamKind::Lifetime { .. } => {}
                         GenericParamKind::Type { .. } => {
                             let ident = param.ident.modern();
-                            debug!("with_type_parameter_rib: {}", param.id);
+                            debug!("with_generic_param_rib: {}", param.id);
 
                             if seen_bindings.contains_key(&ident) {
                                 let span = seen_bindings.get(&ident).unwrap();
-                                let err = ResolutionError::NameAlreadyUsedInTypeParameterList(
+                                let err = ResolutionError::NameAlreadyUsedInParameterList(
                                     ident.name,
                                     span,
                                 );
@@ -2548,20 +2568,40 @@
                             function_type_rib.bindings.insert(ident, def);
                             self.record_def(param.id, PathResolution::new(def));
                         }
+                        GenericParamKind::Const { .. } => {
+                            let ident = param.ident.modern();
+                            debug!("with_generic_param_rib: {}", param.id);
+
+                            if seen_bindings.contains_key(&ident) {
+                                let span = seen_bindings.get(&ident).unwrap();
+                                let err = ResolutionError::NameAlreadyUsedInParameterList(
+                                    ident.name,
+                                    span,
+                                );
+                                resolve_error(self, param.ident.span, err);
+                            }
+                            seen_bindings.entry(ident).or_insert(param.ident.span);
+
+                            let def = Def::ConstParam(self.definitions.local_def_id(param.id));
+                            function_value_rib.bindings.insert(ident, def);
+                            self.record_def(param.id, PathResolution::new(def));
+                        }
                     }
                 }
+                self.ribs[ValueNS].push(function_value_rib);
                 self.ribs[TypeNS].push(function_type_rib);
             }
 
-            NoTypeParameters => {
+            NoGenericParams => {
                 // Nothing to do.
             }
         }
 
         f(self);
 
-        if let HasTypeParameters(..) = type_parameters {
+        if let HasGenericParams(..) = generic_params {
             self.ribs[TypeNS].pop();
+            self.ribs[ValueNS].pop();
         }
     }
 
@@ -2586,6 +2626,7 @@
     fn with_constant_rib<F>(&mut self, f: F)
         where F: FnOnce(&mut Resolver<'_>)
     {
+        debug!("with_constant_rib");
         self.ribs[ValueNS].push(Rib::new(ConstantItemRibKind));
         self.label_ribs.push(Rib::new(ConstantItemRibKind));
         f(self);
@@ -2679,8 +2720,9 @@
                               self_type: &Ty,
                               item_id: NodeId,
                               impl_items: &[ImplItem]) {
+        debug!("resolve_implementation");
         // If applicable, create a rib for the type parameters.
-        self.with_type_parameter_rib(HasTypeParameters(generics, ItemRibKind), |this| {
+        self.with_generic_param_rib(HasGenericParams(generics, ItemRibKind), |this| {
             // Dummy self type for better errors if `Self` is used in the trait path.
             this.with_self_rib(Def::SelfTy(None, None), |this| {
                 // Resolve the trait reference, if necessary.
@@ -2693,30 +2735,37 @@
                         }
                         // Resolve the self type.
                         this.visit_ty(self_type);
-                        // Resolve the type parameters.
+                        // Resolve the generic parameters.
                         this.visit_generics(generics);
                         // Resolve the items within the impl.
                         this.with_current_self_type(self_type, |this| {
                             this.with_self_struct_ctor_rib(item_def_id, |this| {
+                                debug!("resolve_implementation with_self_struct_ctor_rib");
                                 for impl_item in impl_items {
                                     this.resolve_visibility(&impl_item.vis);
 
                                     // We also need a new scope for the impl item type parameters.
-                                    let type_parameters = HasTypeParameters(&impl_item.generics,
-                                                                            TraitOrImplItemRibKind);
-                                    this.with_type_parameter_rib(type_parameters, |this| {
+                                    let generic_params = HasGenericParams(&impl_item.generics,
+                                                                          TraitOrImplItemRibKind);
+                                    this.with_generic_param_rib(generic_params, |this| {
                                         use self::ResolutionError::*;
                                         match impl_item.node {
                                             ImplItemKind::Const(..) => {
+                                                debug!(
+                                                    "resolve_implementation ImplItemKind::Const",
+                                                );
                                                 // If this is a trait impl, ensure the const
                                                 // exists in trait
-                                                this.check_trait_item(impl_item.ident,
-                                                                      ValueNS,
-                                                                      impl_item.span,
-                                                    |n, s| ConstNotMemberOfTrait(n, s));
-                                                this.with_constant_rib(|this|
-                                                    visit::walk_impl_item(this, impl_item)
+                                                this.check_trait_item(
+                                                    impl_item.ident,
+                                                    ValueNS,
+                                                    impl_item.span,
+                                                    |n, s| ConstNotMemberOfTrait(n, s),
                                                 );
+
+                                                this.with_constant_rib(|this| {
+                                                    visit::walk_impl_item(this, impl_item)
+                                                });
                                             }
                                             ImplItemKind::Method(..) => {
                                                 // If this is a trait impl, ensure the method
@@ -3134,383 +3183,11 @@
                                    source: PathSource<'_>,
                                    crate_lint: CrateLint)
                                    -> PathResolution {
-        let ident_span = path.last().map_or(span, |ident| ident.ident.span);
         let ns = source.namespace();
         let is_expected = &|def| source.is_expected(def);
-        let is_enum_variant = &|def| if let Def::Variant(..) = def { true } else { false };
 
-        // Base error is amended with one short label and possibly some longer helps/notes.
         let report_errors = |this: &mut Self, def: Option<Def>| {
-            // Make the base error.
-            let expected = source.descr_expected();
-            let path_str = Segment::names_to_string(path);
-            let item_str = path.last().unwrap().ident;
-            let code = source.error_code(def.is_some());
-            let (base_msg, fallback_label, base_span) = if let Some(def) = def {
-                (format!("expected {}, found {} `{}`", expected, def.kind_name(), path_str),
-                 format!("not a {}", expected),
-                 span)
-            } else {
-                let item_span = path.last().unwrap().ident.span;
-                let (mod_prefix, mod_str) = if path.len() == 1 {
-                    (String::new(), "this scope".to_string())
-                } else if path.len() == 2 && path[0].ident.name == keywords::PathRoot.name() {
-                    (String::new(), "the crate root".to_string())
-                } else {
-                    let mod_path = &path[..path.len() - 1];
-                    let mod_prefix = match this.resolve_path_without_parent_scope(
-                        mod_path, Some(TypeNS), false, span, CrateLint::No
-                    ) {
-                        PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
-                            module.def(),
-                        _ => None,
-                    }.map_or(String::new(), |def| format!("{} ", def.kind_name()));
-                    (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
-                };
-                (format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
-                 format!("not found in {}", mod_str),
-                 item_span)
-            };
-
-            let code = DiagnosticId::Error(code.into());
-            let mut err = this.session.struct_span_err_with_code(base_span, &base_msg, code);
-
-            // Emit help message for fake-self from other languages like `this`(javascript)
-            if ["this", "my"].contains(&&*item_str.as_str())
-                && this.self_value_is_available(path[0].ident.span, span) {
-                err.span_suggestion(
-                    span,
-                    "did you mean",
-                    "self".to_string(),
-                    Applicability::MaybeIncorrect,
-                );
-            }
-
-            // Emit special messages for unresolved `Self` and `self`.
-            if is_self_type(path, ns) {
-                __diagnostic_used!(E0411);
-                err.code(DiagnosticId::Error("E0411".into()));
-                err.span_label(span, format!("`Self` is only available in impls, traits, \
-                                              and type definitions"));
-                return (err, Vec::new());
-            }
-            if is_self_value(path, ns) {
-                debug!("smart_resolve_path_fragment E0424 source:{:?}", source);
-
-                __diagnostic_used!(E0424);
-                err.code(DiagnosticId::Error("E0424".into()));
-                err.span_label(span, match source {
-                    PathSource::Pat => {
-                        format!("`self` value is a keyword \
-                                and may not be bound to \
-                                variables or shadowed")
-                    }
-                    _ => {
-                        format!("`self` value is a keyword \
-                                only available in methods \
-                                with `self` parameter")
-                    }
-                });
-                return (err, Vec::new());
-            }
-
-            // Try to lookup the name in more relaxed fashion for better error reporting.
-            let ident = path.last().unwrap().ident;
-            let candidates = this.lookup_import_candidates(ident, ns, is_expected);
-            if candidates.is_empty() && is_expected(Def::Enum(DefId::local(CRATE_DEF_INDEX))) {
-                let enum_candidates =
-                    this.lookup_import_candidates(ident, ns, is_enum_variant);
-                let mut enum_candidates = enum_candidates.iter()
-                    .map(|suggestion| {
-                        import_candidate_to_enum_paths(&suggestion)
-                    }).collect::<Vec<_>>();
-                enum_candidates.sort();
-
-                if !enum_candidates.is_empty() {
-                    // contextualize for E0412 "cannot find type", but don't belabor the point
-                    // (that it's a variant) for E0573 "expected type, found variant"
-                    let preamble = if def.is_none() {
-                        let others = match enum_candidates.len() {
-                            1 => String::new(),
-                            2 => " and 1 other".to_owned(),
-                            n => format!(" and {} others", n)
-                        };
-                        format!("there is an enum variant `{}`{}; ",
-                                enum_candidates[0].0, others)
-                    } else {
-                        String::new()
-                    };
-                    let msg = format!("{}try using the variant's enum", preamble);
-
-                    err.span_suggestions(
-                        span,
-                        &msg,
-                        enum_candidates.into_iter()
-                            .map(|(_variant_path, enum_ty_path)| enum_ty_path)
-                            // variants reëxported in prelude doesn't mean `prelude::v1` is the
-                            // type name! FIXME: is there a more principled way to do this that
-                            // would work for other reëxports?
-                            .filter(|enum_ty_path| enum_ty_path != "std::prelude::v1")
-                            // also say `Option` rather than `std::prelude::v1::Option`
-                            .map(|enum_ty_path| {
-                                // FIXME #56861: DRYer prelude filtering
-                                enum_ty_path.trim_start_matches("std::prelude::v1::").to_owned()
-                            }),
-                        Applicability::MachineApplicable,
-                    );
-                }
-            }
-            if path.len() == 1 && this.self_type_is_available(span) {
-                if let Some(candidate) = this.lookup_assoc_candidate(ident, ns, is_expected) {
-                    let self_is_available = this.self_value_is_available(path[0].ident.span, span);
-                    match candidate {
-                        AssocSuggestion::Field => {
-                            err.span_suggestion(
-                                span,
-                                "try",
-                                format!("self.{}", path_str),
-                                Applicability::MachineApplicable,
-                            );
-                            if !self_is_available {
-                                err.span_label(span, format!("`self` value is a keyword \
-                                                               only available in \
-                                                               methods with `self` parameter"));
-                            }
-                        }
-                        AssocSuggestion::MethodWithSelf if self_is_available => {
-                            err.span_suggestion(
-                                span,
-                                "try",
-                                format!("self.{}", path_str),
-                                Applicability::MachineApplicable,
-                            );
-                        }
-                        AssocSuggestion::MethodWithSelf | AssocSuggestion::AssocItem => {
-                            err.span_suggestion(
-                                span,
-                                "try",
-                                format!("Self::{}", path_str),
-                                Applicability::MachineApplicable,
-                            );
-                        }
-                    }
-                    return (err, candidates);
-                }
-            }
-
-            let mut levenshtein_worked = false;
-
-            // Try Levenshtein algorithm.
-            let suggestion = this.lookup_typo_candidate(path, ns, is_expected, span);
-            if let Some(suggestion) = suggestion {
-                let msg = format!(
-                    "{} {} with a similar name exists",
-                    suggestion.article, suggestion.kind
-                );
-                err.span_suggestion(
-                    ident_span,
-                    &msg,
-                    suggestion.candidate.to_string(),
-                    Applicability::MaybeIncorrect,
-                );
-
-                levenshtein_worked = true;
-            }
-
-            // Try context dependent help if relaxed lookup didn't work.
-            if let Some(def) = def {
-                match (def, source) {
-                    (Def::Macro(..), _) => {
-                        err.span_suggestion(
-                            span,
-                            "use `!` to invoke the macro",
-                            format!("{}!", path_str),
-                            Applicability::MaybeIncorrect,
-                        );
-                        return (err, candidates);
-                    }
-                    (Def::TyAlias(..), PathSource::Trait(_)) => {
-                        err.span_label(span, "type aliases cannot be used as traits");
-                        if nightly_options::is_nightly_build() {
-                            err.note("did you mean to use a trait alias?");
-                        }
-                        return (err, candidates);
-                    }
-                    (Def::Mod(..), PathSource::Expr(Some(parent))) => match parent.node {
-                        ExprKind::Field(_, ident) => {
-                            err.span_suggestion(
-                                parent.span,
-                                "use the path separator to refer to an item",
-                                format!("{}::{}", path_str, ident),
-                                Applicability::MaybeIncorrect,
-                            );
-                            return (err, candidates);
-                        }
-                        ExprKind::MethodCall(ref segment, ..) => {
-                            let span = parent.span.with_hi(segment.ident.span.hi());
-                            err.span_suggestion(
-                                span,
-                                "use the path separator to refer to an item",
-                                format!("{}::{}", path_str, segment.ident),
-                                Applicability::MaybeIncorrect,
-                            );
-                            return (err, candidates);
-                        }
-                        _ => {}
-                    },
-                    (Def::Enum(..), PathSource::TupleStruct)
-                        | (Def::Enum(..), PathSource::Expr(..))  => {
-                        if let Some(variants) = this.collect_enum_variants(def) {
-                            err.note(&format!("did you mean to use one \
-                                               of the following variants?\n{}",
-                                variants.iter()
-                                    .map(|suggestion| path_names_to_string(suggestion))
-                                    .map(|suggestion| format!("- `{}`", suggestion))
-                                    .collect::<Vec<_>>()
-                                    .join("\n")));
-
-                        } else {
-                            err.note("did you mean to use one of the enum's variants?");
-                        }
-                        return (err, candidates);
-                    },
-                    (Def::Struct(def_id), _) if ns == ValueNS => {
-                        if let Some((ctor_def, ctor_vis))
-                                = this.struct_constructors.get(&def_id).cloned() {
-                            let accessible_ctor = this.is_accessible(ctor_vis);
-                            if is_expected(ctor_def) && !accessible_ctor {
-                                err.span_label(span, format!("constructor is not visible \
-                                                              here due to private fields"));
-                            }
-                        } else {
-                            // HACK(estebank): find a better way to figure out that this was a
-                            // parser issue where a struct literal is being used on an expression
-                            // where a brace being opened means a block is being started. Look
-                            // ahead for the next text to see if `span` is followed by a `{`.
-                            let sm = this.session.source_map();
-                            let mut sp = span;
-                            loop {
-                                sp = sm.next_point(sp);
-                                match sm.span_to_snippet(sp) {
-                                    Ok(ref snippet) => {
-                                        if snippet.chars().any(|c| { !c.is_whitespace() }) {
-                                            break;
-                                        }
-                                    }
-                                    _ => break,
-                                }
-                            }
-                            let followed_by_brace = match sm.span_to_snippet(sp) {
-                                Ok(ref snippet) if snippet == "{" => true,
-                                _ => false,
-                            };
-                            // In case this could be a struct literal that needs to be surrounded
-                            // by parenthesis, find the appropriate span.
-                            let mut i = 0;
-                            let mut closing_brace = None;
-                            loop {
-                                sp = sm.next_point(sp);
-                                match sm.span_to_snippet(sp) {
-                                    Ok(ref snippet) => {
-                                        if snippet == "}" {
-                                            let sp = span.to(sp);
-                                            if let Ok(snippet) = sm.span_to_snippet(sp) {
-                                                closing_brace = Some((sp, snippet));
-                                            }
-                                            break;
-                                        }
-                                    }
-                                    _ => break,
-                                }
-                                i += 1;
-                                if i > 100 { // The bigger the span the more likely we're
-                                    break;   // incorrect. Bound it to 100 chars long.
-                                }
-                            }
-                            match source {
-                                PathSource::Expr(Some(parent)) => {
-                                    match parent.node {
-                                        ExprKind::MethodCall(ref path_assignment, _)  => {
-                                            err.span_suggestion(
-                                                sm.start_point(parent.span)
-                                                  .to(path_assignment.ident.span),
-                                                "use `::` to access an associated function",
-                                                format!("{}::{}",
-                                                        path_str,
-                                                        path_assignment.ident),
-                                                Applicability::MaybeIncorrect
-                                            );
-                                            return (err, candidates);
-                                        },
-                                        _ => {
-                                            err.span_label(
-                                                span,
-                                                format!("did you mean `{} {{ /* fields */ }}`?",
-                                                        path_str),
-                                            );
-                                            return (err, candidates);
-                                        },
-                                    }
-                                },
-                                PathSource::Expr(None) if followed_by_brace == true => {
-                                    if let Some((sp, snippet)) = closing_brace {
-                                        err.span_suggestion(
-                                            sp,
-                                            "surround the struct literal with parenthesis",
-                                            format!("({})", snippet),
-                                            Applicability::MaybeIncorrect,
-                                        );
-                                    } else {
-                                        err.span_label(
-                                            span,
-                                            format!("did you mean `({} {{ /* fields */ }})`?",
-                                                    path_str),
-                                        );
-                                    }
-                                    return (err, candidates);
-                                },
-                                _ => {
-                                    err.span_label(
-                                        span,
-                                        format!("did you mean `{} {{ /* fields */ }}`?",
-                                                path_str),
-                                    );
-                                    return (err, candidates);
-                                },
-                            }
-                        }
-                        return (err, candidates);
-                    }
-                    (Def::Union(..), _) |
-                    (Def::Variant(..), _) |
-                    (Def::VariantCtor(_, CtorKind::Fictive), _) if ns == ValueNS => {
-                        err.span_label(span, format!("did you mean `{} {{ /* fields */ }}`?",
-                                                     path_str));
-                        return (err, candidates);
-                    }
-                    (Def::SelfTy(..), _) if ns == ValueNS => {
-                        err.span_label(span, fallback_label);
-                        err.note("can't use `Self` as a constructor, you must use the \
-                                  implemented struct");
-                        return (err, candidates);
-                    }
-                    (Def::TyAlias(_), _) | (Def::AssociatedTy(..), _) if ns == ValueNS => {
-                        err.note("can't use a type alias as a constructor");
-                        return (err, candidates);
-                    }
-                    _ => {}
-                }
-            }
-
-            // Fallback label.
-            if !levenshtein_worked {
-                err.span_label(base_span, fallback_label);
-                this.type_ascription_suggestion(&mut err, base_span);
-            }
-            (err, candidates)
-        };
-        let report_errors = |this: &mut Self, def: Option<Def>| {
-            let (err, candidates) = report_errors(this, def);
+            let (err, candidates) = this.smart_resolve_report_errors(path, span, source, def);
             let def_id = this.current_module.normal_ancestor_id;
             let node_id = this.definitions.as_local_node_id(def_id).unwrap();
             let better = def.is_some();
@@ -3581,7 +3258,8 @@
         debug!("self.current_type_ascription {:?}", self.current_type_ascription);
         if let Some(sp) = self.current_type_ascription.last() {
             let mut sp = *sp;
-            loop {  // try to find the `:`, bail on first non-':'/non-whitespace
+            loop {
+                // Try to find the `:`; bail on first non-':' / non-whitespace.
                 sp = cm.next_point(sp);
                 if let Ok(snippet) = cm.span_to_snippet(sp.to(cm.next_point(sp))) {
                     debug!("snippet {:?}", snippet);
@@ -4095,6 +3773,7 @@
                         mut def: Def,
                         record_used: bool,
                         span: Span) -> Def {
+        debug!("adjust_local_def");
         let ribs = &self.ribs[ns][rib_index + 1..];
 
         // An invalid forward use of a type parameter from a previous default.
@@ -4111,6 +3790,9 @@
                 span_bug!(span, "unexpected {:?} in bindings", def)
             }
             Def::Local(node_id) => {
+                use ResolutionError::*;
+                let mut res_err = None;
+
                 for rib in ribs {
                     match rib.kind {
                         NormalRibKind | ModuleRibKind(..) | MacroDefinition(..) |
@@ -4146,21 +3828,26 @@
                             // named function item. This is not allowed, so we
                             // report an error.
                             if record_used {
-                                resolve_error(self, span,
-                                    ResolutionError::CannotCaptureDynamicEnvironmentInFnItem);
+                                // We don't immediately trigger a resolve error, because
+                                // we want certain other resolution errors (namely those
+                                // emitted for `ConstantItemRibKind` below) to take
+                                // precedence.
+                                res_err = Some(CannotCaptureDynamicEnvironmentInFnItem);
                             }
-                            return Def::Err;
                         }
                         ConstantItemRibKind => {
                             // Still doesn't deal with upvars
                             if record_used {
-                                resolve_error(self, span,
-                                    ResolutionError::AttemptToUseNonConstantValueInConstant);
+                                resolve_error(self, span, AttemptToUseNonConstantValueInConstant);
                             }
                             return Def::Err;
                         }
                     }
                 }
+                if let Some(res_err) = res_err {
+                     resolve_error(self, span, res_err);
+                     return Def::Err;
+                }
             }
             Def::TyParam(..) | Def::SelfTy(..) => {
                 for rib in ribs {
@@ -4171,17 +3858,38 @@
                             // Nothing to do. Continue.
                         }
                         ItemRibKind => {
-                            // This was an attempt to use a type parameter outside
-                            // its scope.
+                            // This was an attempt to use a type parameter outside its scope.
                             if record_used {
-                                resolve_error(self, span,
-                                    ResolutionError::TypeParametersFromOuterFunction(def));
+                                resolve_error(
+                                    self,
+                                    span,
+                                    ResolutionError::GenericParamsFromOuterFunction(def),
+                                );
                             }
                             return Def::Err;
                         }
                     }
                 }
             }
+            Def::ConstParam(..) => {
+                // A const param is always declared in a signature, which is always followed by
+                // some kind of function rib kind (specifically, ItemRibKind in the case of a
+                // normal function), so we can skip the first rib as it will be guaranteed to
+                // (spuriously) conflict with the const param.
+                for rib in &ribs[1..] {
+                    if let ItemRibKind = rib.kind {
+                        // This was an attempt to use a const parameter outside its scope.
+                        if record_used {
+                            resolve_error(
+                                self,
+                                span,
+                                ResolutionError::GenericParamsFromOuterFunction(def),
+                            );
+                        }
+                        return Def::Err;
+                    }
+                }
+            }
             _ => {}
         }
         def
@@ -5440,7 +5148,6 @@
     (variant_path_string, enum_path_string)
 }
 
-
 /// When an entity with a given name is not available in scope, we search for
 /// entities with that name in all crates. This method allows outputting the
 /// results of this search in a programmer-friendly way
diff --git a/src/librustc_save_analysis/Cargo.toml b/src/librustc_save_analysis/Cargo.toml
index e47f89c..8bb2e72 100644
--- a/src/librustc_save_analysis/Cargo.toml
+++ b/src/librustc_save_analysis/Cargo.toml
@@ -2,6 +2,7 @@
 authors = ["The Rust Project Developers"]
 name = "rustc_save_analysis"
 version = "0.0.0"
+edition = "2018"
 
 [lib]
 name = "rustc_save_analysis"
diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs
index 995df38..1a49056 100644
--- a/src/librustc_save_analysis/dump_visitor.rs
+++ b/src/librustc_save_analysis/dump_visitor.rs
@@ -16,6 +16,7 @@
 use rustc::hir::def::Def as HirDef;
 use rustc::hir::def_id::DefId;
 use rustc::session::config::Input;
+use rustc::span_bug;
 use rustc::ty::{self, TyCtxt};
 use rustc_data_structures::fx::FxHashSet;
 
@@ -32,16 +33,20 @@
 };
 use syntax::ptr::P;
 use syntax::source_map::{Spanned, DUMMY_SP, respan};
+use syntax::walk_list;
 use syntax_pos::*;
 
-use {escape, generated_code, lower_attributes, PathCollector, SaveContext};
-use json_dumper::{Access, DumpOutput, JsonDumper};
-use span_utils::SpanUtils;
-use sig;
+use crate::{escape, generated_code, id_from_def_id, id_from_node_id, lower_attributes,
+            PathCollector, SaveContext};
+use crate::json_dumper::{Access, DumpOutput, JsonDumper};
+use crate::span_utils::SpanUtils;
+use crate::sig;
 
 use rls_data::{CompilationOptions, CratePreludeData, Def, DefKind, GlobalCrateId, Import,
                ImportKind, Ref, RefKind, Relation, RelationKind, SpanData};
 
+use log::{debug, error};
+
 macro_rules! down_cast_data {
     ($id:ident, $kind:ident, $sp:expr) => {
         let $id = if let super::Data::$kind(data) = $id {
@@ -68,7 +73,7 @@
     };
 }
 
-pub struct DumpVisitor<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> {
+pub struct DumpVisitor<'l, 'tcx: 'l, 'll, O: DumpOutput> {
     save_ctxt: SaveContext<'l, 'tcx>,
     tcx: TyCtxt<'l, 'tcx, 'tcx>,
     dumper: &'ll mut JsonDumper<O>,
@@ -245,7 +250,7 @@
                     None => continue,
                 };
                 if !self.span.filter_generated(ident.span) {
-                    let id = ::id_from_node_id(id, &self.save_ctxt);
+                    let id = id_from_node_id(id, &self.save_ctxt);
                     let span = self.span_from_span(ident.span);
 
                     self.dumper.dump_def(
@@ -286,7 +291,7 @@
         debug!("process_method: {}:{}", id, ident);
 
         if let Some(mut method_data) = self.save_ctxt.get_method_data(id, ident, span) {
-            let sig_str = ::make_signature(&sig.decl, &generics);
+            let sig_str = crate::make_signature(&sig.decl, &generics);
             if body.is_some() {
                 self.nest_tables(
                     id,
@@ -339,7 +344,7 @@
                     // Append $id to name to make sure each one is unique.
                     let qualname = format!("{}::{}${}", prefix, name, id);
                     if !self.span.filter_generated(param_ss) {
-                        let id = ::id_from_node_id(param.id, &self.save_ctxt);
+                        let id = id_from_node_id(param.id, &self.save_ctxt);
                         let span = self.span_from_span(param_ss);
 
                         self.dumper.dump_def(
@@ -364,6 +369,7 @@
                         );
                     }
                 }
+                ast::GenericParamKind::Const { .. } => {}
             }
         }
         self.visit_generics(generics);
@@ -433,12 +439,12 @@
                 &access_from!(self.save_ctxt, vis, id),
                 Def {
                     kind: DefKind::Const,
-                    id: ::id_from_node_id(id, &self.save_ctxt),
+                    id: id_from_node_id(id, &self.save_ctxt),
                     span,
                     name: ident.name.to_string(),
                     qualname,
                     value: ty_to_string(&typ),
-                    parent: Some(::id_from_def_id(parent_id)),
+                    parent: Some(id_from_def_id(parent_id)),
                     children: vec![],
                     decl_id: None,
                     docs: self.save_ctxt.docs_for_attrs(attrs),
@@ -495,7 +501,7 @@
                     value,
                     fields
                         .iter()
-                        .map(|f| ::id_from_node_id(f.id, &self.save_ctxt))
+                        .map(|f| id_from_node_id(f.id, &self.save_ctxt))
                         .collect(),
                 )
             }
@@ -508,7 +514,7 @@
                 &access_from!(self.save_ctxt, item),
                 Def {
                     kind,
-                    id: ::id_from_node_id(item.id, &self.save_ctxt),
+                    id: id_from_node_id(item.id, &self.save_ctxt),
                     span,
                     name,
                     qualname: qualname.clone(),
@@ -564,8 +570,8 @@
                     let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
                     if !self.span.filter_generated(name_span) {
                         let span = self.span_from_span(name_span);
-                        let id = ::id_from_node_id(variant.node.data.id(), &self.save_ctxt);
-                        let parent = Some(::id_from_node_id(item.id, &self.save_ctxt));
+                        let id = id_from_node_id(variant.node.data.id(), &self.save_ctxt);
+                        let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
 
                         self.dumper.dump_def(
                             &access,
@@ -602,8 +608,8 @@
                     }
                     if !self.span.filter_generated(name_span) {
                         let span = self.span_from_span(name_span);
-                        let id = ::id_from_node_id(variant.node.data.id(), &self.save_ctxt);
-                        let parent = Some(::id_from_node_id(item.id, &self.save_ctxt));
+                        let id = id_from_node_id(variant.node.data.id(), &self.save_ctxt);
+                        let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
 
                         self.dumper.dump_def(
                             &access,
@@ -686,11 +692,11 @@
             val.push_str(&bounds_to_string(trait_refs));
         }
         if !self.span.filter_generated(item.ident.span) {
-            let id = ::id_from_node_id(item.id, &self.save_ctxt);
+            let id = id_from_node_id(item.id, &self.save_ctxt);
             let span = self.span_from_span(item.ident.span);
             let children = methods
                 .iter()
-                .map(|i| ::id_from_node_id(i.id, &self.save_ctxt))
+                .map(|i| id_from_node_id(i.id, &self.save_ctxt))
                 .collect();
             self.dumper.dump_def(
                 &access_from!(self.save_ctxt, item),
@@ -726,14 +732,14 @@
                     self.dumper.dump_ref(Ref {
                         kind: RefKind::Type,
                         span: span.clone(),
-                        ref_id: ::id_from_def_id(id),
+                        ref_id: id_from_def_id(id),
                     });
 
                     self.dumper.dump_relation(Relation {
                         kind: RelationKind::SuperTrait,
                         span,
-                        from: ::id_from_def_id(id),
-                        to: ::id_from_node_id(item.id, &self.save_ctxt),
+                        from: id_from_def_id(id),
+                        to: id_from_node_id(item.id, &self.save_ctxt),
                     });
                 }
             }
@@ -873,7 +879,7 @@
                             self.dumper.dump_ref(Ref {
                                 kind: RefKind::Variable,
                                 span,
-                                ref_id: ::id_from_def_id(variant.fields[index].did),
+                                ref_id: id_from_def_id(variant.fields[index].did),
                             });
                         }
                     }
@@ -912,7 +918,7 @@
 
                     if !self.span.filter_generated(ident.span) {
                         let qualname = format!("{}${}", ident.to_string(), id);
-                        let id = ::id_from_node_id(id, &self.save_ctxt);
+                        let id = id_from_node_id(id, &self.save_ctxt);
                         let span = self.span_from_span(ident.span);
 
                         self.dumper.dump_def(
@@ -988,7 +994,7 @@
             // Rust uses the id of the pattern for var lookups, so we'll use it too.
             if !self.span.filter_generated(ident.span) {
                 let qualname = format!("{}${}", ident.to_string(), id);
-                let id = ::id_from_node_id(id, &self.save_ctxt);
+                let id = id_from_node_id(id, &self.save_ctxt);
                 let span = self.span_from_span(ident.span);
 
                 self.dumper.dump_def(
@@ -1091,7 +1097,7 @@
 
                 if !self.span.filter_generated(trait_item.ident.span) {
                     let span = self.span_from_span(trait_item.ident.span);
-                    let id = ::id_from_node_id(trait_item.id, &self.save_ctxt);
+                    let id = id_from_node_id(trait_item.id, &self.save_ctxt);
 
                     self.dumper.dump_def(
                         &Access {
@@ -1105,7 +1111,7 @@
                             name,
                             qualname,
                             value: self.span.snippet(trait_item.span),
-                            parent: Some(::id_from_def_id(trait_id)),
+                            parent: Some(id_from_def_id(trait_id)),
                             children: vec![],
                             decl_id: None,
                             docs: self.save_ctxt.docs_for_attrs(&trait_item.attrs),
@@ -1196,7 +1202,7 @@
         // The parent def id of a given use tree is always the enclosing item.
         let parent = self.save_ctxt.tcx.hir().opt_local_def_id(id)
             .and_then(|id| self.save_ctxt.tcx.parent_def_id(id))
-            .map(::id_from_def_id);
+            .map(id_from_def_id);
 
         match use_tree.kind {
             ast::UseTreeKind::Simple(alias, ..) => {
@@ -1212,7 +1218,7 @@
 
                 let sub_span = path.segments.last().unwrap().ident.span;
                 if !self.span.filter_generated(sub_span) {
-                    let ref_id = self.lookup_def_id(id).map(|id| ::id_from_def_id(id));
+                    let ref_id = self.lookup_def_id(id).map(|id| id_from_def_id(id));
                     let alias_span = alias.map(|i| self.span_from_span(i.span));
                     let span = self.span_from_span(sub_span);
                     self.dumper.import(&access, Import {
@@ -1298,10 +1304,10 @@
 
         let cm = self.tcx.sess.source_map();
         let filename = cm.span_to_filename(span);
-        let data_id = ::id_from_node_id(id, &self.save_ctxt);
+        let data_id = id_from_node_id(id, &self.save_ctxt);
         let children = m.items
             .iter()
-            .map(|i| ::id_from_node_id(i.id, &self.save_ctxt))
+            .map(|i| id_from_node_id(i.id, &self.save_ctxt))
             .collect();
         let span = self.span_from_span(span);
 
@@ -1345,7 +1351,7 @@
                     let span = self.span_from_span(name_span);
                     let parent = self.save_ctxt.tcx.hir().opt_local_def_id(item.id)
                         .and_then(|id| self.save_ctxt.tcx.parent_def_id(id))
-                        .map(::id_from_def_id);
+                        .map(id_from_def_id);
                     self.dumper.import(
                         &Access {
                             public: false,
@@ -1387,7 +1393,7 @@
                 let value = ty_to_string(&ty);
                 if !self.span.filter_generated(item.ident.span) {
                     let span = self.span_from_span(item.ident.span);
-                    let id = ::id_from_node_id(item.id, &self.save_ctxt);
+                    let id = id_from_node_id(item.id, &self.save_ctxt);
 
                     self.dumper.dump_def(
                         &access_from!(self.save_ctxt, item),
@@ -1417,7 +1423,7 @@
                 let value = String::new();
                 if !self.span.filter_generated(item.ident.span) {
                     let span = self.span_from_span(item.ident.span);
-                    let id = ::id_from_node_id(item.id, &self.save_ctxt);
+                    let id = id_from_node_id(item.id, &self.save_ctxt);
 
                     self.dumper.dump_def(
                         &access_from!(self.save_ctxt, item),
@@ -1447,9 +1453,16 @@
 
     fn visit_generics(&mut self, generics: &'l ast::Generics) {
         for param in &generics.params {
-            if let ast::GenericParamKind::Type { ref default, .. } = param.kind {
-                self.process_bounds(&param.bounds);
-                if let Some(ref ty) = default {
+            match param.kind {
+                ast::GenericParamKind::Lifetime { .. } => {}
+                ast::GenericParamKind::Type { ref default, .. } => {
+                    self.process_bounds(&param.bounds);
+                    if let Some(ref ty) = default {
+                        self.visit_ty(&ty);
+                    }
+                }
+                ast::GenericParamKind::Const { ref ty } => {
+                    self.process_bounds(&param.bounds);
                     self.visit_ty(&ty);
                 }
             }
@@ -1476,7 +1489,7 @@
                     self.dumper.dump_ref(Ref {
                         kind: RefKind::Type,
                         span,
-                        ref_id: ::id_from_def_id(id),
+                        ref_id: id_from_def_id(id),
                     });
                 }
 
diff --git a/src/librustc_save_analysis/json_dumper.rs b/src/librustc_save_analysis/json_dumper.rs
index 3627c55..1840cf6 100644
--- a/src/librustc_save_analysis/json_dumper.rs
+++ b/src/librustc_save_analysis/json_dumper.rs
@@ -7,6 +7,8 @@
                MacroRef, Ref, RefKind, Relation};
 use rls_span::{Column, Row};
 
+use log::error;
+
 #[derive(Debug)]
 pub struct Access {
     pub reachable: bool,
@@ -23,7 +25,7 @@
     fn dump(&mut self, result: &Analysis);
 }
 
-pub struct WriteOutput<'b, W: Write + 'b> {
+pub struct WriteOutput<'b, W: Write> {
     output: &'b mut W,
 }
 
diff --git a/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs
index 73eb5de..c4a2ebe 100644
--- a/src/librustc_save_analysis/lib.rs
+++ b/src/librustc_save_analysis/lib.rs
@@ -1,29 +1,10 @@
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 #![feature(custom_attribute)]
-#![feature(nll)]
+#![deny(rust_2018_idioms)]
 #![allow(unused_attributes)]
 
 #![recursion_limit="256"]
 
-#[macro_use]
-extern crate rustc;
-
-#[macro_use]
-extern crate log;
-extern crate rustc_data_structures;
-extern crate rustc_codegen_utils;
-extern crate rustc_serialize;
-extern crate rustc_target;
-extern crate rustc_typeck;
-#[macro_use]
-extern crate syntax;
-extern crate syntax_pos;
-
-extern crate rls_data;
-extern crate rls_span;
-
 
 mod json_dumper;
 mod dump_visitor;
@@ -39,6 +20,7 @@
 use rustc::middle::cstore::ExternCrate;
 use rustc::session::config::{CrateType, Input, OutputType};
 use rustc::ty::{self, TyCtxt};
+use rustc::{bug, span_bug};
 use rustc_typeck::hir_ty_to_ty;
 use rustc_codegen_utils::link::{filename_for_metadata, out_filename};
 use rustc_data_structures::sync::Lrc;
@@ -66,6 +48,8 @@
                RelationKind, SpanData, Impl, ImplKind};
 use rls_data::config::Config;
 
+use log::{debug, error, info};
+
 
 pub struct SaveContext<'l, 'tcx: 'l> {
     tcx: TyCtxt<'l, 'tcx, 'tcx>,
@@ -172,7 +156,7 @@
             ast::ForeignItemKind::Static(ref ty, _) => {
                 filter!(self.span_utils, item.ident.span);
 
-                let id = ::id_from_node_id(item.id, self);
+                let id = id_from_node_id(item.id, self);
                 let span = self.span_from_span(item.ident.span);
 
                 Some(Data::DefData(Def {
@@ -762,6 +746,13 @@
                     ref_id: id_from_def_id(def_id),
                 })
             }
+            HirDef::ConstParam(def_id) => {
+                Some(Ref {
+                    kind: RefKind::Variable,
+                    span,
+                    ref_id: id_from_def_id(def_id),
+                })
+            }
             HirDef::StructCtor(def_id, _) => {
                 // This is a reference to a tuple struct where the def_id points
                 // to an invisible constructor function. That is not a very useful
@@ -1029,7 +1020,7 @@
         }
     }
 
-    fn output_file(&self, ctx: &SaveContext) -> File {
+    fn output_file(&self, ctx: &SaveContext<'_, '_>) -> File {
         let sess = &ctx.tcx.sess;
         let file_name = match ctx.config.output_file {
             Some(ref s) => PathBuf::from(s),
@@ -1180,7 +1171,7 @@
     }
 }
 
-fn id_from_node_id(id: NodeId, scx: &SaveContext) -> rls_data::Id {
+fn id_from_node_id(id: NodeId, scx: &SaveContext<'_, '_>) -> rls_data::Id {
     let def_id = scx.tcx.hir().opt_local_def_id(id);
     def_id.map(|id| id_from_def_id(id)).unwrap_or_else(|| {
         // Create a *fake* `DefId` out of a `NodeId` by subtracting the `NodeId`
@@ -1200,7 +1191,7 @@
     }
 }
 
-fn lower_attributes(attrs: Vec<Attribute>, scx: &SaveContext) -> Vec<rls_data::Attribute> {
+fn lower_attributes(attrs: Vec<Attribute>, scx: &SaveContext<'_, '_>) -> Vec<rls_data::Attribute> {
     attrs.into_iter()
     // Only retain real attributes. Doc comments are lowered separately.
     .filter(|attr| attr.path != "doc")
diff --git a/src/librustc_save_analysis/sig.rs b/src/librustc_save_analysis/sig.rs
index 7d4c0d0..50a335b 100644
--- a/src/librustc_save_analysis/sig.rs
+++ b/src/librustc_save_analysis/sig.rs
@@ -25,7 +25,7 @@
 //
 // FIXME where clauses need implementing, defs/refs in generics are mostly missing.
 
-use {id_from_def_id, id_from_node_id, SaveContext};
+use crate::{id_from_def_id, id_from_node_id, SaveContext};
 
 use rls_data::{SigElement, Signature};
 
@@ -34,14 +34,17 @@
 use syntax::print::pprust;
 
 
-pub fn item_signature(item: &ast::Item, scx: &SaveContext) -> Option<Signature> {
+pub fn item_signature(item: &ast::Item, scx: &SaveContext<'_, '_>) -> Option<Signature> {
     if !scx.config.signatures {
         return None;
     }
     item.make(0, None, scx).ok()
 }
 
-pub fn foreign_item_signature(item: &ast::ForeignItem, scx: &SaveContext) -> Option<Signature> {
+pub fn foreign_item_signature(
+    item: &ast::ForeignItem,
+    scx: &SaveContext<'_, '_>
+) -> Option<Signature> {
     if !scx.config.signatures {
         return None;
     }
@@ -50,7 +53,7 @@
 
 /// Signature for a struct or tuple field declaration.
 /// Does not include a trailing comma.
-pub fn field_signature(field: &ast::StructField, scx: &SaveContext) -> Option<Signature> {
+pub fn field_signature(field: &ast::StructField, scx: &SaveContext<'_, '_>) -> Option<Signature> {
     if !scx.config.signatures {
         return None;
     }
@@ -58,7 +61,7 @@
 }
 
 /// Does not include a trailing comma.
-pub fn variant_signature(variant: &ast::Variant, scx: &SaveContext) -> Option<Signature> {
+pub fn variant_signature(variant: &ast::Variant, scx: &SaveContext<'_, '_>) -> Option<Signature> {
     if !scx.config.signatures {
         return None;
     }
@@ -70,7 +73,7 @@
     ident: ast::Ident,
     generics: &ast::Generics,
     m: &ast::MethodSig,
-    scx: &SaveContext,
+    scx: &SaveContext<'_, '_>,
 ) -> Option<Signature> {
     if !scx.config.signatures {
         return None;
@@ -83,7 +86,7 @@
     ident: ast::Name,
     ty: &ast::Ty,
     default: Option<&ast::Expr>,
-    scx: &SaveContext,
+    scx: &SaveContext<'_, '_>,
 ) -> Option<Signature> {
     if !scx.config.signatures {
         return None;
@@ -96,7 +99,7 @@
     ident: ast::Ident,
     bounds: Option<&ast::GenericBounds>,
     default: Option<&ast::Ty>,
-    scx: &SaveContext,
+    scx: &SaveContext<'_, '_>,
 ) -> Option<Signature> {
     if !scx.config.signatures {
         return None;
@@ -104,10 +107,10 @@
     make_assoc_type_signature(id, ident, bounds, default, scx).ok()
 }
 
-type Result = ::std::result::Result<Signature, &'static str>;
+type Result = std::result::Result<Signature, &'static str>;
 
 trait Sig {
-    fn make(&self, offset: usize, id: Option<NodeId>, scx: &SaveContext) -> Result;
+    fn make(&self, offset: usize, id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result;
 }
 
 fn extend_sig(
@@ -155,7 +158,7 @@
 }
 
 impl Sig for ast::Ty {
-    fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext) -> Result {
+    fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result {
         let id = Some(self.id);
         match self.node {
             ast::TyKind::Slice(ref ty) => {
@@ -227,7 +230,7 @@
                 if f.unsafety == ast::Unsafety::Unsafe {
                     text.push_str("unsafe ");
                 }
-                if f.abi != ::rustc_target::spec::abi::Abi::Rust {
+                if f.abi != rustc_target::spec::abi::Abi::Rust {
                     text.push_str("extern");
                     text.push_str(&f.abi.to_string());
                     text.push(' ');
@@ -317,7 +320,7 @@
 }
 
 impl Sig for ast::Item {
-    fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext) -> Result {
+    fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result {
         let id = Some(self.id);
 
         match self.node {
@@ -381,7 +384,7 @@
                 if header.unsafety == ast::Unsafety::Unsafe {
                     text.push_str("unsafe ");
                 }
-                if header.abi != ::rustc_target::spec::abi::Abi::Rust {
+                if header.abi != rustc_target::spec::abi::Abi::Rust {
                     text.push_str("extern");
                     text.push_str(&header.abi.to_string());
                     text.push(' ');
@@ -571,7 +574,7 @@
 }
 
 impl Sig for ast::Path {
-    fn make(&self, offset: usize, id: Option<NodeId>, scx: &SaveContext) -> Result {
+    fn make(&self, offset: usize, id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result {
         let def = scx.get_path_def(id.ok_or("Missing id for Path")?);
 
         let (name, start, end) = match def {
@@ -613,7 +616,7 @@
 
 // This does not cover the where clause, which must be processed separately.
 impl Sig for ast::Generics {
-    fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext) -> Result {
+    fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result {
         if self.params.is_empty() {
             return Ok(text_sig(String::new()));
         }
@@ -622,12 +625,20 @@
 
         let mut defs = Vec::with_capacity(self.params.len());
         for param in &self.params {
-            let mut param_text = param.ident.to_string();
+            let mut param_text = String::new();
+            if let ast::GenericParamKind::Const { .. } = param.kind {
+                param_text.push_str("const ");
+            }
+            param_text.push_str(&param.ident.as_str());
             defs.push(SigElement {
                 id: id_from_node_id(param.id, scx),
                 start: offset + text.len(),
-                end: offset + text.len() + param_text.len(),
+                end: offset + text.len() + param_text.as_str().len(),
             });
+            if let ast::GenericParamKind::Const { ref ty } = param.kind {
+                param_text.push_str(": ");
+                param_text.push_str(&pprust::ty_to_string(&ty));
+            }
             if !param.bounds.is_empty() {
                 param_text.push_str(": ");
                 match param.kind {
@@ -646,6 +657,9 @@
                         param_text.push_str(&pprust::bounds_to_string(&param.bounds));
                         // FIXME descend properly into bounds.
                     }
+                    ast::GenericParamKind::Const { .. } => {
+                        // Const generics cannot contain bounds.
+                    }
                 }
             }
             text.push_str(&param_text);
@@ -662,7 +676,7 @@
 }
 
 impl Sig for ast::StructField {
-    fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext) -> Result {
+    fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result {
         let mut text = String::new();
         let mut defs = None;
         if let Some(ident) = self.ident {
@@ -685,7 +699,7 @@
 
 
 impl Sig for ast::Variant_ {
-    fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext) -> Result {
+    fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result {
         let mut text = self.ident.to_string();
         match self.data {
             ast::VariantData::Struct(ref fields, id) => {
@@ -743,7 +757,7 @@
 }
 
 impl Sig for ast::ForeignItem {
-    fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext) -> Result {
+    fn make(&self, offset: usize, _parent_id: Option<NodeId>, scx: &SaveContext<'_, '_>) -> Result {
         let id = Some(self.id);
         match self.node {
             ast::ForeignItemKind::Fn(ref decl, ref generics) => {
@@ -827,7 +841,7 @@
     generics: &ast::Generics,
     id: NodeId,
     name: ast::Ident,
-    scx: &SaveContext,
+    scx: &SaveContext<'_, '_>,
 ) -> Result {
     let name = name.to_string();
     let def = SigElement {
@@ -848,7 +862,7 @@
     ident: ast::Ident,
     bounds: Option<&ast::GenericBounds>,
     default: Option<&ast::Ty>,
-    scx: &SaveContext,
+    scx: &SaveContext<'_, '_>,
 ) -> Result {
     let mut text = "type ".to_owned();
     let name = ident.to_string();
@@ -882,7 +896,7 @@
     ident: ast::Name,
     ty: &ast::Ty,
     default: Option<&ast::Expr>,
-    scx: &SaveContext,
+    scx: &SaveContext<'_, '_>,
 ) -> Result {
     let mut text = "const ".to_owned();
     let name = ident.to_string();
@@ -915,7 +929,7 @@
     ident: ast::Ident,
     generics: &ast::Generics,
     m: &ast::MethodSig,
-    scx: &SaveContext,
+    scx: &SaveContext<'_, '_>,
 ) -> Result {
     // FIXME code dup with function signature
     let mut text = String::new();
@@ -928,7 +942,7 @@
     if m.header.unsafety == ast::Unsafety::Unsafe {
         text.push_str("unsafe ");
     }
-    if m.header.abi != ::rustc_target::spec::abi::Abi::Rust {
+    if m.header.abi != rustc_target::spec::abi::Abi::Rust {
         text.push_str("extern");
         text.push_str(&m.header.abi.to_string());
         text.push(' ');
diff --git a/src/librustc_save_analysis/span_utils.rs b/src/librustc_save_analysis/span_utils.rs
index 88c6012..e2c93b6 100644
--- a/src/librustc_save_analysis/span_utils.rs
+++ b/src/librustc_save_analysis/span_utils.rs
@@ -1,6 +1,6 @@
 use rustc::session::Session;
 
-use generated_code;
+use crate::generated_code;
 
 use std::cell::Cell;
 
diff --git a/src/librustc_target/Cargo.toml b/src/librustc_target/Cargo.toml
index dfdd7f0..ecea15a 100644
--- a/src/librustc_target/Cargo.toml
+++ b/src/librustc_target/Cargo.toml
@@ -2,6 +2,7 @@
 authors = ["The Rust Project Developers"]
 name = "rustc_target"
 version = "0.0.0"
+edition = "2018"
 
 [lib]
 name = "rustc_target"
diff --git a/src/librustc_target/abi/call/aarch64.rs b/src/librustc_target/abi/call/aarch64.rs
index 9f9bba1..f50ec6c 100644
--- a/src/librustc_target/abi/call/aarch64.rs
+++ b/src/librustc_target/abi/call/aarch64.rs
@@ -1,5 +1,5 @@
-use abi::call::{FnType, ArgType, Reg, RegKind, Uniform};
-use abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
+use crate::abi::call::{FnType, ArgType, Reg, RegKind, Uniform};
+use crate::abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
 
 fn is_homogeneous_aggregate<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>)
                                      -> Option<Uniform>
diff --git a/src/librustc_target/abi/call/amdgpu.rs b/src/librustc_target/abi/call/amdgpu.rs
index ea9d417..6bfd1f4 100644
--- a/src/librustc_target/abi/call/amdgpu.rs
+++ b/src/librustc_target/abi/call/amdgpu.rs
@@ -1,5 +1,5 @@
-use abi::call::{ArgType, FnType, };
-use abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
+use crate::abi::call::{ArgType, FnType, };
+use crate::abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
 
 fn classify_ret_ty<'a, Ty, C>(_cx: &C, ret: &mut ArgType<'a, Ty>)
   where Ty: TyLayoutMethods<'a, C> + Copy,
diff --git a/src/librustc_target/abi/call/arm.rs b/src/librustc_target/abi/call/arm.rs
index 228dd36..52d7f3a 100644
--- a/src/librustc_target/abi/call/arm.rs
+++ b/src/librustc_target/abi/call/arm.rs
@@ -1,6 +1,6 @@
-use abi::call::{Conv, FnType, ArgType, Reg, RegKind, Uniform};
-use abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
-use spec::HasTargetSpec;
+use crate::abi::call::{Conv, FnType, ArgType, Reg, RegKind, Uniform};
+use crate::abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
+use crate::spec::HasTargetSpec;
 
 fn is_homogeneous_aggregate<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>)
                                      -> Option<Uniform>
diff --git a/src/librustc_target/abi/call/asmjs.rs b/src/librustc_target/abi/call/asmjs.rs
index 8544450..92c8637 100644
--- a/src/librustc_target/abi/call/asmjs.rs
+++ b/src/librustc_target/abi/call/asmjs.rs
@@ -1,5 +1,5 @@
-use abi::call::{FnType, ArgType, Uniform};
-use abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
+use crate::abi::call::{FnType, ArgType, Uniform};
+use crate::abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
 
 // Data layout: e-p:32:32-i64:64-v128:32:128-n32-S128
 
@@ -26,7 +26,7 @@
     }
 }
 
-fn classify_arg_ty<Ty>(arg: &mut ArgType<Ty>) {
+fn classify_arg_ty<Ty>(arg: &mut ArgType<'_, Ty>) {
     if arg.layout.is_aggregate() {
         arg.make_indirect_byval();
     }
diff --git a/src/librustc_target/abi/call/hexagon.rs b/src/librustc_target/abi/call/hexagon.rs
index d538a80..db8c915 100644
--- a/src/librustc_target/abi/call/hexagon.rs
+++ b/src/librustc_target/abi/call/hexagon.rs
@@ -1,8 +1,8 @@
 #![allow(non_upper_case_globals)]
 
-use abi::call::{FnType, ArgType};
+use crate::abi::call::{FnType, ArgType};
 
-fn classify_ret_ty<Ty>(ret: &mut ArgType<Ty>) {
+fn classify_ret_ty<Ty>(ret: &mut ArgType<'_, Ty>) {
     if ret.layout.is_aggregate() && ret.layout.size.bits() > 64 {
         ret.make_indirect();
     } else {
@@ -10,7 +10,7 @@
     }
 }
 
-fn classify_arg_ty<Ty>(arg: &mut ArgType<Ty>) {
+fn classify_arg_ty<Ty>(arg: &mut ArgType<'_, Ty>) {
     if arg.layout.is_aggregate() && arg.layout.size.bits() > 64 {
         arg.make_indirect();
     } else {
@@ -18,7 +18,7 @@
     }
 }
 
-pub fn compute_abi_info<Ty>(fty: &mut FnType<Ty>) {
+pub fn compute_abi_info<Ty>(fty: &mut FnType<'_,Ty>) {
     if !fty.ret.is_ignore() {
         classify_ret_ty(&mut fty.ret);
     }
diff --git a/src/librustc_target/abi/call/mips.rs b/src/librustc_target/abi/call/mips.rs
index 2335bfb..d496abf 100644
--- a/src/librustc_target/abi/call/mips.rs
+++ b/src/librustc_target/abi/call/mips.rs
@@ -1,7 +1,7 @@
-use abi::call::{ArgType, FnType, Reg, Uniform};
-use abi::{HasDataLayout, LayoutOf, Size, TyLayoutMethods};
+use crate::abi::call::{ArgType, FnType, Reg, Uniform};
+use crate::abi::{HasDataLayout, LayoutOf, Size, TyLayoutMethods};
 
-fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType<Ty>, offset: &mut Size)
+fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType<'_, Ty>, offset: &mut Size)
     where Ty: TyLayoutMethods<'a, C>, C: LayoutOf<Ty = Ty> + HasDataLayout
 {
     if !ret.layout.is_aggregate() {
@@ -12,7 +12,7 @@
     }
 }
 
-fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType<Ty>, offset: &mut Size)
+fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType<'_, Ty>, offset: &mut Size)
     where Ty: TyLayoutMethods<'a, C>, C: LayoutOf<Ty = Ty> + HasDataLayout
 {
     let dl = cx.data_layout();
@@ -34,7 +34,7 @@
     *offset = offset.align_to(align) + size.align_to(align);
 }
 
-pub fn compute_abi_info<'a, Ty, C>(cx: &C, fty: &mut FnType<Ty>)
+pub fn compute_abi_info<'a, Ty, C>(cx: &C, fty: &mut FnType<'_, Ty>)
     where Ty: TyLayoutMethods<'a, C>, C: LayoutOf<Ty = Ty> + HasDataLayout
 {
     let mut offset = Size::ZERO;
diff --git a/src/librustc_target/abi/call/mips64.rs b/src/librustc_target/abi/call/mips64.rs
index 6f3e649..5ba05c6 100644
--- a/src/librustc_target/abi/call/mips64.rs
+++ b/src/librustc_target/abi/call/mips64.rs
@@ -1,7 +1,7 @@
-use abi::call::{ArgAttribute, ArgType, CastTarget, FnType, PassMode, Reg, RegKind, Uniform};
-use abi::{self, HasDataLayout, LayoutOf, Size, TyLayout, TyLayoutMethods};
+use crate::abi::call::{ArgAttribute, ArgType, CastTarget, FnType, PassMode, Reg, RegKind, Uniform};
+use crate::abi::{self, HasDataLayout, LayoutOf, Size, TyLayout, TyLayoutMethods};
 
-fn extend_integer_width_mips<Ty>(arg: &mut ArgType<Ty>, bits: u64) {
+fn extend_integer_width_mips<Ty>(arg: &mut ArgType<'_, Ty>, bits: u64) {
     // Always sign extend u32 values on 64-bit mips
     if let abi::Abi::Scalar(ref scalar) = arg.layout.abi {
         if let abi::Int(i, signed) = scalar.value {
diff --git a/src/librustc_target/abi/call/mod.rs b/src/librustc_target/abi/call/mod.rs
index 0d50439..839c9a8 100644
--- a/src/librustc_target/abi/call/mod.rs
+++ b/src/librustc_target/abi/call/mod.rs
@@ -1,6 +1,6 @@
-use abi::{self, Abi, Align, FieldPlacement, Size};
-use abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
-use spec::HasTargetSpec;
+use crate::abi::{self, Abi, Align, FieldPlacement, Size};
+use crate::abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
+use crate::spec::{self, HasTargetSpec};
 
 mod aarch64;
 mod amdgpu;
@@ -42,13 +42,13 @@
 
 // Hack to disable non_upper_case_globals only for the bitflags! and not for the rest
 // of this module
-pub use self::attr_impl::ArgAttribute;
+pub use attr_impl::ArgAttribute;
 
 #[allow(non_upper_case_globals)]
 #[allow(unused)]
 mod attr_impl {
     // The subset of llvm::Attribute needed for arguments, packed into a bitfield.
-    bitflags! {
+    bitflags::bitflags! {
         #[derive(Default)]
         pub struct ArgAttribute: u16 {
             const ByVal     = 1 << 0;
@@ -526,22 +526,22 @@
 }
 
 impl<'a, Ty> FnType<'a, Ty> {
-    pub fn adjust_for_cabi<C>(&mut self, cx: &C, abi: ::spec::abi::Abi) -> Result<(), String>
+    pub fn adjust_for_cabi<C>(&mut self, cx: &C, abi: spec::abi::Abi) -> Result<(), String>
         where Ty: TyLayoutMethods<'a, C> + Copy,
               C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout + HasTargetSpec
     {
         match &cx.target_spec().arch[..] {
             "x86" => {
-                let flavor = if abi == ::spec::abi::Abi::Fastcall {
+                let flavor = if abi == spec::abi::Abi::Fastcall {
                     x86::Flavor::Fastcall
                 } else {
                     x86::Flavor::General
                 };
                 x86::compute_abi_info(cx, self, flavor);
             },
-            "x86_64" => if abi == ::spec::abi::Abi::SysV64 {
+            "x86_64" => if abi == spec::abi::Abi::SysV64 {
                 x86_64::compute_abi_info(cx, self);
-            } else if abi == ::spec::abi::Abi::Win64 || cx.target_spec().options.is_like_windows {
+            } else if abi == spec::abi::Abi::Win64 || cx.target_spec().options.is_like_windows {
                 x86_win64::compute_abi_info(self);
             } else {
                 x86_64::compute_abi_info(cx, self);
diff --git a/src/librustc_target/abi/call/msp430.rs b/src/librustc_target/abi/call/msp430.rs
index d8ba37d..7ae1116 100644
--- a/src/librustc_target/abi/call/msp430.rs
+++ b/src/librustc_target/abi/call/msp430.rs
@@ -1,7 +1,7 @@
 // Reference: MSP430 Embedded Application Binary Interface
 // http://www.ti.com/lit/an/slaa534/slaa534.pdf
 
-use abi::call::{ArgType, FnType};
+use crate::abi::call::{ArgType, FnType};
 
 // 3.5 Structures or Unions Passed and Returned by Reference
 //
@@ -9,7 +9,7 @@
 // returned by reference. To pass a structure or union by reference, the caller
 // places its address in the appropriate location: either in a register or on
 // the stack, according to its position in the argument list. (..)"
-fn classify_ret_ty<Ty>(ret: &mut ArgType<Ty>) {
+fn classify_ret_ty<Ty>(ret: &mut ArgType<'_, Ty>) {
     if ret.layout.is_aggregate() && ret.layout.size.bits() > 32 {
         ret.make_indirect();
     } else {
@@ -17,7 +17,7 @@
     }
 }
 
-fn classify_arg_ty<Ty>(arg: &mut ArgType<Ty>) {
+fn classify_arg_ty<Ty>(arg: &mut ArgType<'_, Ty>) {
     if arg.layout.is_aggregate() && arg.layout.size.bits() > 32 {
         arg.make_indirect();
     } else {
@@ -25,7 +25,7 @@
     }
 }
 
-pub fn compute_abi_info<Ty>(fty: &mut FnType<Ty>) {
+pub fn compute_abi_info<Ty>(fty: &mut FnType<'_, Ty>) {
     if !fty.ret.is_ignore() {
         classify_ret_ty(&mut fty.ret);
     }
diff --git a/src/librustc_target/abi/call/nvptx.rs b/src/librustc_target/abi/call/nvptx.rs
index 4cf0f11..4722249 100644
--- a/src/librustc_target/abi/call/nvptx.rs
+++ b/src/librustc_target/abi/call/nvptx.rs
@@ -1,9 +1,9 @@
 // Reference: PTX Writer's Guide to Interoperability
 // http://docs.nvidia.com/cuda/ptx-writers-guide-to-interoperability
 
-use abi::call::{ArgType, FnType};
+use crate::abi::call::{ArgType, FnType};
 
-fn classify_ret_ty<Ty>(ret: &mut ArgType<Ty>) {
+fn classify_ret_ty<Ty>(ret: &mut ArgType<'_, Ty>) {
     if ret.layout.is_aggregate() && ret.layout.size.bits() > 32 {
         ret.make_indirect();
     } else {
@@ -11,7 +11,7 @@
     }
 }
 
-fn classify_arg_ty<Ty>(arg: &mut ArgType<Ty>) {
+fn classify_arg_ty<Ty>(arg: &mut ArgType<'_, Ty>) {
     if arg.layout.is_aggregate() && arg.layout.size.bits() > 32 {
         arg.make_indirect();
     } else {
@@ -19,7 +19,7 @@
     }
 }
 
-pub fn compute_abi_info<Ty>(fty: &mut FnType<Ty>) {
+pub fn compute_abi_info<Ty>(fty: &mut FnType<'_, Ty>) {
     if !fty.ret.is_ignore() {
         classify_ret_ty(&mut fty.ret);
     }
diff --git a/src/librustc_target/abi/call/nvptx64.rs b/src/librustc_target/abi/call/nvptx64.rs
index 8ccc775..51c00ae 100644
--- a/src/librustc_target/abi/call/nvptx64.rs
+++ b/src/librustc_target/abi/call/nvptx64.rs
@@ -1,9 +1,9 @@
 // Reference: PTX Writer's Guide to Interoperability
 // http://docs.nvidia.com/cuda/ptx-writers-guide-to-interoperability
 
-use abi::call::{ArgType, FnType};
+use crate::abi::call::{ArgType, FnType};
 
-fn classify_ret_ty<Ty>(ret: &mut ArgType<Ty>) {
+fn classify_ret_ty<Ty>(ret: &mut ArgType<'_, Ty>) {
     if ret.layout.is_aggregate() && ret.layout.size.bits() > 64 {
         ret.make_indirect();
     } else {
@@ -11,7 +11,7 @@
     }
 }
 
-fn classify_arg_ty<Ty>(arg: &mut ArgType<Ty>) {
+fn classify_arg_ty<Ty>(arg: &mut ArgType<'_, Ty>) {
     if arg.layout.is_aggregate() && arg.layout.size.bits() > 64 {
         arg.make_indirect();
     } else {
@@ -19,7 +19,7 @@
     }
 }
 
-pub fn compute_abi_info<Ty>(fty: &mut FnType<Ty>) {
+pub fn compute_abi_info<Ty>(fty: &mut FnType<'_, Ty>) {
     if !fty.ret.is_ignore() {
         classify_ret_ty(&mut fty.ret);
     }
diff --git a/src/librustc_target/abi/call/powerpc.rs b/src/librustc_target/abi/call/powerpc.rs
index 2335bfb..d496abf 100644
--- a/src/librustc_target/abi/call/powerpc.rs
+++ b/src/librustc_target/abi/call/powerpc.rs
@@ -1,7 +1,7 @@
-use abi::call::{ArgType, FnType, Reg, Uniform};
-use abi::{HasDataLayout, LayoutOf, Size, TyLayoutMethods};
+use crate::abi::call::{ArgType, FnType, Reg, Uniform};
+use crate::abi::{HasDataLayout, LayoutOf, Size, TyLayoutMethods};
 
-fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType<Ty>, offset: &mut Size)
+fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType<'_, Ty>, offset: &mut Size)
     where Ty: TyLayoutMethods<'a, C>, C: LayoutOf<Ty = Ty> + HasDataLayout
 {
     if !ret.layout.is_aggregate() {
@@ -12,7 +12,7 @@
     }
 }
 
-fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType<Ty>, offset: &mut Size)
+fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType<'_, Ty>, offset: &mut Size)
     where Ty: TyLayoutMethods<'a, C>, C: LayoutOf<Ty = Ty> + HasDataLayout
 {
     let dl = cx.data_layout();
@@ -34,7 +34,7 @@
     *offset = offset.align_to(align) + size.align_to(align);
 }
 
-pub fn compute_abi_info<'a, Ty, C>(cx: &C, fty: &mut FnType<Ty>)
+pub fn compute_abi_info<'a, Ty, C>(cx: &C, fty: &mut FnType<'_, Ty>)
     where Ty: TyLayoutMethods<'a, C>, C: LayoutOf<Ty = Ty> + HasDataLayout
 {
     let mut offset = Size::ZERO;
diff --git a/src/librustc_target/abi/call/powerpc64.rs b/src/librustc_target/abi/call/powerpc64.rs
index 305a2d4..a968310 100644
--- a/src/librustc_target/abi/call/powerpc64.rs
+++ b/src/librustc_target/abi/call/powerpc64.rs
@@ -2,16 +2,16 @@
 // Alignment of 128 bit types is not currently handled, this will
 // need to be fixed when PowerPC vector support is added.
 
-use abi::call::{FnType, ArgType, Reg, RegKind, Uniform};
-use abi::{Endian, HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
-use spec::HasTargetSpec;
+use crate::abi::call::{FnType, ArgType, Reg, RegKind, Uniform};
+use crate::abi::{Endian, HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
+use crate::spec::HasTargetSpec;
 
 #[derive(Debug, Clone, Copy, PartialEq)]
 enum ABI {
     ELFv1, // original ABI used for powerpc64 (big-endian)
     ELFv2, // newer ABI used for powerpc64le and musl (both endians)
 }
-use self::ABI::*;
+use ABI::*;
 
 fn is_homogeneous_aggregate<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>, abi: ABI)
                                        -> Option<Uniform>
diff --git a/src/librustc_target/abi/call/riscv.rs b/src/librustc_target/abi/call/riscv.rs
index 4950bcd..ba82e49 100644
--- a/src/librustc_target/abi/call/riscv.rs
+++ b/src/librustc_target/abi/call/riscv.rs
@@ -1,9 +1,9 @@
 // Reference: RISC-V ELF psABI specification
 // https://github.com/riscv/riscv-elf-psabi-doc
 
-use abi::call::{ArgType, FnType};
+use crate::abi::call::{ArgType, FnType};
 
-fn classify_ret_ty<Ty>(arg: &mut ArgType<Ty>, xlen: u64) {
+fn classify_ret_ty<Ty>(arg: &mut ArgType<'_, Ty>, xlen: u64) {
     // "Scalars wider than 2✕XLEN are passed by reference and are replaced in
     // the argument list with the address."
     // "Aggregates larger than 2✕XLEN bits are passed by reference and are
@@ -19,7 +19,7 @@
     arg.extend_integer_width_to(xlen); // this method only affects integer scalars
 }
 
-fn classify_arg_ty<Ty>(arg: &mut ArgType<Ty>, xlen: u64) {
+fn classify_arg_ty<Ty>(arg: &mut ArgType<'_, Ty>, xlen: u64) {
     // "Scalars wider than 2✕XLEN are passed by reference and are replaced in
     // the argument list with the address."
     // "Aggregates larger than 2✕XLEN bits are passed by reference and are
@@ -35,7 +35,7 @@
     arg.extend_integer_width_to(xlen); // this method only affects integer scalars
 }
 
-pub fn compute_abi_info<Ty>(fty: &mut FnType<Ty>, xlen: u64) {
+pub fn compute_abi_info<Ty>(fty: &mut FnType<'_, Ty>, xlen: u64) {
     if !fty.ret.is_ignore() {
         classify_ret_ty(&mut fty.ret, xlen);
     }
diff --git a/src/librustc_target/abi/call/s390x.rs b/src/librustc_target/abi/call/s390x.rs
index 954c37f..c2717b1 100644
--- a/src/librustc_target/abi/call/s390x.rs
+++ b/src/librustc_target/abi/call/s390x.rs
@@ -1,10 +1,10 @@
 // FIXME: The assumes we're using the non-vector ABI, i.e., compiling
 // for a pre-z13 machine or using -mno-vx.
 
-use abi::call::{FnType, ArgType, Reg};
-use abi::{self, HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
+use crate::abi::call::{FnType, ArgType, Reg};
+use crate::abi::{self, HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
 
-fn classify_ret_ty<'a, Ty, C>(ret: &mut ArgType<Ty>)
+fn classify_ret_ty<'a, Ty, C>(ret: &mut ArgType<'_, Ty>)
     where Ty: TyLayoutMethods<'a, C>, C: LayoutOf<Ty = Ty> + HasDataLayout
 {
     if !ret.layout.is_aggregate() && ret.layout.size.bits() <= 64 {
diff --git a/src/librustc_target/abi/call/sparc.rs b/src/librustc_target/abi/call/sparc.rs
index 2335bfb..d496abf 100644
--- a/src/librustc_target/abi/call/sparc.rs
+++ b/src/librustc_target/abi/call/sparc.rs
@@ -1,7 +1,7 @@
-use abi::call::{ArgType, FnType, Reg, Uniform};
-use abi::{HasDataLayout, LayoutOf, Size, TyLayoutMethods};
+use crate::abi::call::{ArgType, FnType, Reg, Uniform};
+use crate::abi::{HasDataLayout, LayoutOf, Size, TyLayoutMethods};
 
-fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType<Ty>, offset: &mut Size)
+fn classify_ret_ty<'a, Ty, C>(cx: &C, ret: &mut ArgType<'_, Ty>, offset: &mut Size)
     where Ty: TyLayoutMethods<'a, C>, C: LayoutOf<Ty = Ty> + HasDataLayout
 {
     if !ret.layout.is_aggregate() {
@@ -12,7 +12,7 @@
     }
 }
 
-fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType<Ty>, offset: &mut Size)
+fn classify_arg_ty<'a, Ty, C>(cx: &C, arg: &mut ArgType<'_, Ty>, offset: &mut Size)
     where Ty: TyLayoutMethods<'a, C>, C: LayoutOf<Ty = Ty> + HasDataLayout
 {
     let dl = cx.data_layout();
@@ -34,7 +34,7 @@
     *offset = offset.align_to(align) + size.align_to(align);
 }
 
-pub fn compute_abi_info<'a, Ty, C>(cx: &C, fty: &mut FnType<Ty>)
+pub fn compute_abi_info<'a, Ty, C>(cx: &C, fty: &mut FnType<'_, Ty>)
     where Ty: TyLayoutMethods<'a, C>, C: LayoutOf<Ty = Ty> + HasDataLayout
 {
     let mut offset = Size::ZERO;
diff --git a/src/librustc_target/abi/call/sparc64.rs b/src/librustc_target/abi/call/sparc64.rs
index 150b48a..d8930a8 100644
--- a/src/librustc_target/abi/call/sparc64.rs
+++ b/src/librustc_target/abi/call/sparc64.rs
@@ -1,7 +1,7 @@
 // FIXME: This needs an audit for correctness and completeness.
 
-use abi::call::{FnType, ArgType, Reg, RegKind, Uniform};
-use abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
+use crate::abi::call::{FnType, ArgType, Reg, RegKind, Uniform};
+use crate::abi::{HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
 
 fn is_homogeneous_aggregate<'a, Ty, C>(cx: &C, arg: &mut ArgType<'a, Ty>)
                                      -> Option<Uniform>
diff --git a/src/librustc_target/abi/call/wasm32.rs b/src/librustc_target/abi/call/wasm32.rs
index 78f43f8..1fdcbb8 100644
--- a/src/librustc_target/abi/call/wasm32.rs
+++ b/src/librustc_target/abi/call/wasm32.rs
@@ -1,14 +1,14 @@
-use abi::call::{FnType, ArgType};
+use crate::abi::call::{FnType, ArgType};
 
-fn classify_ret_ty<Ty>(ret: &mut ArgType<Ty>) {
+fn classify_ret_ty<Ty>(ret: &mut ArgType<'_, Ty>) {
     ret.extend_integer_width_to(32);
 }
 
-fn classify_arg_ty<Ty>(arg: &mut ArgType<Ty>) {
+fn classify_arg_ty<Ty>(arg: &mut ArgType<'_, Ty>) {
     arg.extend_integer_width_to(32);
 }
 
-pub fn compute_abi_info<Ty>(fty: &mut FnType<Ty>) {
+pub fn compute_abi_info<Ty>(fty: &mut FnType<'_, Ty>) {
     if !fty.ret.is_ignore() {
         classify_ret_ty(&mut fty.ret);
     }
diff --git a/src/librustc_target/abi/call/x86.rs b/src/librustc_target/abi/call/x86.rs
index 648a4b5..2e80957 100644
--- a/src/librustc_target/abi/call/x86.rs
+++ b/src/librustc_target/abi/call/x86.rs
@@ -1,6 +1,6 @@
-use abi::call::{ArgAttribute, FnType, PassMode, Reg, RegKind};
-use abi::{self, HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
-use spec::HasTargetSpec;
+use crate::abi::call::{ArgAttribute, FnType, PassMode, Reg, RegKind};
+use crate::abi::{self, HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods};
+use crate::spec::HasTargetSpec;
 
 #[derive(PartialEq)]
 pub enum Flavor {
diff --git a/src/librustc_target/abi/call/x86_64.rs b/src/librustc_target/abi/call/x86_64.rs
index 9d8cc19..680e529 100644
--- a/src/librustc_target/abi/call/x86_64.rs
+++ b/src/librustc_target/abi/call/x86_64.rs
@@ -1,8 +1,8 @@
 // The classification code for the x86_64 ABI is taken from the clay language
 // https://github.com/jckarter/clay/blob/master/compiler/src/externals.cpp
 
-use abi::call::{ArgType, CastTarget, FnType, Reg, RegKind};
-use abi::{self, Abi, HasDataLayout, LayoutOf, Size, TyLayout, TyLayoutMethods};
+use crate::abi::call::{ArgType, CastTarget, FnType, Reg, RegKind};
+use crate::abi::{self, Abi, HasDataLayout, LayoutOf, Size, TyLayout, TyLayoutMethods};
 
 /// Classification of "eightbyte" components.
 // N.B., the order of the variants is from general to specific,
diff --git a/src/librustc_target/abi/call/x86_win64.rs b/src/librustc_target/abi/call/x86_win64.rs
index c583f7a..ebdeb63 100644
--- a/src/librustc_target/abi/call/x86_win64.rs
+++ b/src/librustc_target/abi/call/x86_win64.rs
@@ -1,10 +1,10 @@
-use abi::call::{ArgType, FnType, Reg};
-use abi::Abi;
+use crate::abi::call::{ArgType, FnType, Reg};
+use crate::abi::Abi;
 
 // Win64 ABI: http://msdn.microsoft.com/en-us/library/zthk2dkh.aspx
 
-pub fn compute_abi_info<Ty>(fty: &mut FnType<Ty>) {
-    let fixup = |a: &mut ArgType<Ty>| {
+pub fn compute_abi_info<Ty>(fty: &mut FnType<'_, Ty>) {
+    let fixup = |a: &mut ArgType<'_, Ty>| {
         match a.layout.abi {
             Abi::Uninhabited => {}
             Abi::ScalarPair(..) |
diff --git a/src/librustc_target/abi/mod.rs b/src/librustc_target/abi/mod.rs
index 3f95e66..bb194d5 100644
--- a/src/librustc_target/abi/mod.rs
+++ b/src/librustc_target/abi/mod.rs
@@ -1,7 +1,7 @@
-pub use self::Integer::*;
-pub use self::Primitive::*;
+pub use Integer::*;
+pub use Primitive::*;
 
-use spec::Target;
+use crate::spec::Target;
 
 use std::fmt;
 use std::ops::{Add, Deref, Sub, Mul, AddAssign, Range, RangeInclusive};
@@ -533,13 +533,13 @@
 }
 
 impl fmt::Debug for FloatTy {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         fmt::Display::fmt(self, f)
     }
 }
 
 impl fmt::Display for FloatTy {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(f, "{}", self.ty_to_string())
     }
 }
diff --git a/src/librustc_target/lib.rs b/src/librustc_target/lib.rs
index 0df0027..e831eb4 100644
--- a/src/librustc_target/lib.rs
+++ b/src/librustc_target/lib.rs
@@ -7,9 +7,7 @@
 //! more 'stuff' here in the future.  It does not have a dependency on
 //! LLVM.
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-      html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-      html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 
 #![feature(box_syntax)]
 #![feature(nll)]
@@ -17,11 +15,11 @@
 #![feature(slice_patterns)]
 #![feature(step_trait)]
 
-#[macro_use]
-extern crate bitflags;
-extern crate serialize;
+#![deny(rust_2018_idioms)]
+
 #[macro_use] extern crate log;
 
+#[allow(unused_extern_crates)]
 extern crate serialize as rustc_serialize; // used by deriving
 
 // See librustc_cratesio_shim/Cargo.toml for a comment explaining this.
diff --git a/src/librustc_target/spec/aarch64_apple_ios.rs b/src/librustc_target/spec/aarch64_apple_ios.rs
index 2210fd1..8bdc08c 100644
--- a/src/librustc_target/spec/aarch64_apple_ios.rs
+++ b/src/librustc_target/spec/aarch64_apple_ios.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 use super::apple_ios_base::{opts, Arch};
 
 pub fn target() -> TargetResult {
diff --git a/src/librustc_target/spec/aarch64_fuchsia.rs b/src/librustc_target/spec/aarch64_fuchsia.rs
index e39a1c2..308954d 100644
--- a/src/librustc_target/spec/aarch64_fuchsia.rs
+++ b/src/librustc_target/spec/aarch64_fuchsia.rs
@@ -1,4 +1,4 @@
-use spec::{LldFlavor, LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LldFlavor, LinkerFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::fuchsia_base::opts();
diff --git a/src/librustc_target/spec/aarch64_linux_android.rs b/src/librustc_target/spec/aarch64_linux_android.rs
index c059642..65160f6 100644
--- a/src/librustc_target/spec/aarch64_linux_android.rs
+++ b/src/librustc_target/spec/aarch64_linux_android.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 // See https://developer.android.com/ndk/guides/abis.html#arm64-v8a
 // for target ABI requirements.
diff --git a/src/librustc_target/spec/aarch64_pc_windows_msvc.rs b/src/librustc_target/spec/aarch64_pc_windows_msvc.rs
index b33430b..1aee381 100644
--- a/src/librustc_target/spec/aarch64_pc_windows_msvc.rs
+++ b/src/librustc_target/spec/aarch64_pc_windows_msvc.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult, PanicStrategy};
+use crate::spec::{LinkerFlavor, Target, TargetResult, PanicStrategy};
 
 pub fn target() -> TargetResult {
     let mut base = super::windows_msvc_base::opts();
diff --git a/src/librustc_target/spec/aarch64_unknown_cloudabi.rs b/src/librustc_target/spec/aarch64_unknown_cloudabi.rs
index ac3345c..7141954 100644
--- a/src/librustc_target/spec/aarch64_unknown_cloudabi.rs
+++ b/src/librustc_target/spec/aarch64_unknown_cloudabi.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::cloudabi_base::opts();
diff --git a/src/librustc_target/spec/aarch64_unknown_freebsd.rs b/src/librustc_target/spec/aarch64_unknown_freebsd.rs
index 1fb0a2b..3686064 100644
--- a/src/librustc_target/spec/aarch64_unknown_freebsd.rs
+++ b/src/librustc_target/spec/aarch64_unknown_freebsd.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::freebsd_base::opts();
diff --git a/src/librustc_target/spec/aarch64_unknown_hermit.rs b/src/librustc_target/spec/aarch64_unknown_hermit.rs
index 26006d0..7b02060 100644
--- a/src/librustc_target/spec/aarch64_unknown_hermit.rs
+++ b/src/librustc_target/spec/aarch64_unknown_hermit.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::hermit_base::opts();
diff --git a/src/librustc_target/spec/aarch64_unknown_linux_gnu.rs b/src/librustc_target/spec/aarch64_unknown_linux_gnu.rs
index d30d927..e772d8b 100644
--- a/src/librustc_target/spec/aarch64_unknown_linux_gnu.rs
+++ b/src/librustc_target/spec/aarch64_unknown_linux_gnu.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_base::opts();
diff --git a/src/librustc_target/spec/aarch64_unknown_linux_musl.rs b/src/librustc_target/spec/aarch64_unknown_linux_musl.rs
index 258725f..8123ee8 100644
--- a/src/librustc_target/spec/aarch64_unknown_linux_musl.rs
+++ b/src/librustc_target/spec/aarch64_unknown_linux_musl.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_musl_base::opts();
diff --git a/src/librustc_target/spec/aarch64_unknown_netbsd.rs b/src/librustc_target/spec/aarch64_unknown_netbsd.rs
index 10aef8f..47ae08a 100644
--- a/src/librustc_target/spec/aarch64_unknown_netbsd.rs
+++ b/src/librustc_target/spec/aarch64_unknown_netbsd.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::netbsd_base::opts();
diff --git a/src/librustc_target/spec/aarch64_unknown_openbsd.rs b/src/librustc_target/spec/aarch64_unknown_openbsd.rs
index 815e11a..c9cd64c 100644
--- a/src/librustc_target/spec/aarch64_unknown_openbsd.rs
+++ b/src/librustc_target/spec/aarch64_unknown_openbsd.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::openbsd_base::opts();
diff --git a/src/librustc_target/spec/abi.rs b/src/librustc_target/spec/abi.rs
index 46606e7..c9c41f1 100644
--- a/src/librustc_target/spec/abi.rs
+++ b/src/librustc_target/spec/abi.rs
@@ -96,7 +96,7 @@
 }
 
 impl fmt::Display for Abi {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(f, "\"{}\"", self.name())
     }
 }
diff --git a/src/librustc_target/spec/android_base.rs b/src/librustc_target/spec/android_base.rs
index a8f8ad3..684c059 100644
--- a/src/librustc_target/spec/android_base.rs
+++ b/src/librustc_target/spec/android_base.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, TargetOptions};
+use crate::spec::{LinkerFlavor, TargetOptions};
 
 pub fn opts() -> TargetOptions {
     let mut base = super::linux_base::opts();
diff --git a/src/librustc_target/spec/apple_base.rs b/src/librustc_target/spec/apple_base.rs
index a80d190..c21f7f3 100644
--- a/src/librustc_target/spec/apple_base.rs
+++ b/src/librustc_target/spec/apple_base.rs
@@ -1,6 +1,6 @@
 use std::env;
 
-use spec::{LinkArgs, TargetOptions};
+use crate::spec::{LinkArgs, TargetOptions};
 
 pub fn opts() -> TargetOptions {
     // ELF TLS is only available in macOS 10.7+. If you try to compile for 10.6
diff --git a/src/librustc_target/spec/apple_ios_base.rs b/src/librustc_target/spec/apple_ios_base.rs
index 72346ab..3068ed8 100644
--- a/src/librustc_target/spec/apple_ios_base.rs
+++ b/src/librustc_target/spec/apple_ios_base.rs
@@ -1,8 +1,8 @@
 use std::io;
 use std::process::Command;
-use spec::{LinkArgs, LinkerFlavor, TargetOptions};
+use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions};
 
-use self::Arch::*;
+use Arch::*;
 
 #[allow(non_camel_case_types)]
 #[derive(Copy, Clone)]
diff --git a/src/librustc_target/spec/arm_base.rs b/src/librustc_target/spec/arm_base.rs
index 1d51d60..77e7bfa 100644
--- a/src/librustc_target/spec/arm_base.rs
+++ b/src/librustc_target/spec/arm_base.rs
@@ -1,4 +1,4 @@
-use spec::abi::Abi;
+use crate::spec::abi::Abi;
 
 // All the calling conventions trigger an assertion(Unsupported calling convention) in llvm on arm
 pub fn abi_blacklist() -> Vec<Abi> {
diff --git a/src/librustc_target/spec/arm_linux_androideabi.rs b/src/librustc_target/spec/arm_linux_androideabi.rs
index 5e4bebf..bb066dc 100644
--- a/src/librustc_target/spec/arm_linux_androideabi.rs
+++ b/src/librustc_target/spec/arm_linux_androideabi.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::android_base::opts();
diff --git a/src/librustc_target/spec/arm_unknown_linux_gnueabi.rs b/src/librustc_target/spec/arm_unknown_linux_gnueabi.rs
index 0f891da..f291818 100644
--- a/src/librustc_target/spec/arm_unknown_linux_gnueabi.rs
+++ b/src/librustc_target/spec/arm_unknown_linux_gnueabi.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_base::opts();
diff --git a/src/librustc_target/spec/arm_unknown_linux_gnueabihf.rs b/src/librustc_target/spec/arm_unknown_linux_gnueabihf.rs
index 5503bf3..32b509d 100644
--- a/src/librustc_target/spec/arm_unknown_linux_gnueabihf.rs
+++ b/src/librustc_target/spec/arm_unknown_linux_gnueabihf.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_base::opts();
diff --git a/src/librustc_target/spec/arm_unknown_linux_musleabi.rs b/src/librustc_target/spec/arm_unknown_linux_musleabi.rs
index c2162be..7637577 100644
--- a/src/librustc_target/spec/arm_unknown_linux_musleabi.rs
+++ b/src/librustc_target/spec/arm_unknown_linux_musleabi.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_musl_base::opts();
diff --git a/src/librustc_target/spec/arm_unknown_linux_musleabihf.rs b/src/librustc_target/spec/arm_unknown_linux_musleabihf.rs
index b3f0033..9def151 100644
--- a/src/librustc_target/spec/arm_unknown_linux_musleabihf.rs
+++ b/src/librustc_target/spec/arm_unknown_linux_musleabihf.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_musl_base::opts();
diff --git a/src/librustc_target/spec/armebv7r_none_eabi.rs b/src/librustc_target/spec/armebv7r_none_eabi.rs
index cd41ffb..86c62da 100644
--- a/src/librustc_target/spec/armebv7r_none_eabi.rs
+++ b/src/librustc_target/spec/armebv7r_none_eabi.rs
@@ -1,7 +1,7 @@
 // Targets the Big endian Cortex-R4/R5 processor (ARMv7-R)
 
 use std::default::Default;
-use spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     Ok(Target {
diff --git a/src/librustc_target/spec/armebv7r_none_eabihf.rs b/src/librustc_target/spec/armebv7r_none_eabihf.rs
index 05b12dd..50ee764 100644
--- a/src/librustc_target/spec/armebv7r_none_eabihf.rs
+++ b/src/librustc_target/spec/armebv7r_none_eabihf.rs
@@ -1,7 +1,7 @@
 // Targets the Cortex-R4F/R5F processor (ARMv7-R)
 
 use std::default::Default;
-use spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     Ok(Target {
diff --git a/src/librustc_target/spec/armv4t_unknown_linux_gnueabi.rs b/src/librustc_target/spec/armv4t_unknown_linux_gnueabi.rs
index 7fe021e..7cd4b14 100644
--- a/src/librustc_target/spec/armv4t_unknown_linux_gnueabi.rs
+++ b/src/librustc_target/spec/armv4t_unknown_linux_gnueabi.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     let base = super::linux_base::opts();
diff --git a/src/librustc_target/spec/armv5te_unknown_linux_gnueabi.rs b/src/librustc_target/spec/armv5te_unknown_linux_gnueabi.rs
index c85a80f..15f6148 100644
--- a/src/librustc_target/spec/armv5te_unknown_linux_gnueabi.rs
+++ b/src/librustc_target/spec/armv5te_unknown_linux_gnueabi.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     let base = super::linux_base::opts();
diff --git a/src/librustc_target/spec/armv5te_unknown_linux_musleabi.rs b/src/librustc_target/spec/armv5te_unknown_linux_musleabi.rs
index dce7678..74915b9 100644
--- a/src/librustc_target/spec/armv5te_unknown_linux_musleabi.rs
+++ b/src/librustc_target/spec/armv5te_unknown_linux_musleabi.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     let base = super::linux_musl_base::opts();
diff --git a/src/librustc_target/spec/armv6_unknown_netbsd_eabihf.rs b/src/librustc_target/spec/armv6_unknown_netbsd_eabihf.rs
index 95cc41e..e460b6c 100644
--- a/src/librustc_target/spec/armv6_unknown_netbsd_eabihf.rs
+++ b/src/librustc_target/spec/armv6_unknown_netbsd_eabihf.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::netbsd_base::opts();
diff --git a/src/librustc_target/spec/armv7_apple_ios.rs b/src/librustc_target/spec/armv7_apple_ios.rs
index 9801821..2052d17 100644
--- a/src/librustc_target/spec/armv7_apple_ios.rs
+++ b/src/librustc_target/spec/armv7_apple_ios.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 use super::apple_ios_base::{opts, Arch};
 
 pub fn target() -> TargetResult {
diff --git a/src/librustc_target/spec/armv7_linux_androideabi.rs b/src/librustc_target/spec/armv7_linux_androideabi.rs
index 65c3c7f..92f1a55 100644
--- a/src/librustc_target/spec/armv7_linux_androideabi.rs
+++ b/src/librustc_target/spec/armv7_linux_androideabi.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 // This target if is for the baseline of the Android v7a ABI
 // in thumb mode. It's named armv7-* instead of thumbv7-*
diff --git a/src/librustc_target/spec/armv7_unknown_cloudabi_eabihf.rs b/src/librustc_target/spec/armv7_unknown_cloudabi_eabihf.rs
index fa43879..a6c7fb5 100644
--- a/src/librustc_target/spec/armv7_unknown_cloudabi_eabihf.rs
+++ b/src/librustc_target/spec/armv7_unknown_cloudabi_eabihf.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::cloudabi_base::opts();
diff --git a/src/librustc_target/spec/armv7_unknown_linux_gnueabihf.rs b/src/librustc_target/spec/armv7_unknown_linux_gnueabihf.rs
index 864c59b..f162154 100644
--- a/src/librustc_target/spec/armv7_unknown_linux_gnueabihf.rs
+++ b/src/librustc_target/spec/armv7_unknown_linux_gnueabihf.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 // This target is for glibc Linux on ARMv7 without NEON or
 // thumb-mode. See the thumbv7neon variant for enabling both.
diff --git a/src/librustc_target/spec/armv7_unknown_linux_musleabihf.rs b/src/librustc_target/spec/armv7_unknown_linux_musleabihf.rs
index ae0cb2c..45a2696 100644
--- a/src/librustc_target/spec/armv7_unknown_linux_musleabihf.rs
+++ b/src/librustc_target/spec/armv7_unknown_linux_musleabihf.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 // This target is for musl Linux on ARMv7 without thumb-mode or NEON.
 
diff --git a/src/librustc_target/spec/armv7_unknown_netbsd_eabihf.rs b/src/librustc_target/spec/armv7_unknown_netbsd_eabihf.rs
index f9e416f..44e2636 100644
--- a/src/librustc_target/spec/armv7_unknown_netbsd_eabihf.rs
+++ b/src/librustc_target/spec/armv7_unknown_netbsd_eabihf.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     let base = super::netbsd_base::opts();
diff --git a/src/librustc_target/spec/armv7r_none_eabi.rs b/src/librustc_target/spec/armv7r_none_eabi.rs
index 38d115b..19d3324 100644
--- a/src/librustc_target/spec/armv7r_none_eabi.rs
+++ b/src/librustc_target/spec/armv7r_none_eabi.rs
@@ -1,7 +1,7 @@
 // Targets the Little-endian Cortex-R4/R5 processor (ARMv7-R)
 
 use std::default::Default;
-use spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     Ok(Target {
diff --git a/src/librustc_target/spec/armv7r_none_eabihf.rs b/src/librustc_target/spec/armv7r_none_eabihf.rs
index cb707f7..06ef9f3 100644
--- a/src/librustc_target/spec/armv7r_none_eabihf.rs
+++ b/src/librustc_target/spec/armv7r_none_eabihf.rs
@@ -1,7 +1,7 @@
 // Targets the Little-endian Cortex-R4F/R5F processor (ARMv7-R)
 
 use std::default::Default;
-use spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     Ok(Target {
diff --git a/src/librustc_target/spec/armv7s_apple_ios.rs b/src/librustc_target/spec/armv7s_apple_ios.rs
index 6d9635b..29e2902 100644
--- a/src/librustc_target/spec/armv7s_apple_ios.rs
+++ b/src/librustc_target/spec/armv7s_apple_ios.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 use super::apple_ios_base::{opts, Arch};
 
 pub fn target() -> TargetResult {
diff --git a/src/librustc_target/spec/bitrig_base.rs b/src/librustc_target/spec/bitrig_base.rs
index 3b6985f..9b34119 100644
--- a/src/librustc_target/spec/bitrig_base.rs
+++ b/src/librustc_target/spec/bitrig_base.rs
@@ -1,4 +1,4 @@
-use spec::{TargetOptions, RelroLevel};
+use crate::spec::{TargetOptions, RelroLevel};
 use std::default::Default;
 
 pub fn opts() -> TargetOptions {
diff --git a/src/librustc_target/spec/cloudabi_base.rs b/src/librustc_target/spec/cloudabi_base.rs
index 145de0e..a34122d 100644
--- a/src/librustc_target/spec/cloudabi_base.rs
+++ b/src/librustc_target/spec/cloudabi_base.rs
@@ -1,4 +1,4 @@
-use spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel};
+use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel};
 
 pub fn opts() -> TargetOptions {
     let mut args = LinkArgs::new();
diff --git a/src/librustc_target/spec/dragonfly_base.rs b/src/librustc_target/spec/dragonfly_base.rs
index 6ce2912..766030e80 100644
--- a/src/librustc_target/spec/dragonfly_base.rs
+++ b/src/librustc_target/spec/dragonfly_base.rs
@@ -1,4 +1,4 @@
-use spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel};
+use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel};
 use std::default::Default;
 
 pub fn opts() -> TargetOptions {
diff --git a/src/librustc_target/spec/freebsd_base.rs b/src/librustc_target/spec/freebsd_base.rs
index 47316f7..51f030f 100644
--- a/src/librustc_target/spec/freebsd_base.rs
+++ b/src/librustc_target/spec/freebsd_base.rs
@@ -1,4 +1,4 @@
-use spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel};
+use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel};
 use std::default::Default;
 
 pub fn opts() -> TargetOptions {
diff --git a/src/librustc_target/spec/fuchsia_base.rs b/src/librustc_target/spec/fuchsia_base.rs
index 5d94f30..4e4f2fa 100644
--- a/src/librustc_target/spec/fuchsia_base.rs
+++ b/src/librustc_target/spec/fuchsia_base.rs
@@ -1,4 +1,4 @@
-use spec::{LldFlavor, LinkArgs, LinkerFlavor, TargetOptions};
+use crate::spec::{LldFlavor, LinkArgs, LinkerFlavor, TargetOptions};
 use std::default::Default;
 
 pub fn opts() -> TargetOptions {
diff --git a/src/librustc_target/spec/haiku_base.rs b/src/librustc_target/spec/haiku_base.rs
index 00c6bd4..d071062 100644
--- a/src/librustc_target/spec/haiku_base.rs
+++ b/src/librustc_target/spec/haiku_base.rs
@@ -1,4 +1,4 @@
-use spec::{TargetOptions, RelroLevel};
+use crate::spec::{TargetOptions, RelroLevel};
 use std::default::Default;
 
 pub fn opts() -> TargetOptions {
diff --git a/src/librustc_target/spec/hermit_base.rs b/src/librustc_target/spec/hermit_base.rs
index d7d8562..ee75339 100644
--- a/src/librustc_target/spec/hermit_base.rs
+++ b/src/librustc_target/spec/hermit_base.rs
@@ -1,4 +1,4 @@
-use spec::{LinkArgs, LinkerFlavor, PanicStrategy, TargetOptions};
+use crate::spec::{LinkArgs, LinkerFlavor, PanicStrategy, TargetOptions};
 use std::default::Default;
 
 pub fn opts() -> TargetOptions {
diff --git a/src/librustc_target/spec/i386_apple_ios.rs b/src/librustc_target/spec/i386_apple_ios.rs
index d0e3176..78e9cbb 100644
--- a/src/librustc_target/spec/i386_apple_ios.rs
+++ b/src/librustc_target/spec/i386_apple_ios.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 use super::apple_ios_base::{opts, Arch};
 
 pub fn target() -> TargetResult {
diff --git a/src/librustc_target/spec/i586_pc_windows_msvc.rs b/src/librustc_target/spec/i586_pc_windows_msvc.rs
index 12a7f98..ba712ac 100644
--- a/src/librustc_target/spec/i586_pc_windows_msvc.rs
+++ b/src/librustc_target/spec/i586_pc_windows_msvc.rs
@@ -1,4 +1,4 @@
-use spec::TargetResult;
+use crate::spec::TargetResult;
 
 pub fn target() -> TargetResult {
     let mut base = super::i686_pc_windows_msvc::target()?;
diff --git a/src/librustc_target/spec/i586_unknown_linux_gnu.rs b/src/librustc_target/spec/i586_unknown_linux_gnu.rs
index 76f6a4eb..49f4f2c 100644
--- a/src/librustc_target/spec/i586_unknown_linux_gnu.rs
+++ b/src/librustc_target/spec/i586_unknown_linux_gnu.rs
@@ -1,4 +1,4 @@
-use spec::TargetResult;
+use crate::spec::TargetResult;
 
 pub fn target() -> TargetResult {
     let mut base = super::i686_unknown_linux_gnu::target()?;
diff --git a/src/librustc_target/spec/i586_unknown_linux_musl.rs b/src/librustc_target/spec/i586_unknown_linux_musl.rs
index 2b56fd7..0f2cceb 100644
--- a/src/librustc_target/spec/i586_unknown_linux_musl.rs
+++ b/src/librustc_target/spec/i586_unknown_linux_musl.rs
@@ -1,4 +1,4 @@
-use spec::TargetResult;
+use crate::spec::TargetResult;
 
 pub fn target() -> TargetResult {
     let mut base = super::i686_unknown_linux_musl::target()?;
diff --git a/src/librustc_target/spec/i686_apple_darwin.rs b/src/librustc_target/spec/i686_apple_darwin.rs
index 40d9588..c8a6129 100644
--- a/src/librustc_target/spec/i686_apple_darwin.rs
+++ b/src/librustc_target/spec/i686_apple_darwin.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::apple_base::opts();
diff --git a/src/librustc_target/spec/i686_linux_android.rs b/src/librustc_target/spec/i686_linux_android.rs
index 5b8cb7a..3f73d24 100644
--- a/src/librustc_target/spec/i686_linux_android.rs
+++ b/src/librustc_target/spec/i686_linux_android.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 // See https://developer.android.com/ndk/guides/abis.html#x86
 // for target ABI requirements.
diff --git a/src/librustc_target/spec/i686_pc_windows_gnu.rs b/src/librustc_target/spec/i686_pc_windows_gnu.rs
index d7bc38c..12214a7 100644
--- a/src/librustc_target/spec/i686_pc_windows_gnu.rs
+++ b/src/librustc_target/spec/i686_pc_windows_gnu.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::windows_base::opts();
diff --git a/src/librustc_target/spec/i686_pc_windows_msvc.rs b/src/librustc_target/spec/i686_pc_windows_msvc.rs
index f0d75ae..1967834 100644
--- a/src/librustc_target/spec/i686_pc_windows_msvc.rs
+++ b/src/librustc_target/spec/i686_pc_windows_msvc.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::windows_msvc_base::opts();
diff --git a/src/librustc_target/spec/i686_unknown_cloudabi.rs b/src/librustc_target/spec/i686_unknown_cloudabi.rs
index 3a9e424..f3b4063 100644
--- a/src/librustc_target/spec/i686_unknown_cloudabi.rs
+++ b/src/librustc_target/spec/i686_unknown_cloudabi.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::cloudabi_base::opts();
diff --git a/src/librustc_target/spec/i686_unknown_dragonfly.rs b/src/librustc_target/spec/i686_unknown_dragonfly.rs
index 9d71c5a..20315e7 100644
--- a/src/librustc_target/spec/i686_unknown_dragonfly.rs
+++ b/src/librustc_target/spec/i686_unknown_dragonfly.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::dragonfly_base::opts();
diff --git a/src/librustc_target/spec/i686_unknown_freebsd.rs b/src/librustc_target/spec/i686_unknown_freebsd.rs
index 627dffa..71f05a1 100644
--- a/src/librustc_target/spec/i686_unknown_freebsd.rs
+++ b/src/librustc_target/spec/i686_unknown_freebsd.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::freebsd_base::opts();
diff --git a/src/librustc_target/spec/i686_unknown_haiku.rs b/src/librustc_target/spec/i686_unknown_haiku.rs
index 86c64ce..b807e4e 100644
--- a/src/librustc_target/spec/i686_unknown_haiku.rs
+++ b/src/librustc_target/spec/i686_unknown_haiku.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::haiku_base::opts();
diff --git a/src/librustc_target/spec/i686_unknown_linux_gnu.rs b/src/librustc_target/spec/i686_unknown_linux_gnu.rs
index ab38832..5875cbf 100644
--- a/src/librustc_target/spec/i686_unknown_linux_gnu.rs
+++ b/src/librustc_target/spec/i686_unknown_linux_gnu.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_base::opts();
diff --git a/src/librustc_target/spec/i686_unknown_linux_musl.rs b/src/librustc_target/spec/i686_unknown_linux_musl.rs
index 81cbf57..7329490 100644
--- a/src/librustc_target/spec/i686_unknown_linux_musl.rs
+++ b/src/librustc_target/spec/i686_unknown_linux_musl.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_musl_base::opts();
diff --git a/src/librustc_target/spec/i686_unknown_netbsd.rs b/src/librustc_target/spec/i686_unknown_netbsd.rs
index 1027e24..e8a9f29 100644
--- a/src/librustc_target/spec/i686_unknown_netbsd.rs
+++ b/src/librustc_target/spec/i686_unknown_netbsd.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::netbsd_base::opts();
diff --git a/src/librustc_target/spec/i686_unknown_openbsd.rs b/src/librustc_target/spec/i686_unknown_openbsd.rs
index d2bbc6b..d7c323e 100644
--- a/src/librustc_target/spec/i686_unknown_openbsd.rs
+++ b/src/librustc_target/spec/i686_unknown_openbsd.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::openbsd_base::opts();
diff --git a/src/librustc_target/spec/l4re_base.rs b/src/librustc_target/spec/l4re_base.rs
index 9510059..9317f05 100644
--- a/src/librustc_target/spec/l4re_base.rs
+++ b/src/librustc_target/spec/l4re_base.rs
@@ -1,4 +1,4 @@
-use spec::{LinkArgs, LinkerFlavor, PanicStrategy, TargetOptions};
+use crate::spec::{LinkArgs, LinkerFlavor, PanicStrategy, TargetOptions};
 use std::default::Default;
 //use std::process::Command;
 
diff --git a/src/librustc_target/spec/linux_base.rs b/src/librustc_target/spec/linux_base.rs
index b036bf8..195fba3 100644
--- a/src/librustc_target/spec/linux_base.rs
+++ b/src/librustc_target/spec/linux_base.rs
@@ -1,4 +1,4 @@
-use spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel};
+use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel};
 use std::default::Default;
 
 pub fn opts() -> TargetOptions {
diff --git a/src/librustc_target/spec/linux_musl_base.rs b/src/librustc_target/spec/linux_musl_base.rs
index 1bc90d1..e294e63 100644
--- a/src/librustc_target/spec/linux_musl_base.rs
+++ b/src/librustc_target/spec/linux_musl_base.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, TargetOptions};
+use crate::spec::{LinkerFlavor, TargetOptions};
 
 pub fn opts() -> TargetOptions {
     let mut base = super::linux_base::opts();
diff --git a/src/librustc_target/spec/mips64_unknown_linux_gnuabi64.rs b/src/librustc_target/spec/mips64_unknown_linux_gnuabi64.rs
index 650f387..3b38e64 100644
--- a/src/librustc_target/spec/mips64_unknown_linux_gnuabi64.rs
+++ b/src/librustc_target/spec/mips64_unknown_linux_gnuabi64.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     Ok(Target {
diff --git a/src/librustc_target/spec/mips64el_unknown_linux_gnuabi64.rs b/src/librustc_target/spec/mips64el_unknown_linux_gnuabi64.rs
index cb348d4..0f6cd86 100644
--- a/src/librustc_target/spec/mips64el_unknown_linux_gnuabi64.rs
+++ b/src/librustc_target/spec/mips64el_unknown_linux_gnuabi64.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     Ok(Target {
diff --git a/src/librustc_target/spec/mips_unknown_linux_gnu.rs b/src/librustc_target/spec/mips_unknown_linux_gnu.rs
index 6cc3d30..b4d29c5 100644
--- a/src/librustc_target/spec/mips_unknown_linux_gnu.rs
+++ b/src/librustc_target/spec/mips_unknown_linux_gnu.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     Ok(Target {
diff --git a/src/librustc_target/spec/mips_unknown_linux_musl.rs b/src/librustc_target/spec/mips_unknown_linux_musl.rs
index 152b11b..c56c6e3 100644
--- a/src/librustc_target/spec/mips_unknown_linux_musl.rs
+++ b/src/librustc_target/spec/mips_unknown_linux_musl.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_musl_base::opts();
diff --git a/src/librustc_target/spec/mips_unknown_linux_uclibc.rs b/src/librustc_target/spec/mips_unknown_linux_uclibc.rs
index 99cd20e..cb02769 100644
--- a/src/librustc_target/spec/mips_unknown_linux_uclibc.rs
+++ b/src/librustc_target/spec/mips_unknown_linux_uclibc.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     Ok(Target {
diff --git a/src/librustc_target/spec/mipsel_unknown_linux_gnu.rs b/src/librustc_target/spec/mipsel_unknown_linux_gnu.rs
index 476cf15..ed49ddd 100644
--- a/src/librustc_target/spec/mipsel_unknown_linux_gnu.rs
+++ b/src/librustc_target/spec/mipsel_unknown_linux_gnu.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     Ok(Target {
diff --git a/src/librustc_target/spec/mipsel_unknown_linux_musl.rs b/src/librustc_target/spec/mipsel_unknown_linux_musl.rs
index 9df131d..bcc49cf 100644
--- a/src/librustc_target/spec/mipsel_unknown_linux_musl.rs
+++ b/src/librustc_target/spec/mipsel_unknown_linux_musl.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_musl_base::opts();
diff --git a/src/librustc_target/spec/mipsel_unknown_linux_uclibc.rs b/src/librustc_target/spec/mipsel_unknown_linux_uclibc.rs
index 37c55d1..205f328 100644
--- a/src/librustc_target/spec/mipsel_unknown_linux_uclibc.rs
+++ b/src/librustc_target/spec/mipsel_unknown_linux_uclibc.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     Ok(Target {
diff --git a/src/librustc_target/spec/mod.rs b/src/librustc_target/spec/mod.rs
index aeecce4..107583e 100644
--- a/src/librustc_target/spec/mod.rs
+++ b/src/librustc_target/spec/mod.rs
@@ -40,7 +40,7 @@
 use std::{fmt, io};
 use std::path::{Path, PathBuf};
 use std::str::FromStr;
-use spec::abi::{Abi, lookup as lookup_abi};
+use crate::spec::abi::{Abi, lookup as lookup_abi};
 
 pub mod abi;
 mod android_base;
@@ -1408,7 +1408,7 @@
 }
 
 impl fmt::Display for TargetTriple {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(f, "{}", self.debug_triple())
     }
 }
diff --git a/src/librustc_target/spec/msp430_none_elf.rs b/src/librustc_target/spec/msp430_none_elf.rs
index df564bc..90af589 100644
--- a/src/librustc_target/spec/msp430_none_elf.rs
+++ b/src/librustc_target/spec/msp430_none_elf.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, PanicStrategy, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, PanicStrategy, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     Ok(Target {
diff --git a/src/librustc_target/spec/netbsd_base.rs b/src/librustc_target/spec/netbsd_base.rs
index b88d360..e9cd98c 100644
--- a/src/librustc_target/spec/netbsd_base.rs
+++ b/src/librustc_target/spec/netbsd_base.rs
@@ -1,4 +1,4 @@
-use spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel};
+use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel};
 use std::default::Default;
 
 pub fn opts() -> TargetOptions {
diff --git a/src/librustc_target/spec/nvptx64_nvidia_cuda.rs b/src/librustc_target/spec/nvptx64_nvidia_cuda.rs
index e851241..db9d6a7 100644
--- a/src/librustc_target/spec/nvptx64_nvidia_cuda.rs
+++ b/src/librustc_target/spec/nvptx64_nvidia_cuda.rs
@@ -1,5 +1,5 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult, PanicStrategy, MergeFunctions};
-use spec::abi::Abi;
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult, PanicStrategy, MergeFunctions};
+use crate::spec::abi::Abi;
 
 pub fn target() -> TargetResult {
     Ok(Target {
diff --git a/src/librustc_target/spec/openbsd_base.rs b/src/librustc_target/spec/openbsd_base.rs
index 4bdf73f..5bcfd62 100644
--- a/src/librustc_target/spec/openbsd_base.rs
+++ b/src/librustc_target/spec/openbsd_base.rs
@@ -1,4 +1,4 @@
-use spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel};
+use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions, RelroLevel};
 use std::default::Default;
 
 pub fn opts() -> TargetOptions {
diff --git a/src/librustc_target/spec/powerpc64_unknown_freebsd.rs b/src/librustc_target/spec/powerpc64_unknown_freebsd.rs
index cc7b87b..360876b 100644
--- a/src/librustc_target/spec/powerpc64_unknown_freebsd.rs
+++ b/src/librustc_target/spec/powerpc64_unknown_freebsd.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::freebsd_base::opts();
diff --git a/src/librustc_target/spec/powerpc64_unknown_linux_gnu.rs b/src/librustc_target/spec/powerpc64_unknown_linux_gnu.rs
index 1f7ae93..c16db75 100644
--- a/src/librustc_target/spec/powerpc64_unknown_linux_gnu.rs
+++ b/src/librustc_target/spec/powerpc64_unknown_linux_gnu.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult, RelroLevel};
+use crate::spec::{LinkerFlavor, Target, TargetResult, RelroLevel};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_base::opts();
diff --git a/src/librustc_target/spec/powerpc64_unknown_linux_musl.rs b/src/librustc_target/spec/powerpc64_unknown_linux_musl.rs
index 6fc8be8..ac0b743 100644
--- a/src/librustc_target/spec/powerpc64_unknown_linux_musl.rs
+++ b/src/librustc_target/spec/powerpc64_unknown_linux_musl.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_musl_base::opts();
diff --git a/src/librustc_target/spec/powerpc64le_unknown_linux_gnu.rs b/src/librustc_target/spec/powerpc64le_unknown_linux_gnu.rs
index 21791a7..038b925 100644
--- a/src/librustc_target/spec/powerpc64le_unknown_linux_gnu.rs
+++ b/src/librustc_target/spec/powerpc64le_unknown_linux_gnu.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_base::opts();
diff --git a/src/librustc_target/spec/powerpc64le_unknown_linux_musl.rs b/src/librustc_target/spec/powerpc64le_unknown_linux_musl.rs
index 38f7fe8..5710334 100644
--- a/src/librustc_target/spec/powerpc64le_unknown_linux_musl.rs
+++ b/src/librustc_target/spec/powerpc64le_unknown_linux_musl.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_musl_base::opts();
diff --git a/src/librustc_target/spec/powerpc_unknown_linux_gnu.rs b/src/librustc_target/spec/powerpc_unknown_linux_gnu.rs
index 286d177..38a801d 100644
--- a/src/librustc_target/spec/powerpc_unknown_linux_gnu.rs
+++ b/src/librustc_target/spec/powerpc_unknown_linux_gnu.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_base::opts();
diff --git a/src/librustc_target/spec/powerpc_unknown_linux_gnuspe.rs b/src/librustc_target/spec/powerpc_unknown_linux_gnuspe.rs
index ae144af..675b2c7 100644
--- a/src/librustc_target/spec/powerpc_unknown_linux_gnuspe.rs
+++ b/src/librustc_target/spec/powerpc_unknown_linux_gnuspe.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_base::opts();
diff --git a/src/librustc_target/spec/powerpc_unknown_linux_musl.rs b/src/librustc_target/spec/powerpc_unknown_linux_musl.rs
index 3b61889..240443a 100644
--- a/src/librustc_target/spec/powerpc_unknown_linux_musl.rs
+++ b/src/librustc_target/spec/powerpc_unknown_linux_musl.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_musl_base::opts();
diff --git a/src/librustc_target/spec/powerpc_unknown_netbsd.rs b/src/librustc_target/spec/powerpc_unknown_netbsd.rs
index e8662a7..10e7089 100644
--- a/src/librustc_target/spec/powerpc_unknown_netbsd.rs
+++ b/src/librustc_target/spec/powerpc_unknown_netbsd.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::netbsd_base::opts();
diff --git a/src/librustc_target/spec/redox_base.rs b/src/librustc_target/spec/redox_base.rs
index dd32f02..dc51aeb 100644
--- a/src/librustc_target/spec/redox_base.rs
+++ b/src/librustc_target/spec/redox_base.rs
@@ -1,4 +1,4 @@
-use spec::{LinkArgs, LinkerFlavor, TargetOptions};
+use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions};
 use std::default::Default;
 
 pub fn opts() -> TargetOptions {
diff --git a/src/librustc_target/spec/riscv32imac_unknown_none_elf.rs b/src/librustc_target/spec/riscv32imac_unknown_none_elf.rs
index 8adf562..5064393 100644
--- a/src/librustc_target/spec/riscv32imac_unknown_none_elf.rs
+++ b/src/librustc_target/spec/riscv32imac_unknown_none_elf.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, LldFlavor, PanicStrategy,
+use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy,
            Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
diff --git a/src/librustc_target/spec/riscv32imc_unknown_none_elf.rs b/src/librustc_target/spec/riscv32imc_unknown_none_elf.rs
index 5d8157e..31e74c5 100644
--- a/src/librustc_target/spec/riscv32imc_unknown_none_elf.rs
+++ b/src/librustc_target/spec/riscv32imc_unknown_none_elf.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, LldFlavor, PanicStrategy,
+use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy,
            Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
diff --git a/src/librustc_target/spec/riscv_base.rs b/src/librustc_target/spec/riscv_base.rs
index ea7fdc3..ec1dc9b 100644
--- a/src/librustc_target/spec/riscv_base.rs
+++ b/src/librustc_target/spec/riscv_base.rs
@@ -1,4 +1,4 @@
-use spec::abi::Abi;
+use crate::spec::abi::Abi;
 
 // All the calling conventions trigger an assertion(Unsupported calling
 // convention) in llvm on RISCV
diff --git a/src/librustc_target/spec/s390x_unknown_linux_gnu.rs b/src/librustc_target/spec/s390x_unknown_linux_gnu.rs
index c18c945..f259787 100644
--- a/src/librustc_target/spec/s390x_unknown_linux_gnu.rs
+++ b/src/librustc_target/spec/s390x_unknown_linux_gnu.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_base::opts();
diff --git a/src/librustc_target/spec/solaris_base.rs b/src/librustc_target/spec/solaris_base.rs
index f5f8509..0dfbb13 100644
--- a/src/librustc_target/spec/solaris_base.rs
+++ b/src/librustc_target/spec/solaris_base.rs
@@ -1,4 +1,4 @@
-use spec::TargetOptions;
+use crate::spec::TargetOptions;
 use std::default::Default;
 
 pub fn opts() -> TargetOptions {
diff --git a/src/librustc_target/spec/sparc64_unknown_linux_gnu.rs b/src/librustc_target/spec/sparc64_unknown_linux_gnu.rs
index e5e3752..c842b22 100644
--- a/src/librustc_target/spec/sparc64_unknown_linux_gnu.rs
+++ b/src/librustc_target/spec/sparc64_unknown_linux_gnu.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_base::opts();
diff --git a/src/librustc_target/spec/sparc64_unknown_netbsd.rs b/src/librustc_target/spec/sparc64_unknown_netbsd.rs
index 62efd41..78d53e6 100644
--- a/src/librustc_target/spec/sparc64_unknown_netbsd.rs
+++ b/src/librustc_target/spec/sparc64_unknown_netbsd.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::netbsd_base::opts();
diff --git a/src/librustc_target/spec/sparc_unknown_linux_gnu.rs b/src/librustc_target/spec/sparc_unknown_linux_gnu.rs
index b646899..162cd31 100644
--- a/src/librustc_target/spec/sparc_unknown_linux_gnu.rs
+++ b/src/librustc_target/spec/sparc_unknown_linux_gnu.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_base::opts();
diff --git a/src/librustc_target/spec/sparcv9_sun_solaris.rs b/src/librustc_target/spec/sparcv9_sun_solaris.rs
index f1c5c5a..acc03fd 100644
--- a/src/librustc_target/spec/sparcv9_sun_solaris.rs
+++ b/src/librustc_target/spec/sparcv9_sun_solaris.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::solaris_base::opts();
diff --git a/src/librustc_target/spec/thumb_base.rs b/src/librustc_target/spec/thumb_base.rs
index 06cb6a8..ed0dbb7 100644
--- a/src/librustc_target/spec/thumb_base.rs
+++ b/src/librustc_target/spec/thumb_base.rs
@@ -28,7 +28,7 @@
 // build scripts / gcc flags.
 
 use std::default::Default;
-use spec::{PanicStrategy, TargetOptions};
+use crate::spec::{PanicStrategy, TargetOptions};
 
 pub fn opts() -> TargetOptions {
     // See rust-lang/rfcs#1645 for a discussion about these defaults
diff --git a/src/librustc_target/spec/thumbv6m_none_eabi.rs b/src/librustc_target/spec/thumbv6m_none_eabi.rs
index 98c46e9..2ab61b5 100644
--- a/src/librustc_target/spec/thumbv6m_none_eabi.rs
+++ b/src/librustc_target/spec/thumbv6m_none_eabi.rs
@@ -1,6 +1,6 @@
 // Targets the Cortex-M0, Cortex-M0+ and Cortex-M1 processors (ARMv6-M architecture)
 
-use spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     Ok(Target {
diff --git a/src/librustc_target/spec/thumbv7a_pc_windows_msvc.rs b/src/librustc_target/spec/thumbv7a_pc_windows_msvc.rs
index eaa08fa..310fac3 100644
--- a/src/librustc_target/spec/thumbv7a_pc_windows_msvc.rs
+++ b/src/librustc_target/spec/thumbv7a_pc_windows_msvc.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult, PanicStrategy};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult, PanicStrategy};
 
 pub fn target() -> TargetResult {
     let mut base = super::windows_msvc_base::opts();
diff --git a/src/librustc_target/spec/thumbv7em_none_eabi.rs b/src/librustc_target/spec/thumbv7em_none_eabi.rs
index 8a1fe09..97114c3 100644
--- a/src/librustc_target/spec/thumbv7em_none_eabi.rs
+++ b/src/librustc_target/spec/thumbv7em_none_eabi.rs
@@ -9,7 +9,7 @@
 // To opt-in to hardware accelerated floating point operations, you can use, for example,
 // `-C target-feature=+vfp4` or `-C target-cpu=cortex-m4`.
 
-use spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     Ok(Target {
diff --git a/src/librustc_target/spec/thumbv7em_none_eabihf.rs b/src/librustc_target/spec/thumbv7em_none_eabihf.rs
index 0c9aa1c..e4358bd 100644
--- a/src/librustc_target/spec/thumbv7em_none_eabihf.rs
+++ b/src/librustc_target/spec/thumbv7em_none_eabihf.rs
@@ -8,7 +8,7 @@
 //
 // To opt into double precision hardware support, use the `-C target-feature=-fp-only-sp` flag.
 
-use spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     Ok(Target {
diff --git a/src/librustc_target/spec/thumbv7m_none_eabi.rs b/src/librustc_target/spec/thumbv7m_none_eabi.rs
index 9bff3473..daf25b1 100644
--- a/src/librustc_target/spec/thumbv7m_none_eabi.rs
+++ b/src/librustc_target/spec/thumbv7m_none_eabi.rs
@@ -1,6 +1,6 @@
 // Targets the Cortex-M3 processor (ARMv7-M)
 
-use spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     Ok(Target {
diff --git a/src/librustc_target/spec/thumbv7neon_linux_androideabi.rs b/src/librustc_target/spec/thumbv7neon_linux_androideabi.rs
index 2d92e29..e248b930 100644
--- a/src/librustc_target/spec/thumbv7neon_linux_androideabi.rs
+++ b/src/librustc_target/spec/thumbv7neon_linux_androideabi.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 // This target if is for the Android v7a ABI in thumb mode with
 // NEON unconditionally enabled and, therefore, with 32 FPU registers
diff --git a/src/librustc_target/spec/thumbv7neon_unknown_linux_gnueabihf.rs b/src/librustc_target/spec/thumbv7neon_unknown_linux_gnueabihf.rs
index bdf5796..bef62b0 100644
--- a/src/librustc_target/spec/thumbv7neon_unknown_linux_gnueabihf.rs
+++ b/src/librustc_target/spec/thumbv7neon_unknown_linux_gnueabihf.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 
 // This target is for glibc Linux on ARMv7 with thumb mode enabled
 // (for consistency with Android and Debian-based distributions)
diff --git a/src/librustc_target/spec/thumbv8m_base_none_eabi.rs b/src/librustc_target/spec/thumbv8m_base_none_eabi.rs
index 0e0e73e..be8a476 100644
--- a/src/librustc_target/spec/thumbv8m_base_none_eabi.rs
+++ b/src/librustc_target/spec/thumbv8m_base_none_eabi.rs
@@ -1,6 +1,6 @@
 // Targets the Cortex-M23 processor (Baseline ARMv8-M)
 
-use spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     Ok(Target {
diff --git a/src/librustc_target/spec/thumbv8m_main_none_eabi.rs b/src/librustc_target/spec/thumbv8m_main_none_eabi.rs
index dc2454d..49ab643 100644
--- a/src/librustc_target/spec/thumbv8m_main_none_eabi.rs
+++ b/src/librustc_target/spec/thumbv8m_main_none_eabi.rs
@@ -1,7 +1,7 @@
 // Targets the Cortex-M33 processor (Armv8-M Mainline architecture profile),
 // without the Floating Point extension.
 
-use spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     Ok(Target {
diff --git a/src/librustc_target/spec/thumbv8m_main_none_eabihf.rs b/src/librustc_target/spec/thumbv8m_main_none_eabihf.rs
index 5fa1f42..6a3d8e6 100644
--- a/src/librustc_target/spec/thumbv8m_main_none_eabihf.rs
+++ b/src/librustc_target/spec/thumbv8m_main_none_eabihf.rs
@@ -1,7 +1,7 @@
 // Targets the Cortex-M33 processor (Armv8-M Mainline architecture profile),
 // with the Floating Point extension.
 
-use spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, LldFlavor, Target, TargetOptions, TargetResult};
 
 pub fn target() -> TargetResult {
     Ok(Target {
diff --git a/src/librustc_target/spec/uefi_base.rs b/src/librustc_target/spec/uefi_base.rs
index 4628089..5078d50 100644
--- a/src/librustc_target/spec/uefi_base.rs
+++ b/src/librustc_target/spec/uefi_base.rs
@@ -9,7 +9,7 @@
 // the timer-interrupt. Device-drivers are required to use polling-based models. Furthermore, all
 // code runs in the same environment, no process separation is supported.
 
-use spec::{LinkArgs, LinkerFlavor, LldFlavor, PanicStrategy, TargetOptions};
+use crate::spec::{LinkArgs, LinkerFlavor, LldFlavor, PanicStrategy, TargetOptions};
 use std::default::Default;
 
 pub fn opts() -> TargetOptions {
diff --git a/src/librustc_target/spec/windows_base.rs b/src/librustc_target/spec/windows_base.rs
index 65d6182..38db9cd 100644
--- a/src/librustc_target/spec/windows_base.rs
+++ b/src/librustc_target/spec/windows_base.rs
@@ -1,4 +1,4 @@
-use spec::{LinkArgs, LinkerFlavor, TargetOptions};
+use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions};
 use std::default::Default;
 
 pub fn opts() -> TargetOptions {
diff --git a/src/librustc_target/spec/windows_msvc_base.rs b/src/librustc_target/spec/windows_msvc_base.rs
index 89f6b1b..fdd747c 100644
--- a/src/librustc_target/spec/windows_msvc_base.rs
+++ b/src/librustc_target/spec/windows_msvc_base.rs
@@ -1,4 +1,4 @@
-use spec::{LinkArgs, LinkerFlavor, TargetOptions};
+use crate::spec::{LinkArgs, LinkerFlavor, TargetOptions};
 use std::default::Default;
 
 pub fn opts() -> TargetOptions {
diff --git a/src/librustc_target/spec/x86_64_apple_darwin.rs b/src/librustc_target/spec/x86_64_apple_darwin.rs
index 7de33fe..0911ce0 100644
--- a/src/librustc_target/spec/x86_64_apple_darwin.rs
+++ b/src/librustc_target/spec/x86_64_apple_darwin.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::apple_base::opts();
diff --git a/src/librustc_target/spec/x86_64_apple_ios.rs b/src/librustc_target/spec/x86_64_apple_ios.rs
index 286a73d..1f9594b 100644
--- a/src/librustc_target/spec/x86_64_apple_ios.rs
+++ b/src/librustc_target/spec/x86_64_apple_ios.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetOptions, TargetResult};
 use super::apple_ios_base::{opts, Arch};
 
 pub fn target() -> TargetResult {
diff --git a/src/librustc_target/spec/x86_64_fuchsia.rs b/src/librustc_target/spec/x86_64_fuchsia.rs
index 00fb706..a24d432c 100644
--- a/src/librustc_target/spec/x86_64_fuchsia.rs
+++ b/src/librustc_target/spec/x86_64_fuchsia.rs
@@ -1,4 +1,4 @@
-use spec::{LldFlavor, LinkerFlavor, Target, TargetResult};
+use crate::spec::{LldFlavor, LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::fuchsia_base::opts();
diff --git a/src/librustc_target/spec/x86_64_linux_android.rs b/src/librustc_target/spec/x86_64_linux_android.rs
index 29d5dfa..c3c6c7b 100644
--- a/src/librustc_target/spec/x86_64_linux_android.rs
+++ b/src/librustc_target/spec/x86_64_linux_android.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::android_base::opts();
diff --git a/src/librustc_target/spec/x86_64_pc_windows_gnu.rs b/src/librustc_target/spec/x86_64_pc_windows_gnu.rs
index c3c36d2..35e0d55 100644
--- a/src/librustc_target/spec/x86_64_pc_windows_gnu.rs
+++ b/src/librustc_target/spec/x86_64_pc_windows_gnu.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::windows_base::opts();
diff --git a/src/librustc_target/spec/x86_64_pc_windows_msvc.rs b/src/librustc_target/spec/x86_64_pc_windows_msvc.rs
index 178d6778..073d49b 100644
--- a/src/librustc_target/spec/x86_64_pc_windows_msvc.rs
+++ b/src/librustc_target/spec/x86_64_pc_windows_msvc.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::windows_msvc_base::opts();
diff --git a/src/librustc_target/spec/x86_64_rumprun_netbsd.rs b/src/librustc_target/spec/x86_64_rumprun_netbsd.rs
index 37c7925..a2c706c 100644
--- a/src/librustc_target/spec/x86_64_rumprun_netbsd.rs
+++ b/src/librustc_target/spec/x86_64_rumprun_netbsd.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::netbsd_base::opts();
diff --git a/src/librustc_target/spec/x86_64_sun_solaris.rs b/src/librustc_target/spec/x86_64_sun_solaris.rs
index 3534f9e..3bf3f51 100644
--- a/src/librustc_target/spec/x86_64_sun_solaris.rs
+++ b/src/librustc_target/spec/x86_64_sun_solaris.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::solaris_base::opts();
diff --git a/src/librustc_target/spec/x86_64_unknown_bitrig.rs b/src/librustc_target/spec/x86_64_unknown_bitrig.rs
index fa53921..999d93a 100644
--- a/src/librustc_target/spec/x86_64_unknown_bitrig.rs
+++ b/src/librustc_target/spec/x86_64_unknown_bitrig.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::bitrig_base::opts();
diff --git a/src/librustc_target/spec/x86_64_unknown_cloudabi.rs b/src/librustc_target/spec/x86_64_unknown_cloudabi.rs
index c1253a3..d48120c 100644
--- a/src/librustc_target/spec/x86_64_unknown_cloudabi.rs
+++ b/src/librustc_target/spec/x86_64_unknown_cloudabi.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::cloudabi_base::opts();
diff --git a/src/librustc_target/spec/x86_64_unknown_dragonfly.rs b/src/librustc_target/spec/x86_64_unknown_dragonfly.rs
index 815aa57..f55ee69 100644
--- a/src/librustc_target/spec/x86_64_unknown_dragonfly.rs
+++ b/src/librustc_target/spec/x86_64_unknown_dragonfly.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::dragonfly_base::opts();
diff --git a/src/librustc_target/spec/x86_64_unknown_freebsd.rs b/src/librustc_target/spec/x86_64_unknown_freebsd.rs
index 8d43883..1d9c5cc 100644
--- a/src/librustc_target/spec/x86_64_unknown_freebsd.rs
+++ b/src/librustc_target/spec/x86_64_unknown_freebsd.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::freebsd_base::opts();
diff --git a/src/librustc_target/spec/x86_64_unknown_haiku.rs b/src/librustc_target/spec/x86_64_unknown_haiku.rs
index 6083547..4ab15fa 100644
--- a/src/librustc_target/spec/x86_64_unknown_haiku.rs
+++ b/src/librustc_target/spec/x86_64_unknown_haiku.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::haiku_base::opts();
diff --git a/src/librustc_target/spec/x86_64_unknown_hermit.rs b/src/librustc_target/spec/x86_64_unknown_hermit.rs
index de5992c..a696ee1 100644
--- a/src/librustc_target/spec/x86_64_unknown_hermit.rs
+++ b/src/librustc_target/spec/x86_64_unknown_hermit.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::hermit_base::opts();
diff --git a/src/librustc_target/spec/x86_64_unknown_l4re_uclibc.rs b/src/librustc_target/spec/x86_64_unknown_l4re_uclibc.rs
index cf04cc1..e5fdb38 100644
--- a/src/librustc_target/spec/x86_64_unknown_l4re_uclibc.rs
+++ b/src/librustc_target/spec/x86_64_unknown_l4re_uclibc.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::l4re_base::opts();
diff --git a/src/librustc_target/spec/x86_64_unknown_linux_gnu.rs b/src/librustc_target/spec/x86_64_unknown_linux_gnu.rs
index c6ec8de..cb279e8 100644
--- a/src/librustc_target/spec/x86_64_unknown_linux_gnu.rs
+++ b/src/librustc_target/spec/x86_64_unknown_linux_gnu.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_base::opts();
diff --git a/src/librustc_target/spec/x86_64_unknown_linux_gnux32.rs b/src/librustc_target/spec/x86_64_unknown_linux_gnux32.rs
index e4dfb8d..0b2d7aa 100644
--- a/src/librustc_target/spec/x86_64_unknown_linux_gnux32.rs
+++ b/src/librustc_target/spec/x86_64_unknown_linux_gnux32.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_base::opts();
diff --git a/src/librustc_target/spec/x86_64_unknown_linux_musl.rs b/src/librustc_target/spec/x86_64_unknown_linux_musl.rs
index 95321fe..2e1bc83 100644
--- a/src/librustc_target/spec/x86_64_unknown_linux_musl.rs
+++ b/src/librustc_target/spec/x86_64_unknown_linux_musl.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::linux_musl_base::opts();
diff --git a/src/librustc_target/spec/x86_64_unknown_netbsd.rs b/src/librustc_target/spec/x86_64_unknown_netbsd.rs
index fbd07ec..ffc4f1d 100644
--- a/src/librustc_target/spec/x86_64_unknown_netbsd.rs
+++ b/src/librustc_target/spec/x86_64_unknown_netbsd.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::netbsd_base::opts();
diff --git a/src/librustc_target/spec/x86_64_unknown_openbsd.rs b/src/librustc_target/spec/x86_64_unknown_openbsd.rs
index 6849624..f2abd10 100644
--- a/src/librustc_target/spec/x86_64_unknown_openbsd.rs
+++ b/src/librustc_target/spec/x86_64_unknown_openbsd.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::openbsd_base::opts();
diff --git a/src/librustc_target/spec/x86_64_unknown_redox.rs b/src/librustc_target/spec/x86_64_unknown_redox.rs
index d04bc5c..f0a4519 100644
--- a/src/librustc_target/spec/x86_64_unknown_redox.rs
+++ b/src/librustc_target/spec/x86_64_unknown_redox.rs
@@ -1,4 +1,4 @@
-use spec::{LinkerFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::redox_base::opts();
diff --git a/src/librustc_target/spec/x86_64_unknown_uefi.rs b/src/librustc_target/spec/x86_64_unknown_uefi.rs
index 0d7b4fc..9ac17a1 100644
--- a/src/librustc_target/spec/x86_64_unknown_uefi.rs
+++ b/src/librustc_target/spec/x86_64_unknown_uefi.rs
@@ -5,7 +5,7 @@
 // The win64 ABI is used. It differs from the sysv64 ABI, so we must use a windows target with
 // LLVM. "x86_64-unknown-windows" is used to get the minimal subset of windows-specific features.
 
-use spec::{LinkerFlavor, LldFlavor, Target, TargetResult};
+use crate::spec::{LinkerFlavor, LldFlavor, Target, TargetResult};
 
 pub fn target() -> TargetResult {
     let mut base = super::uefi_base::opts();
diff --git a/src/librustc_traits/Cargo.toml b/src/librustc_traits/Cargo.toml
index bf946d3..da19cc9 100644
--- a/src/librustc_traits/Cargo.toml
+++ b/src/librustc_traits/Cargo.toml
@@ -2,6 +2,7 @@
 authors = ["The Rust Project Developers"]
 name = "rustc_traits"
 version = "0.0.0"
+edition = "2018"
 
 [lib]
 name = "rustc_traits"
diff --git a/src/librustc_traits/chalk_context/mod.rs b/src/librustc_traits/chalk_context/mod.rs
index 303920b..ffa696c 100644
--- a/src/librustc_traits/chalk_context/mod.rs
+++ b/src/librustc_traits/chalk_context/mod.rs
@@ -502,13 +502,13 @@
 type ChalkExClause<'tcx> = ExClause<ChalkArenas<'tcx>>;
 
 impl Debug for ChalkContext<'cx, 'gcx> {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(f, "ChalkContext")
     }
 }
 
 impl Debug for ChalkInferenceContext<'cx, 'gcx, 'tcx> {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(f, "ChalkInferenceContext")
     }
 }
@@ -658,7 +658,7 @@
     }
 }
 
-crate fn provide(p: &mut Providers) {
+crate fn provide(p: &mut Providers<'_>) {
     *p = Providers {
         evaluate_goal,
         ..*p
diff --git a/src/librustc_traits/chalk_context/program_clauses.rs b/src/librustc_traits/chalk_context/program_clauses.rs
index 71f4945..adfd268 100644
--- a/src/librustc_traits/chalk_context/program_clauses.rs
+++ b/src/librustc_traits/chalk_context/program_clauses.rs
@@ -220,7 +220,7 @@
         def_id: sized_trait,
         substs: tcx.mk_substs_trait(ty, ty::List::empty()),
     };
-    let sized_implemented: DomainGoal = ty::TraitPredicate {
+    let sized_implemented: DomainGoal<'_> = ty::TraitPredicate {
         trait_ref: sized_implemented
     }.lower();
 
@@ -252,7 +252,7 @@
         def_id: sized_trait,
         substs: tcx.mk_substs_trait(ty, ty::List::empty()),
     };
-    let sized_implemented: DomainGoal = ty::TraitPredicate {
+    let sized_implemented: DomainGoal<'_> = ty::TraitPredicate {
         trait_ref: sized_implemented
     }.lower();
 
@@ -326,7 +326,7 @@
         mutbl,
     });
 
-    let _outlives: DomainGoal = ty::OutlivesPredicate(ty, region).lower();
+    let _outlives: DomainGoal<'_> = ty::OutlivesPredicate(ty, region).lower();
     let wf_clause = ProgramClause {
         goal: DomainGoal::WellFormed(WellFormed::Ty(ref_ty)),
         hypotheses: ty::List::empty(),
diff --git a/src/librustc_traits/dropck_outlives.rs b/src/librustc_traits/dropck_outlives.rs
index 7979fe4..45b19e1 100644
--- a/src/librustc_traits/dropck_outlives.rs
+++ b/src/librustc_traits/dropck_outlives.rs
@@ -10,7 +10,7 @@
 use rustc_data_structures::sync::Lrc;
 use syntax::source_map::{Span, DUMMY_SP};
 
-crate fn provide(p: &mut Providers) {
+crate fn provide(p: &mut Providers<'_>) {
     *p = Providers {
         dropck_outlives,
         adt_dtorck_constraint,
@@ -305,7 +305,7 @@
     let mut result = def.all_fields()
         .map(|field| tcx.type_of(field.did))
         .map(|fty| dtorck_constraint_for_ty(tcx, span, fty, 0, fty))
-        .collect::<Result<DtorckConstraint, NoSolution>>()?;
+        .collect::<Result<DtorckConstraint<'_>, NoSolution>>()?;
     result.outlives.extend(tcx.destructor_constraints(def));
     dedup_dtorck_constraint(&mut result);
 
diff --git a/src/librustc_traits/evaluate_obligation.rs b/src/librustc_traits/evaluate_obligation.rs
index c5b6de2..83aebd1 100644
--- a/src/librustc_traits/evaluate_obligation.rs
+++ b/src/librustc_traits/evaluate_obligation.rs
@@ -6,7 +6,7 @@
 use rustc::ty::{ParamEnvAnd, TyCtxt};
 use syntax::source_map::DUMMY_SP;
 
-crate fn provide(p: &mut Providers) {
+crate fn provide(p: &mut Providers<'_>) {
     *p = Providers {
         evaluate_obligation,
         ..*p
diff --git a/src/librustc_traits/implied_outlives_bounds.rs b/src/librustc_traits/implied_outlives_bounds.rs
index a3fb969..e4a032a 100644
--- a/src/librustc_traits/implied_outlives_bounds.rs
+++ b/src/librustc_traits/implied_outlives_bounds.rs
@@ -17,7 +17,7 @@
 
 use rustc_data_structures::sync::Lrc;
 
-crate fn provide(p: &mut Providers) {
+crate fn provide(p: &mut Providers<'_>) {
     *p = Providers {
         implied_outlives_bounds,
         ..*p
diff --git a/src/librustc_traits/lib.rs b/src/librustc_traits/lib.rs
index a220b92..d52a976 100644
--- a/src/librustc_traits/lib.rs
+++ b/src/librustc_traits/lib.rs
@@ -1,22 +1,18 @@
 //! New recursive solver modeled on Chalk's recursive solver. Most of
 //! the guts are broken up into modules; see the comments in those modules.
 
+#![deny(rust_2018_idioms)]
+
 #![feature(crate_visibility_modifier)]
 #![feature(in_band_lifetimes)]
 #![feature(nll)]
 
 #![recursion_limit="256"]
 
-extern crate chalk_engine;
 #[macro_use]
 extern crate log;
 #[macro_use]
 extern crate rustc;
-extern crate rustc_data_structures;
-extern crate rustc_target;
-extern crate syntax;
-extern crate syntax_pos;
-extern crate smallvec;
 
 mod chalk_context;
 mod dropck_outlives;
@@ -30,7 +26,7 @@
 
 use rustc::ty::query::Providers;
 
-pub fn provide(p: &mut Providers) {
+pub fn provide(p: &mut Providers<'_>) {
     dropck_outlives::provide(p);
     evaluate_obligation::provide(p);
     implied_outlives_bounds::provide(p);
diff --git a/src/librustc_traits/lowering/mod.rs b/src/librustc_traits/lowering/mod.rs
index 9bdef30..908fdcf 100644
--- a/src/librustc_traits/lowering/mod.rs
+++ b/src/librustc_traits/lowering/mod.rs
@@ -23,7 +23,7 @@
 
 use std::iter;
 
-crate fn provide(p: &mut Providers) {
+crate fn provide(p: &mut Providers<'_>) {
     *p = Providers {
         program_clauses_for,
         program_clauses_for_env: environment::program_clauses_for_env,
@@ -193,7 +193,7 @@
     };
 
     // `Implemented(Self: Trait<P1..Pn>)`
-    let impl_trait: DomainGoal = trait_pred.lower();
+    let impl_trait: DomainGoal<'_> = trait_pred.lower();
 
     // `FromEnv(Self: Trait<P1..Pn>)`
     let from_env_goal = tcx.mk_goal(impl_trait.into_from_env_goal().into_goal());
@@ -575,7 +575,7 @@
     let ty = tcx.type_of(item_id);
 
     // `Implemented(A0: Trait<A1..An>)`
-    let trait_implemented: DomainGoal = ty::TraitPredicate { trait_ref }.lower();
+    let trait_implemented: DomainGoal<'_> = ty::TraitPredicate { trait_ref }.lower();
 
     // `<A0 as Trait<A1..An>>::AssocType<Pn+1..Pm>`
     let projection_ty = ty::ProjectionTy::from_ref_and_name(tcx, trait_ref, item.ident);
diff --git a/src/librustc_traits/normalize_erasing_regions.rs b/src/librustc_traits/normalize_erasing_regions.rs
index c06cdbd..412d2ca 100644
--- a/src/librustc_traits/normalize_erasing_regions.rs
+++ b/src/librustc_traits/normalize_erasing_regions.rs
@@ -4,7 +4,7 @@
 use rustc::ty::{self, ParamEnvAnd, Ty, TyCtxt};
 use std::sync::atomic::Ordering;
 
-crate fn provide(p: &mut Providers) {
+crate fn provide(p: &mut Providers<'_>) {
     *p = Providers {
         normalize_ty_after_erasing_regions,
         ..*p
diff --git a/src/librustc_traits/normalize_projection_ty.rs b/src/librustc_traits/normalize_projection_ty.rs
index b31e9c1..6fe9e31 100644
--- a/src/librustc_traits/normalize_projection_ty.rs
+++ b/src/librustc_traits/normalize_projection_ty.rs
@@ -8,7 +8,7 @@
 use syntax::ast::DUMMY_NODE_ID;
 use syntax_pos::DUMMY_SP;
 
-crate fn provide(p: &mut Providers) {
+crate fn provide(p: &mut Providers<'_>) {
     *p = Providers {
         normalize_projection_ty,
         ..*p
diff --git a/src/librustc_traits/type_op.rs b/src/librustc_traits/type_op.rs
index 526637e..3cc2f77 100644
--- a/src/librustc_traits/type_op.rs
+++ b/src/librustc_traits/type_op.rs
@@ -21,7 +21,7 @@
 use syntax::ast;
 use syntax_pos::DUMMY_SP;
 
-crate fn provide(p: &mut Providers) {
+crate fn provide(p: &mut Providers<'_>) {
     *p = Providers {
         type_op_ascribe_user_type,
         type_op_eq,
diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs
index 8da0b6dc..733b03d 100644
--- a/src/librustc_typeck/astconv.rs
+++ b/src/librustc_typeck/astconv.rs
@@ -111,7 +111,7 @@
     {
         let tcx = self.tcx();
         let lifetime_name = |def_id| {
-            tcx.hir().name(tcx.hir().as_local_node_id(def_id).unwrap()).as_interned_str()
+            tcx.hir().name_by_hir_id(tcx.hir().as_local_hir_id(def_id).unwrap()).as_interned_str()
         };
 
         let r = match tcx.named_region(lifetime.hir_id) {
@@ -1682,12 +1682,13 @@
                 assert_eq!(opt_self_ty, None);
                 self.prohibit_generics(&path.segments);
 
-                let node_id = tcx.hir().as_local_node_id(did).unwrap();
-                let item_id = tcx.hir().get_parent_node(node_id);
-                let item_def_id = tcx.hir().local_def_id(item_id);
+                let hir_id = tcx.hir().as_local_hir_id(did).unwrap();
+                let item_id = tcx.hir().get_parent_node_by_hir_id(hir_id);
+                let item_def_id = tcx.hir().local_def_id_from_hir_id(item_id);
                 let generics = tcx.generics_of(item_def_id);
-                let index = generics.param_def_id_to_index[&tcx.hir().local_def_id(node_id)];
-                tcx.mk_ty_param(index, tcx.hir().name(node_id).as_interned_str())
+                let index = generics.param_def_id_to_index[
+                    &tcx.hir().local_def_id_from_hir_id(hir_id)];
+                tcx.mk_ty_param(index, tcx.hir().name_by_hir_id(hir_id).as_interned_str())
             }
             Def::SelfTy(_, Some(def_id)) => {
                 // `Self` in impl (we know the concrete type).
@@ -1793,7 +1794,7 @@
                 let length_def_id = tcx.hir().local_def_id(length.id);
                 let substs = Substs::identity_for_item(tcx, length_def_id);
                 let length = ty::LazyConst::Unevaluated(length_def_id, substs);
-                let length = tcx.intern_lazy_const(length);
+                let length = tcx.mk_lazy_const(length);
                 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
                 self.normalize_ty(ast_ty.span, array_ty)
             }
diff --git a/src/librustc_typeck/check/compare_method.rs b/src/librustc_typeck/check/compare_method.rs
index 0eb8d7d..0cc5071 100644
--- a/src/librustc_typeck/check/compare_method.rs
+++ b/src/librustc_typeck/check/compare_method.rs
@@ -736,8 +736,8 @@
         in impl_m_type_params.zip(trait_m_type_params)
     {
         if impl_synthetic != trait_synthetic {
-            let impl_node_id = tcx.hir().as_local_node_id(impl_def_id).unwrap();
-            let impl_span = tcx.hir().span(impl_node_id);
+            let impl_hir_id = tcx.hir().as_local_hir_id(impl_def_id).unwrap();
+            let impl_span = tcx.hir().span_by_hir_id(impl_hir_id);
             let trait_span = tcx.def_span(trait_def_id);
             let mut err = struct_span_err!(tcx.sess,
                                            impl_span,
@@ -840,7 +840,7 @@
                             match param.kind {
                                 GenericParamKind::Lifetime { .. } => None,
                                 GenericParamKind::Type { .. } => {
-                                    if param.id == impl_node_id {
+                                    if param.hir_id == impl_hir_id {
                                         Some(&param.bounds)
                                     } else {
                                         None
diff --git a/src/librustc_typeck/check/dropck.rs b/src/librustc_typeck/check/dropck.rs
index 60b5db0..e2109091 100644
--- a/src/librustc_typeck/check/dropck.rs
+++ b/src/librustc_typeck/check/dropck.rs
@@ -184,7 +184,7 @@
     // absent. So we report an error that the Drop impl injected a
     // predicate that is not present on the struct definition.
 
-    let self_type_node_id = tcx.hir().as_local_node_id(self_type_did).unwrap();
+    let self_type_hir_id = tcx.hir().as_local_hir_id(self_type_did).unwrap();
 
     let drop_impl_span = tcx.def_span(drop_impl_did);
 
@@ -216,7 +216,7 @@
         // repeated `contains` calls.
 
         if !assumptions_in_impl_context.contains(&predicate) {
-            let item_span = tcx.hir().span(self_type_node_id);
+            let item_span = tcx.hir().span_by_hir_id(self_type_hir_id);
             struct_span_err!(
                 tcx.sess,
                 drop_impl_span,
diff --git a/src/librustc_typeck/check/method/probe.rs b/src/librustc_typeck/check/method/probe.rs
index 6236774..ada4a95 100644
--- a/src/librustc_typeck/check/method/probe.rs
+++ b/src/librustc_typeck/check/method/probe.rs
@@ -85,6 +85,37 @@
 
 #[derive(Debug)]
 struct Candidate<'tcx> {
+    // Candidates are (I'm not quite sure, but they are mostly) basically
+    // some metadata on top of a `ty::AssociatedItem` (without substs).
+    //
+    // However, method probing wants to be able to evaluate the predicates
+    // for a function with the substs applied - for example, if a function
+    // has `where Self: Sized`, we don't want to consider it unless `Self`
+    // is actually `Sized`, and similarly, return-type suggestions want
+    // to consider the "actual" return type.
+    //
+    // The way this is handled is through `xform_self_ty`. It contains
+    // the receiver type of this candidate, but `xform_self_ty`,
+    // `xform_ret_ty` and `kind` (which contains the predicates) have the
+    // generic parameters of this candidate substituted with the *same set*
+    // of inference variables, which acts as some weird sort of "query".
+    //
+    // When we check out a candidate, we require `xform_self_ty` to be
+    // a subtype of the passed-in self-type, and this equates the type
+    // variables in the rest of the fields.
+    //
+    // For example, if we have this candidate:
+    // ```
+    //    trait Foo {
+    //        fn foo(&self) where Self: Sized;
+    //    }
+    // ```
+    //
+    // Then `xform_self_ty` will be `&'erased ?X` and `kind` will contain
+    // the predicate `?X: Sized`, so if we are evaluating `Foo` for a
+    // the receiver `&T`, we'll do the subtyping which will make `?X`
+    // get the right value, then when we evaluate the predicate we'll check
+    // if `T: Sized`.
     xform_self_ty: Ty<'tcx>,
     xform_ret_ty: Option<Ty<'tcx>>,
     item: ty::AssociatedItem,
@@ -506,13 +537,28 @@
         match self_ty.value.value.sty {
             ty::Dynamic(ref data, ..) => {
                 if let Some(p) = data.principal() {
-                    let InferOk { value: instantiated_self_ty, obligations: _ } =
-                        self.fcx.probe_instantiate_query_response(
-                            self.span, &self.orig_steps_var_values, self_ty)
-                        .unwrap_or_else(|_| {
-                            span_bug!(self.span, "{:?} was applicable but now isn't?", self_ty)
-                        });
-                    self.assemble_inherent_candidates_from_object(instantiated_self_ty);
+                    // Subtle: we can't use `instantiate_query_response` here: using it will
+                    // commit to all of the type equalities assumed by inference going through
+                    // autoderef (see the `method-probe-no-guessing` test).
+                    //
+                    // However, in this code, it is OK if we end up with an object type that is
+                    // "more general" than the object type that we are evaluating. For *every*
+                    // object type `MY_OBJECT`, a function call that goes through a trait-ref
+                    // of the form `<MY_OBJECT as SuperTraitOf(MY_OBJECT)>::func` is a valid
+                    // `ObjectCandidate`, and it should be discoverable "exactly" through one
+                    // of the iterations in the autoderef loop, so there is no problem with it
+                    // being discoverable in another one of these iterations.
+                    //
+                    // Using `instantiate_canonical_with_fresh_inference_vars` on our
+                    // `Canonical<QueryResponse<Ty<'tcx>>>` and then *throwing away* the
+                    // `CanonicalVarValues` will exactly give us such a generalization - it
+                    // will still match the original object type, but it won't pollute our
+                    // type variables in any form, so just do that!
+                    let (QueryResponse { value: generalized_self_ty, .. }, _ignored_var_values) =
+                        self.fcx.instantiate_canonical_with_fresh_inference_vars(
+                            self.span, &self_ty);
+
+                    self.assemble_inherent_candidates_from_object(generalized_self_ty);
                     self.assemble_inherent_impl_candidates_for_type(p.def_id());
                 }
             }
diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs
index 3e2a9d7..f82c07e 100644
--- a/src/librustc_typeck/check/mod.rs
+++ b/src/librustc_typeck/check/mod.rs
@@ -1883,14 +1883,14 @@
         // 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)].did;
-            let variant_i_node_id = tcx.hir().as_local_node_id(variant_did).unwrap();
-            let variant_i = tcx.hir().expect_variant(variant_i_node_id);
+            let variant_i_hir_id = tcx.hir().as_local_hir_id(variant_did).unwrap();
+            let variant_i = tcx.hir().expect_variant(variant_i_hir_id);
             let i_span = match variant_i.node.disr_expr {
-                Some(ref expr) => tcx.hir().span(expr.id),
-                None => tcx.hir().span(variant_i_node_id)
+                Some(ref expr) => tcx.hir().span_by_hir_id(expr.hir_id),
+                None => tcx.hir().span_by_hir_id(variant_i_hir_id)
             };
             let span = match v.node.disr_expr {
-                Some(ref expr) => tcx.hir().span(expr.id),
+                Some(ref expr) => tcx.hir().span_by_hir_id(expr.hir_id),
                 None => v.span
             };
             struct_span_err!(tcx.sess, span, E0081,
@@ -4597,7 +4597,7 @@
                 if element_ty.references_error() {
                     tcx.types.err
                 } else if let Ok(count) = count {
-                    tcx.mk_ty(ty::Array(t, tcx.intern_lazy_const(ty::LazyConst::Evaluated(count))))
+                    tcx.mk_ty(ty::Array(t, tcx.mk_lazy_const(ty::LazyConst::Evaluated(count))))
                 } else {
                     tcx.types.err
                 }
@@ -5703,8 +5703,8 @@
     });
     for (&used, param) in types_used.iter().zip(types) {
         if !used {
-            let id = tcx.hir().as_local_node_id(param.def_id).unwrap();
-            let span = tcx.hir().span(id);
+            let id = tcx.hir().as_local_hir_id(param.def_id).unwrap();
+            let span = tcx.hir().span_by_hir_id(id);
             struct_span_err!(tcx.sess, span, E0091, "type parameter `{}` is unused", param.name)
                 .span_label(span, "unused type parameter")
                 .emit();
diff --git a/src/librustc_typeck/check/upvar.rs b/src/librustc_typeck/check/upvar.rs
index ffd7c21..15ae016 100644
--- a/src/librustc_typeck/check/upvar.rs
+++ b/src/librustc_typeck/check/upvar.rs
@@ -650,6 +650,5 @@
 }
 
 fn var_name(tcx: TyCtxt, var_hir_id: hir::HirId) -> ast::Name {
-    let var_node_id = tcx.hir().hir_to_node_id(var_hir_id);
-    tcx.hir().name(var_node_id)
+    tcx.hir().name_by_hir_id(var_hir_id)
 }
diff --git a/src/librustc_typeck/check/wfcheck.rs b/src/librustc_typeck/check/wfcheck.rs
index 9788170..1206c8e 100644
--- a/src/librustc_typeck/check/wfcheck.rs
+++ b/src/librustc_typeck/check/wfcheck.rs
@@ -62,11 +62,11 @@
 /// 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<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) {
-    let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
-    let item = tcx.hir().expect_item(node_id);
+    let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    let item = tcx.hir().expect_item_by_hir_id(hir_id);
 
-    debug!("check_item_well_formed(it.id={}, it.name={})",
-           item.id,
+    debug!("check_item_well_formed(it.hir_id={:?}, it.name={})",
+           item.hir_id,
            tcx.item_path_str(def_id));
 
     match item.node {
@@ -88,7 +88,7 @@
         // won't be allowed unless there's an *explicit* implementation of `Send`
         // for `T`
         hir::ItemKind::Impl(_, polarity, defaultness, _, ref trait_ref, ref self_ty, _) => {
-            let is_auto = tcx.impl_trait_ref(tcx.hir().local_def_id(item.id))
+            let is_auto = tcx.impl_trait_ref(tcx.hir().local_def_id_from_hir_id(item.hir_id))
                                 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
             if let (hir::Defaultness::Default { .. }, true) = (defaultness, is_auto) {
                 tcx.sess.span_err(item.span, "impls of auto traits cannot be default");
diff --git a/src/librustc_typeck/check/writeback.rs b/src/librustc_typeck/check/writeback.rs
index 238b087..29f5312 100644
--- a/src/librustc_typeck/check/writeback.rs
+++ b/src/librustc_typeck/check/writeback.rs
@@ -407,8 +407,7 @@
             if let ty::UserType::TypeOf(_, user_substs) = c_ty.value {
                 if self.rustc_dump_user_substs {
                     // This is a unit-testing mechanism.
-                    let node_id = self.tcx().hir().hir_to_node_id(hir_id);
-                    let span = self.tcx().hir().span(node_id);
+                    let span = self.tcx().hir().span_by_hir_id(hir_id);
                     // We need to buffer the errors in order to guarantee a consistent
                     // order when emitting them.
                     let err = self.tcx().sess.struct_span_err(
@@ -739,15 +738,14 @@
 
 impl Locatable for DefIndex {
     fn to_span(&self, tcx: &TyCtxt) -> Span {
-        let node_id = tcx.hir().def_index_to_node_id(*self);
-        tcx.hir().span(node_id)
+        let hir_id = tcx.hir().def_index_to_hir_id(*self);
+        tcx.hir().span_by_hir_id(hir_id)
     }
 }
 
 impl Locatable for hir::HirId {
     fn to_span(&self, tcx: &TyCtxt) -> Span {
-        let node_id = tcx.hir().hir_to_node_id(*self);
-        tcx.hir().span(node_id)
+        tcx.hir().span_by_hir_id(*self)
     }
 }
 
diff --git a/src/librustc_typeck/coherence/builtin.rs b/src/librustc_typeck/coherence/builtin.rs
index bd2373d..3ec08f2 100644
--- a/src/librustc_typeck/coherence/builtin.rs
+++ b/src/librustc_typeck/coherence/builtin.rs
@@ -76,7 +76,7 @@
 fn visit_implementation_of_copy<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, impl_did: DefId) {
     debug!("visit_implementation_of_copy: impl_did={:?}", impl_did);
 
-    let impl_node_id = if let Some(n) = tcx.hir().as_local_node_id(impl_did) {
+    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");
@@ -87,7 +87,7 @@
     debug!("visit_implementation_of_copy: self_type={:?} (bound)",
            self_type);
 
-    let span = tcx.hir().span(impl_node_id);
+    let span = tcx.hir().span_by_hir_id(impl_hir_id);
     let param_env = tcx.param_env(impl_did);
     assert!(!self_type.has_escaping_bound_vars());
 
@@ -97,7 +97,7 @@
     match param_env.can_type_implement_copy(tcx, self_type) {
         Ok(()) => {}
         Err(CopyImplementationError::InfrigingFields(fields)) => {
-            let item = tcx.hir().expect_item(impl_node_id);
+            let item = tcx.hir().expect_item_by_hir_id(impl_hir_id);
             let span = if let ItemKind::Impl(.., Some(ref tr), _, _) = item.node {
                 tr.path.span
             } else {
@@ -114,7 +114,7 @@
             err.emit()
         }
         Err(CopyImplementationError::NotAnAdt) => {
-            let item = tcx.hir().expect_item(impl_node_id);
+            let item = tcx.hir().expect_item_by_hir_id(impl_hir_id);
             let span = if let ItemKind::Impl(.., ref ty, _) = item.node {
                 ty.span
             } else {
diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs
index 9dc74c5..f5e5067 100644
--- a/src/librustc_typeck/collect.rs
+++ b/src/librustc_typeck/collect.rs
@@ -737,8 +737,8 @@
 }
 
 fn trait_def<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::TraitDef {
-    let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
-    let item = tcx.hir().expect_item(node_id);
+    let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    let item = tcx.hir().expect_item_by_hir_id(hir_id);
 
     let (is_auto, unsafety) = match item.node {
         hir::ItemKind::Trait(is_auto, unsafety, ..) => (is_auto == hir::IsAuto::Yes, unsafety),
@@ -1509,8 +1509,8 @@
 ) -> Option<ty::TraitRef<'tcx>> {
     let icx = ItemCtxt::new(tcx, def_id);
 
-    let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
-    match tcx.hir().expect_item(node_id).node {
+    let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    match tcx.hir().expect_item_by_hir_id(hir_id).node {
         hir::ItemKind::Impl(.., ref opt_trait_ref, _, _) => {
             opt_trait_ref.as_ref().map(|ast_trait_ref| {
                 let selfty = tcx.type_of(def_id);
@@ -1522,8 +1522,8 @@
 }
 
 fn impl_polarity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> hir::ImplPolarity {
-    let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
-    match tcx.hir().expect_item(node_id).node {
+    let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
+    match tcx.hir().expect_item_by_hir_id(hir_id).node {
         hir::ItemKind::Impl(_, polarity, ..) => polarity,
         ref item => bug!("impl_polarity: {:?} not an impl", item),
     }
diff --git a/src/librustc_typeck/diagnostics.rs b/src/librustc_typeck/diagnostics.rs
index 3ed09df..e6533ac 100644
--- a/src/librustc_typeck/diagnostics.rs
+++ b/src/librustc_typeck/diagnostics.rs
@@ -348,13 +348,14 @@
 "##,
 
 E0044: r##"
-You can't use type parameters on foreign items. Example of erroneous code:
+You can't use type or const parameters on foreign items.
+Example of erroneous code:
 
 ```compile_fail,E0044
 extern { fn some_func<T>(x: T); }
 ```
 
-To fix this, replace the type parameter with the specializations that you
+To fix this, replace the generic parameter with the specializations that you
 need:
 
 ```
diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs
index d5e870b..8d77310 100644
--- a/src/librustc_typeck/lib.rs
+++ b/src/librustc_typeck/lib.rs
@@ -55,9 +55,7 @@
 
 */
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-      html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-      html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 
 #![allow(non_camel_case_types)]
 
diff --git a/src/librustc_typeck/variance/mod.rs b/src/librustc_typeck/variance/mod.rs
index afb6a68..3474227 100644
--- a/src/librustc_typeck/variance/mod.rs
+++ b/src/librustc_typeck/variance/mod.rs
@@ -46,12 +46,12 @@
 
 fn variances_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId)
                           -> Lrc<Vec<ty::Variance>> {
-    let id = tcx.hir().as_local_node_id(item_def_id).expect("expected local def-id");
+    let id = tcx.hir().as_local_hir_id(item_def_id).expect("expected local def-id");
     let unsupported = || {
         // Variance not relevant.
-        span_bug!(tcx.hir().span(id), "asked to compute variance for wrong kind of item")
+        span_bug!(tcx.hir().span_by_hir_id(id), "asked to compute variance for wrong kind of item")
     };
-    match tcx.hir().get(id) {
+    match tcx.hir().get_by_hir_id(id) {
         Node::Item(item) => match item.node {
             hir::ItemKind::Enum(..) |
             hir::ItemKind::Struct(..) |
diff --git a/src/librustdoc/Cargo.toml b/src/librustdoc/Cargo.toml
index 4b42188..20d5e67 100644
--- a/src/librustdoc/Cargo.toml
+++ b/src/librustdoc/Cargo.toml
@@ -9,6 +9,6 @@
 
 [dependencies]
 pulldown-cmark = { version = "0.1.2", default-features = false }
-minifier = "0.0.26"
+minifier = "0.0.28"
 tempfile = "3"
 parking_lot = "0.6.4"
diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs
index bd05255..b0bb033 100644
--- a/src/librustdoc/clean/mod.rs
+++ b/src/librustdoc/clean/mod.rs
@@ -517,6 +517,7 @@
     StaticItem(Static),
     ConstantItem(Constant),
     TraitItem(Trait),
+    TraitAliasItem(TraitAlias),
     ImplItem(Impl),
     /// A method signature only. Used for required methods in traits (ie,
     /// non-default-methods).
@@ -554,6 +555,7 @@
             ItemEnum::TyMethodItem(ref i) => &i.generics,
             ItemEnum::MethodItem(ref i) => &i.generics,
             ItemEnum::ForeignFunctionItem(ref f) => &f.generics,
+            ItemEnum::TraitAliasItem(ref ta) => &ta.generics,
             _ => return None,
         })
     }
@@ -603,6 +605,7 @@
         items.extend(self.impls.iter().flat_map(|x| x.clean(cx)));
         items.extend(self.macros.iter().map(|x| x.clean(cx)));
         items.extend(self.proc_macros.iter().map(|x| x.clean(cx)));
+        items.extend(self.trait_aliases.iter().map(|x| x.clean(cx)));
 
         // determine if we should display the inner contents or
         // the outer `mod` item for the source code.
@@ -1724,6 +1727,30 @@
     pub fn self_type(&self) -> Option<SelfTy> {
         self.inputs.values.get(0).and_then(|v| v.to_self())
     }
+
+    /// Returns the sugared return type for an async function.
+    ///
+    /// For example, if the return type is `impl std::future::Future<Output = i32>`, this function
+    /// will return `i32`.
+    ///
+    /// # Panics
+    ///
+    /// This function will panic if the return type does not match the expected sugaring for async
+    /// functions.
+    pub fn sugared_async_return_type(&self) -> FunctionRetTy {
+        match &self.output {
+            FunctionRetTy::Return(Type::ImplTrait(bounds)) => {
+                match &bounds[0] {
+                    GenericBound::TraitBound(PolyTrait { trait_, .. }, ..) => {
+                        let bindings = trait_.bindings().unwrap();
+                        FunctionRetTy::Return(bindings[0].ty.clone())
+                    }
+                    _ => panic!("unexpected desugaring of async function"),
+                }
+            }
+            _ => panic!("unexpected desugaring of async function"),
+        }
+    }
 }
 
 #[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Debug, Hash)]
@@ -1885,13 +1912,38 @@
                 items: self.items.clean(cx),
                 generics: self.generics.clean(cx),
                 bounds: self.bounds.clean(cx),
-                is_spotlight: is_spotlight,
+                is_spotlight,
                 is_auto: self.is_auto.clean(cx),
             }),
         }
     }
 }
 
+#[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
+pub struct TraitAlias {
+    pub generics: Generics,
+    pub bounds: Vec<GenericBound>,
+}
+
+impl Clean<Item> for doctree::TraitAlias {
+    fn clean(&self, cx: &DocContext) -> Item {
+        let attrs = self.attrs.clean(cx);
+        Item {
+            name: Some(self.name.clean(cx)),
+            attrs,
+            source: self.whence.clean(cx),
+            def_id: cx.tcx.hir().local_def_id(self.id),
+            visibility: self.vis.clean(cx),
+            stability: self.stab.clean(cx),
+            deprecation: self.depr.clean(cx),
+            inner: TraitAliasItem(TraitAlias {
+                generics: self.generics.clean(cx),
+                bounds: self.bounds.clean(cx),
+            }),
+        }
+    }
+}
+
 impl Clean<bool> for hir::IsAuto {
     fn clean(&self, _: &DocContext) -> bool {
         match *self {
@@ -2223,6 +2275,7 @@
     Macro,
     Attr,
     Derive,
+    TraitAlias,
 }
 
 pub trait GetDefId {
@@ -2282,6 +2335,21 @@
             _ => None,
         }
     }
+
+    pub fn bindings(&self) -> Option<&[TypeBinding]> {
+        match *self {
+            ResolvedPath { ref path, .. } => {
+                path.segments.last().and_then(|seg| {
+                    if let GenericArgs::AngleBracketed { ref bindings, .. } = seg.args {
+                        Some(&**bindings)
+                    } else {
+                        None
+                    }
+                })
+            }
+            _ => None
+        }
+    }
 }
 
 impl GetDefId for Type {
@@ -3819,10 +3887,9 @@
             MacroKind::Derive => (i, TypeKind::Derive),
             MacroKind::ProcMacroStub => unreachable!(),
         },
+        Def::TraitAlias(i) => (i, TypeKind::TraitAlias),
         Def::SelfTy(Some(def_id), _) => (def_id, TypeKind::Trait),
-        Def::SelfTy(_, Some(impl_def_id)) => {
-            return impl_def_id
-        }
+        Def::SelfTy(_, Some(impl_def_id)) => return impl_def_id,
         _ => return def.def_id()
     };
     if did.is_local() { return did }
diff --git a/src/librustdoc/doctree.rs b/src/librustdoc/doctree.rs
index cc27da7..e845838 100644
--- a/src/librustdoc/doctree.rs
+++ b/src/librustdoc/doctree.rs
@@ -38,6 +38,7 @@
     pub foreigns: Vec<hir::ForeignMod>,
     pub macros: Vec<Macro>,
     pub proc_macros: Vec<ProcMacro>,
+    pub trait_aliases: Vec<TraitAlias>,
     pub is_crate: bool,
 }
 
@@ -53,21 +54,22 @@
             where_inner: syntax_pos::DUMMY_SP,
             attrs      : hir::HirVec::new(),
             extern_crates: Vec::new(),
-            imports    : Vec::new(),
-            structs    : Vec::new(),
-            unions     : Vec::new(),
-            enums      : Vec::new(),
-            fns        : Vec::new(),
-            mods       : Vec::new(),
-            typedefs   : Vec::new(),
-            existentials: Vec::new(),
-            statics    : Vec::new(),
-            constants  : Vec::new(),
-            traits     : Vec::new(),
-            impls      : Vec::new(),
-            foreigns   : Vec::new(),
-            macros     : Vec::new(),
-            proc_macros: Vec::new(),
+            imports    :   Vec::new(),
+            structs    :   Vec::new(),
+            unions     :   Vec::new(),
+            enums      :   Vec::new(),
+            fns        :   Vec::new(),
+            mods       :   Vec::new(),
+            typedefs   :   Vec::new(),
+            existentials:  Vec::new(),
+            statics    :   Vec::new(),
+            constants  :   Vec::new(),
+            traits     :   Vec::new(),
+            impls      :   Vec::new(),
+            foreigns   :   Vec::new(),
+            macros     :   Vec::new(),
+            proc_macros:   Vec::new(),
+            trait_aliases: Vec::new(),
             is_crate   : false,
         }
     }
@@ -208,6 +210,18 @@
     pub depr: Option<attr::Deprecation>,
 }
 
+pub struct TraitAlias {
+    pub name: Name,
+    pub generics: hir::Generics,
+    pub bounds: hir::HirVec<hir::GenericBound>,
+    pub attrs: hir::HirVec<ast::Attribute>,
+    pub id: ast::NodeId,
+    pub whence: Span,
+    pub vis: hir::Visibility,
+    pub stab: Option<attr::Stability>,
+    pub depr: Option<attr::Deprecation>,
+}
+
 #[derive(Debug)]
 pub struct Impl {
     pub unsafety: hir::Unsafety,
diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs
index 5a3e698..c03e679 100644
--- a/src/librustdoc/html/format.rs
+++ b/src/librustdoc/html/format.rs
@@ -5,6 +5,7 @@
 //! assume that HTML output is desired, although it may be possible to redesign
 //! them in the future to instead emit any format desired.
 
+use std::borrow::Cow;
 use std::fmt;
 
 use rustc::hir::def_id::DefId;
@@ -44,14 +45,16 @@
 pub struct CommaSep<'a, T: 'a>(pub &'a [T]);
 pub struct AbiSpace(pub Abi);
 
-/// Wrapper struct for properly emitting a method declaration.
-pub struct Method<'a> {
+/// Wrapper struct for properly emitting a function or method declaration.
+pub struct Function<'a> {
     /// The declaration to emit.
     pub decl: &'a clean::FnDecl,
     /// The length of the function's "name", used to determine line-wrapping.
     pub name_len: usize,
     /// The number of spaces to indent each successive line with, if line-wrapping is necessary.
     pub indent: usize,
+    /// Whether the function is async or not.
+    pub asyncness: hir::IsAsync,
 }
 
 /// Wrapper struct for emitting a where clause from Generics.
@@ -829,9 +832,9 @@
     }
 }
 
-impl<'a> fmt::Display for Method<'a> {
+impl<'a> fmt::Display for Function<'a> {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        let &Method { decl, name_len, indent } = self;
+        let &Function { decl, name_len, indent, asyncness } = self;
         let amp = if f.alternate() { "&" } else { "&amp;" };
         let mut args = String::new();
         let mut args_plain = String::new();
@@ -891,11 +894,17 @@
             args_plain.push_str(", ...");
         }
 
-        let arrow_plain = format!("{:#}", decl.output);
-        let arrow = if f.alternate() {
-            format!("{:#}", decl.output)
+        let output = if let hir::IsAsync::Async = asyncness {
+            Cow::Owned(decl.sugared_async_return_type())
         } else {
-            decl.output.to_string()
+            Cow::Borrowed(&decl.output)
+        };
+
+        let arrow_plain = format!("{:#}", &output);
+        let arrow = if f.alternate() {
+            format!("{:#}", &output)
+        } else {
+            output.to_string()
         };
 
         let pad = " ".repeat(name_len);
diff --git a/src/librustdoc/html/item_type.rs b/src/librustdoc/html/item_type.rs
index e20d385..8a3b548 100644
--- a/src/librustdoc/html/item_type.rs
+++ b/src/librustdoc/html/item_type.rs
@@ -42,6 +42,7 @@
     Existential     = 22,
     ProcAttribute   = 23,
     ProcDerive      = 24,
+    TraitAlias      = 25,
 }
 
 
@@ -86,6 +87,7 @@
             clean::AssociatedTypeItem(..)  => ItemType::AssociatedType,
             clean::ForeignTypeItem         => ItemType::ForeignType,
             clean::KeywordItem(..)         => ItemType::Keyword,
+            clean::TraitAliasItem(..)      => ItemType::TraitAlias,
             clean::ProcMacroItem(ref mac)  => match mac.kind {
                 MacroKind::Bang            => ItemType::Macro,
                 MacroKind::Attr            => ItemType::ProcAttribute,
@@ -100,20 +102,21 @@
 impl From<clean::TypeKind> for ItemType {
     fn from(kind: clean::TypeKind) -> ItemType {
         match kind {
-            clean::TypeKind::Struct   => ItemType::Struct,
-            clean::TypeKind::Union    => ItemType::Union,
-            clean::TypeKind::Enum     => ItemType::Enum,
-            clean::TypeKind::Function => ItemType::Function,
-            clean::TypeKind::Trait    => ItemType::Trait,
-            clean::TypeKind::Module   => ItemType::Module,
-            clean::TypeKind::Static   => ItemType::Static,
-            clean::TypeKind::Const    => ItemType::Constant,
-            clean::TypeKind::Variant  => ItemType::Variant,
-            clean::TypeKind::Typedef  => ItemType::Typedef,
-            clean::TypeKind::Foreign  => ItemType::ForeignType,
-            clean::TypeKind::Macro    => ItemType::Macro,
-            clean::TypeKind::Attr     => ItemType::ProcAttribute,
-            clean::TypeKind::Derive   => ItemType::ProcDerive,
+            clean::TypeKind::Struct     => ItemType::Struct,
+            clean::TypeKind::Union      => ItemType::Union,
+            clean::TypeKind::Enum       => ItemType::Enum,
+            clean::TypeKind::Function   => ItemType::Function,
+            clean::TypeKind::Trait      => ItemType::Trait,
+            clean::TypeKind::Module     => ItemType::Module,
+            clean::TypeKind::Static     => ItemType::Static,
+            clean::TypeKind::Const      => ItemType::Constant,
+            clean::TypeKind::Variant    => ItemType::Variant,
+            clean::TypeKind::Typedef    => ItemType::Typedef,
+            clean::TypeKind::Foreign    => ItemType::ForeignType,
+            clean::TypeKind::Macro      => ItemType::Macro,
+            clean::TypeKind::Attr       => ItemType::ProcAttribute,
+            clean::TypeKind::Derive     => ItemType::ProcDerive,
+            clean::TypeKind::TraitAlias => ItemType::TraitAlias,
         }
     }
 }
@@ -146,6 +149,7 @@
             ItemType::Existential     => "existential",
             ItemType::ProcAttribute   => "attr",
             ItemType::ProcDerive      => "derive",
+            ItemType::TraitAlias      => "traitalias",
         }
     }
 
@@ -160,6 +164,7 @@
             ItemType::Primitive |
             ItemType::AssociatedType |
             ItemType::Existential |
+            ItemType::TraitAlias |
             ItemType::ForeignType => NameSpace::Type,
 
             ItemType::ExternCrate |
diff --git a/src/librustdoc/html/layout.rs b/src/librustdoc/html/layout.rs
index c34dcbb..b444993 100644
--- a/src/librustdoc/html/layout.rs
+++ b/src/librustdoc/html/layout.rs
@@ -4,6 +4,8 @@
 
 use externalfiles::ExternalHtml;
 
+use html::render::SlashChecker;
+
 #[derive(Clone)]
 pub struct Layout {
     pub logo: String,
@@ -176,16 +178,22 @@
     static_root_path = static_root_path,
     root_path = page.root_path,
     css_class = page.css_class,
-    logo      = if layout.logo.is_empty() {
-        format!("<a href='{}{}/index.html'>\
-                 <img src='{static_root_path}rust-logo{suffix}.png' alt='logo' width='100'></a>",
-                static_root_path=static_root_path,
-                suffix=page.resource_suffix)
-    } else {
-        format!("<a href='{}{}/index.html'>\
-                 <img src='{}' alt='logo' width='100'></a>",
-                page.root_path, layout.krate,
-                layout.logo)
+    logo      = {
+        let p = format!("{}{}", page.root_path, layout.krate);
+        let p = SlashChecker(&p);
+        if layout.logo.is_empty() {
+            format!("<a href='{path}index.html'>\
+                     <img src='{static_root_path}rust-logo{suffix}.png' \
+                          alt='logo' width='100'></a>",
+                    path=p,
+                    static_root_path=static_root_path,
+                    suffix=page.resource_suffix)
+        } else {
+            format!("<a href='{}index.html'>\
+                     <img src='{}' alt='logo' width='100'></a>",
+                    p,
+                    layout.logo)
+        }
     },
     title     = page.title,
     description = page.description,
diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs
index 86fb514..3a8e8a6 100644
--- a/src/librustdoc/html/render.rs
+++ b/src/librustdoc/html/render.rs
@@ -62,7 +62,7 @@
 use html::escape::Escape;
 use html::format::{AsyncSpace, ConstnessSpace};
 use html::format::{GenericBounds, WhereClause, href, AbiSpace};
-use html::format::{VisSpace, Method, UnsafetySpace, MutableSpace};
+use html::format::{VisSpace, Function, UnsafetySpace, MutableSpace};
 use html::format::fmt_impl_for_trait_page;
 use html::item_type::ItemType;
 use html::markdown::{self, Markdown, MarkdownHtml, MarkdownSummaryLine, ErrorCodes, IdMap};
@@ -73,6 +73,18 @@
 /// A pair of name and its optional document.
 pub type NameDoc = (String, Option<String>);
 
+pub struct SlashChecker<'a>(pub &'a str);
+
+impl<'a> Display for SlashChecker<'a> {
+    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+        if !self.0.ends_with("/") && !self.0.is_empty() {
+            write!(f, "{}/", self.0)
+        } else {
+            write!(f, "{}", self.0)
+        }
+    }
+}
+
 /// Major driving force in all rustdoc rendering. This contains information
 /// about where in the tree-like hierarchy rendering is occurring and controls
 /// how the current page is being rendered.
@@ -939,7 +951,7 @@
         if path.exists() {
             for line in BufReader::new(File::open(path)?).lines() {
                 let line = line?;
-                if for_search_index && line.starts_with("var r_") {
+                if for_search_index && line.starts_with("var R") {
                     variables.push(line.clone());
                     // We need to check if the crate name has been put into a variable as well.
                     let tokens = js::simple_minify(&line).apply(js::clean_tokens);
@@ -1140,7 +1152,8 @@
                                   krates
                                     .iter()
                                     .map(|s| {
-                                        format!("<li><a href=\"{}/index.html\">{}</li>", s, s)
+                                        format!("<li><a href=\"{}index.html\">{}</li>",
+                                                SlashChecker(s), s)
                                     })
                                     .collect::<String>());
             try_err!(layout::render(&mut w, &cx.shared.layout,
@@ -1299,8 +1312,9 @@
                               })
                               .apply(|f| {
                                   // We add a backline after the newly created variables.
-                                  minifier::js::aggregate_strings_with_separation(
+                                  minifier::js::aggregate_strings_into_array_with_separation(
                                       f,
+                                      "R",
                                       Token::Char(ReservedChar::Backline),
                                   )
                               })
@@ -1822,6 +1836,7 @@
     keywords: FxHashSet<ItemEntry>,
     attributes: FxHashSet<ItemEntry>,
     derives: FxHashSet<ItemEntry>,
+    trait_aliases: FxHashSet<ItemEntry>,
 }
 
 impl AllTypes {
@@ -1842,6 +1857,7 @@
             keywords: new_set(100),
             attributes: new_set(100),
             derives: new_set(100),
+            trait_aliases: new_set(100),
         }
     }
 
@@ -1865,6 +1881,7 @@
                 ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)),
                 ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)),
                 ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)),
+                ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)),
                 _ => true,
             };
         }
@@ -1908,6 +1925,7 @@
         print_entries(f, &self.derives, "Derive Macros", "derives")?;
         print_entries(f, &self.functions, "Functions", "functions")?;
         print_entries(f, &self.typedefs, "Typedefs", "typedefs")?;
+        print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases")?;
         print_entries(f, &self.existentials, "Existentials", "existentials")?;
         print_entries(f, &self.statics, "Statics", "statics")?;
         print_entries(f, &self.constants, "Constants", "constants")
@@ -2074,8 +2092,7 @@
         let mut themes = self.shared.themes.clone();
         let sidebar = "<p class='location'>Settings</p><div class='sidebar-elems'></div>";
         themes.push(PathBuf::from("settings.css"));
-        let mut layout = self.shared.layout.clone();
-        layout.krate = String::new();
+        let layout = self.shared.layout.clone();
         try_err!(layout::render(&mut w, &layout,
                                 &page, &sidebar, &settings,
                                 self.shared.css_file_extension.is_some(),
@@ -2406,6 +2423,7 @@
             clean::ForeignTypeItem => write!(fmt, "Foreign Type ")?,
             clean::KeywordItem(..) => write!(fmt, "Keyword ")?,
             clean::ExistentialItem(..) => write!(fmt, "Existential Type ")?,
+            clean::TraitAliasItem(..) => write!(fmt, "Trait Alias ")?,
             _ => {
                 // We don't generate pages for any other type.
                 unreachable!();
@@ -2444,6 +2462,7 @@
             clean::ForeignTypeItem => item_foreign_type(fmt, self.cx, self.item),
             clean::KeywordItem(ref k) => item_keyword(fmt, self.cx, self.item, k),
             clean::ExistentialItem(ref e, _) => item_existential(fmt, self.cx, self.item, e),
+            clean::TraitAliasItem(ref ta) => item_trait_alias(fmt, self.cx, self.item, ta),
             _ => {
                 // We don't generate pages for any other type.
                 unreachable!();
@@ -2454,7 +2473,7 @@
 
 fn item_path(ty: ItemType, name: &str) -> String {
     match ty {
-        ItemType::Module => format!("{}/index.html", name),
+        ItemType::Module => format!("{}index.html", SlashChecker(name)),
         _ => format!("{}.{}.html", ty.css_class(), name),
     }
 }
@@ -2798,9 +2817,13 @@
 fn stability_tags(item: &clean::Item) -> String {
     let mut tags = String::new();
 
+    fn tag_html(class: &str, contents: &str) -> String {
+        format!(r#"<span class="stab {}">{}</span>"#, class, contents)
+    }
+
     // The trailing space after each tag is to space it properly against the rest of the docs.
     if item.deprecation().is_some() {
-        tags.push_str("[<div class='stab deprecated'>Deprecated</div>] ");
+        tags += &tag_html("deprecated", "Deprecated");
     }
 
     if let Some(stab) = item
@@ -2809,17 +2832,14 @@
         .filter(|s| s.level == stability::Unstable)
     {
         if stab.feature.as_ref().map(|s| &**s) == Some("rustc_private") {
-            tags.push_str("[<div class='stab internal'>Internal</div>] ");
+            tags += &tag_html("internal", "Internal");
         } else {
-            tags.push_str("[<div class='stab unstable'>Experimental</div>] ");
+            tags += &tag_html("unstable", "Experimental");
         }
     }
 
     if let Some(ref cfg) = item.attrs.cfg {
-        tags.push_str(&format!(
-            "[<div class='stab portability'>{}</div>] ",
-            cfg.render_short_html()
-        ));
+        tags += &tag_html("portability", &cfg.render_short_html());
     }
 
     tags
@@ -2963,10 +2983,11 @@
            name = it.name.as_ref().unwrap(),
            generics = f.generics,
            where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true },
-           decl = Method {
+           decl = Function {
               decl: &f.decl,
               name_len,
               indent: 0,
+              asyncness: f.header.asyncness,
            })?;
     document(w, cx, it)
 }
@@ -3000,23 +3021,17 @@
     Ok(())
 }
 
-fn bounds(t_bounds: &[clean::GenericBound]) -> String {
+fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool) -> String {
     let mut bounds = String::new();
-    let mut bounds_plain = String::new();
     if !t_bounds.is_empty() {
-        if !bounds.is_empty() {
-            bounds.push(' ');
-            bounds_plain.push(' ');
+        if !trait_alias {
+            bounds.push_str(": ");
         }
-        bounds.push_str(": ");
-        bounds_plain.push_str(": ");
         for (i, p) in t_bounds.iter().enumerate() {
             if i > 0 {
                 bounds.push_str(" + ");
-                bounds_plain.push_str(" + ");
             }
             bounds.push_str(&(*p).to_string());
-            bounds_plain.push_str(&format!("{:#}", *p));
         }
     }
     bounds
@@ -3036,7 +3051,7 @@
     it: &clean::Item,
     t: &clean::Trait,
 ) -> fmt::Result {
-    let bounds = bounds(&t.bounds);
+    let bounds = bounds(&t.bounds, false);
     let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>();
     let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>();
     let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>();
@@ -3410,10 +3425,11 @@
                href = href,
                name = name,
                generics = *g,
-               decl = Method {
+               decl = Function {
                    decl: d,
                    name_len: head_len,
                    indent,
+                   asyncness: header.asyncness,
                },
                where_clause = WhereClause {
                    gens: g,
@@ -3483,10 +3499,6 @@
                        ns_id = ns_id,
                        name = field.name.as_ref().unwrap(),
                        ty = ty)?;
-                if let Some(stability_class) = field.stability_class() {
-                    write!(w, "<span class='stab {stab}'></span>",
-                        stab = stability_class)?;
-                }
                 document(w, cx, field)?;
             }
         }
@@ -4270,7 +4282,26 @@
            it.name.as_ref().unwrap(),
            t.generics,
            where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true },
-           bounds = bounds(&t.bounds))?;
+           bounds = bounds(&t.bounds, false))?;
+
+    document(w, cx, it)?;
+
+    // Render any items associated directly to this alias, as otherwise they
+    // won't be visible anywhere in the docs. It would be nice to also show
+    // associated items from the aliased type (see discussion in #32077), but
+    // we need #14072 to make sense of the generics.
+    render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All)
+}
+
+fn item_trait_alias(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
+                    t: &clean::TraitAlias) -> fmt::Result {
+    write!(w, "<pre class='rust trait-alias'>")?;
+    render_attributes(w, it)?;
+    write!(w, "trait {}{}{} = {};</pre>",
+           it.name.as_ref().unwrap(),
+           t.generics,
+           WhereClause { gens: &t.generics, indent: 0, end_newline: true },
+           bounds(&t.bounds, true))?;
 
     document(w, cx, it)?;
 
@@ -4470,15 +4501,17 @@
 
         {
             let used_links_bor = Rc::new(RefCell::new(&mut used_links));
-            let ret = v.iter()
-                       .filter(|i| i.inner_impl().trait_.is_none())
-                       .flat_map(move |i| get_methods(i.inner_impl(),
-                                                      false,
-                                                      &mut used_links_bor.borrow_mut()))
-                       .collect::<String>();
+            let mut ret = v.iter()
+                           .filter(|i| i.inner_impl().trait_.is_none())
+                           .flat_map(move |i| get_methods(i.inner_impl(),
+                                                          false,
+                                                          &mut used_links_bor.borrow_mut()))
+                           .collect::<Vec<_>>();
+            // We want links' order to be reproducible so we don't use unstable sort.
+            ret.sort();
             if !ret.is_empty() {
                 out.push_str(&format!("<a class=\"sidebar-title\" href=\"#methods\">Methods\
-                                       </a><div class=\"sidebar-links\">{}</div>", ret));
+                                       </a><div class=\"sidebar-links\">{}</div>", ret.join("")));
             }
         }
 
@@ -4502,40 +4535,47 @@
                                                      impl_.inner_impl().trait_.as_ref().unwrap())),
                                               Escape(&format!("{:#}", target))));
                         out.push_str("</a>");
-                        let ret = impls.iter()
-                                       .filter(|i| i.inner_impl().trait_.is_none())
-                                       .flat_map(|i| get_methods(i.inner_impl(),
-                                                                 true,
-                                                                 &mut used_links))
-                                       .collect::<String>();
-                        out.push_str(&format!("<div class=\"sidebar-links\">{}</div>", ret));
+                        let mut ret = impls.iter()
+                                           .filter(|i| i.inner_impl().trait_.is_none())
+                                           .flat_map(|i| get_methods(i.inner_impl(),
+                                                                     true,
+                                                                     &mut used_links))
+                                           .collect::<Vec<_>>();
+                        // We want links' order to be reproducible so we don't use unstable sort.
+                        ret.sort();
+                        if !ret.is_empty() {
+                            out.push_str(&format!("<div class=\"sidebar-links\">{}</div>",
+                                                  ret.join("")));
+                        }
                     }
                 }
             }
             let format_impls = |impls: Vec<&Impl>| {
                 let mut links = FxHashSet::default();
 
-                impls.iter()
-                     .filter_map(|i| {
-                         let is_negative_impl = is_negative_impl(i.inner_impl());
-                         if let Some(ref i) = i.inner_impl().trait_ {
-                             let i_display = format!("{:#}", i);
-                             let out = Escape(&i_display);
-                             let encoded = small_url_encode(&format!("{:#}", i));
-                             let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
-                                                     encoded,
-                                                     if is_negative_impl { "!" } else { "" },
-                                                     out);
-                             if links.insert(generated.clone()) {
-                                 Some(generated)
-                             } else {
-                                 None
-                             }
-                         } else {
-                             None
-                         }
-                     })
-                     .collect::<String>()
+                let mut ret = impls.iter()
+                    .filter_map(|i| {
+                        let is_negative_impl = is_negative_impl(i.inner_impl());
+                        if let Some(ref i) = i.inner_impl().trait_ {
+                            let i_display = format!("{:#}", i);
+                            let out = Escape(&i_display);
+                            let encoded = small_url_encode(&format!("{:#}", i));
+                            let generated = format!("<a href=\"#impl-{}\">{}{}</a>",
+                                                    encoded,
+                                                    if is_negative_impl { "!" } else { "" },
+                                                    out);
+                            if links.insert(generated.clone()) {
+                                Some(generated)
+                            } else {
+                                None
+                            }
+                        } else {
+                            None
+                        }
+                    })
+                    .collect::<Vec<String>>();
+                ret.sort();
+                ret.join("")
             };
 
             let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = v
@@ -4637,29 +4677,29 @@
                       }
                   })
                   .collect::<String>();
-    let required = t.items
-                    .iter()
-                    .filter_map(|m| {
-                        match m.name {
-                            Some(ref name) if m.is_ty_method() => {
-                                Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
-                                             name=name))
+    let mut required = t.items
+                        .iter()
+                        .filter_map(|m| {
+                            match m.name {
+                                Some(ref name) if m.is_ty_method() => {
+                                    Some(format!("<a href=\"#tymethod.{name}\">{name}</a>",
+                                                 name=name))
+                                }
+                                _ => None,
                             }
-                            _ => None,
-                        }
-                    })
-                    .collect::<String>();
-    let provided = t.items
-                    .iter()
-                    .filter_map(|m| {
-                        match m.name {
-                            Some(ref name) if m.is_method() => {
-                                Some(format!("<a href=\"#method.{name}\">{name}</a>", name=name))
+                        })
+                        .collect::<Vec<String>>();
+    let mut provided = t.items
+                        .iter()
+                        .filter_map(|m| {
+                            match m.name {
+                                Some(ref name) if m.is_method() => {
+                                    Some(format!("<a href=\"#method.{0}\">{0}</a>", name))
+                                }
+                                _ => None,
                             }
-                            _ => None,
-                        }
-                    })
-                    .collect::<String>();
+                        })
+                        .collect::<Vec<String>>();
 
     if !types.is_empty() {
         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#associated-types\">\
@@ -4672,38 +4712,41 @@
                                   consts));
     }
     if !required.is_empty() {
+        required.sort();
         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#required-methods\">\
                                    Required Methods</a><div class=\"sidebar-links\">{}</div>",
-                                  required));
+                                  required.join("")));
     }
     if !provided.is_empty() {
+        provided.sort();
         sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#provided-methods\">\
                                    Provided Methods</a><div class=\"sidebar-links\">{}</div>",
-                                  provided));
+                                  provided.join("")));
     }
 
     let c = cache();
 
     if let Some(implementors) = c.implementors.get(&it.def_id) {
-        let res = implementors.iter()
-                              .filter(|i| i.inner_impl().for_.def_id()
-                              .map_or(false, |d| !c.paths.contains_key(&d)))
-                              .filter_map(|i| {
-                                  match extract_for_impl_name(&i.impl_item) {
-                                      Some((ref name, ref url)) => {
-                                          Some(format!("<a href=\"#impl-{}\">{}</a>",
-                                                      small_url_encode(url),
-                                                      Escape(name)))
+        let mut res = implementors.iter()
+                                  .filter(|i| i.inner_impl().for_.def_id()
+                                  .map_or(false, |d| !c.paths.contains_key(&d)))
+                                  .filter_map(|i| {
+                                      match extract_for_impl_name(&i.impl_item) {
+                                          Some((ref name, ref url)) => {
+                                              Some(format!("<a href=\"#impl-{}\">{}</a>",
+                                                          small_url_encode(url),
+                                                          Escape(name)))
+                                          }
+                                          _ => None,
                                       }
-                                      _ => None,
-                                  }
-                              })
-                              .collect::<String>();
+                                  })
+                                  .collect::<Vec<String>>();
         if !res.is_empty() {
+            res.sort();
             sidebar.push_str(&format!("<a class=\"sidebar-title\" href=\"#foreign-impls\">\
                                        Implementations on Foreign Types</a><div \
                                        class=\"sidebar-links\">{}</div>",
-                                      res));
+                                      res.join("")));
         }
     }
 
@@ -4822,6 +4865,7 @@
         ItemType::Existential     => ("existentials", "Existentials"),
         ItemType::ProcAttribute   => ("attributes", "Attribute Macros"),
         ItemType::ProcDerive      => ("derives", "Derive Macros"),
+        ItemType::TraitAlias      => ("trait-aliases", "Trait aliases"),
     }
 }
 
diff --git a/src/librustdoc/html/static/main.js b/src/librustdoc/html/static/main.js
index 82604cc..840f943 100644
--- a/src/librustdoc/html/static/main.js
+++ b/src/librustdoc/html/static/main.js
@@ -68,7 +68,8 @@
                      "keyword",
                      "existential",
                      "attr",
-                     "derive"];
+                     "derive",
+                     "traitalias"];
 
     var search_input = document.getElementsByClassName("search-input")[0];
 
@@ -79,8 +80,6 @@
     // 2 for "In Return Types"
     var currentTab = 0;
 
-    var themesWidth = null;
-
     var titleBeforeSearch = document.title;
 
     function getPageId() {
@@ -150,8 +149,7 @@
     }
 
     function browserSupportsHistoryApi() {
-        return document.location.protocol != "file:" &&
-          window.history && typeof window.history.pushState === "function";
+        return window.history && typeof window.history.pushState === "function";
     }
 
     var main = document.getElementById("main");
@@ -241,7 +239,7 @@
         return String.fromCharCode(c);
     }
 
-    function displayHelp(display, ev) {
+    function displayHelp(display, ev, help) {
         if (display === true) {
             if (hasClass(help, "hidden")) {
                 ev.preventDefault();
@@ -259,7 +257,7 @@
         hideModal();
         var search = document.getElementById("search");
         if (hasClass(help, "hidden") === false) {
-            displayHelp(false, ev);
+            displayHelp(false, ev, help);
         } else if (hasClass(search, "hidden") === false) {
             ev.preventDefault();
             addClass(search, "hidden");
@@ -290,7 +288,7 @@
 
             case "s":
             case "S":
-                displayHelp(false, ev);
+                displayHelp(false, ev, help);
                 hideModal();
                 ev.preventDefault();
                 focusSearchBar();
@@ -305,7 +303,7 @@
             case "?":
                 if (ev.shiftKey) {
                     hideModal();
-                    displayHelp(true, ev);
+                    displayHelp(true, ev, help);
                 }
                 break;
             }
@@ -655,7 +653,7 @@
                                 return MAX_LEV_DISTANCE + 1;
                             }
                         }
-                        return lev_distance;//Math.ceil(total / done);
+                        return Math.ceil(total / done);
                     }
                 }
                 return MAX_LEV_DISTANCE + 1;
@@ -1787,6 +1785,7 @@
         block("type", "Type Definitions");
         block("foreigntype", "Foreign Types");
         block("keyword", "Keywords");
+        block("traitalias", "Trait Aliases");
     }
 
     window.initSidebarItems = initSidebarItems;
@@ -1887,12 +1886,30 @@
             updateLocalStorage("rustdoc-collapse", "true");
             addClass(innerToggle, "will-expand");
             onEveryMatchingChild(innerToggle, "inner", function(e) {
-                e.innerHTML = labelForToggleButton(true);
+                var parent = e.parentNode;
+                var superParent = null;
+
+                if (parent) {
+                    superParent = parent.parentNode;
+                }
+                if (!parent || !superParent || superParent.id !== "main" ||
+                    hasClass(parent, "impl") === false) {
+                    e.innerHTML = labelForToggleButton(true);
+                }
             });
             innerToggle.title = "expand all docs";
             if (fromAutoCollapse !== true) {
                 onEachLazy(document.getElementsByClassName("collapse-toggle"), function(e) {
-                    collapseDocs(e, "hide", pageId);
+                    var parent = e.parentNode;
+                    var superParent = null;
+
+                    if (parent) {
+                        superParent = parent.parentNode;
+                    }
+                    if (!parent || !superParent || superParent.id !== "main" ||
+                        hasClass(parent, "impl") === false) {
+                        collapseDocs(e, "hide", pageId);
+                    }
                 });
             }
         }
@@ -1918,9 +1935,9 @@
             };
         }
 
-        function implHider(addOrRemove) {
+        function implHider(addOrRemove, fullHide) {
             return function(n) {
-                var is_method = hasClass(n, "method");
+                var is_method = hasClass(n, "method") || fullHide;
                 if (is_method || hasClass(n, "type")) {
                     if (is_method === true) {
                         if (addOrRemove) {
@@ -1974,7 +1991,7 @@
                 }
             }
         } else {
-            // we are collapsing the impl block
+            // we are collapsing the impl block(s).
 
             var parentElem = toggle.parentNode;
             relatedDoc = parentElem;
@@ -1989,7 +2006,7 @@
                 return;
             }
 
-            // Hide all functions, but not associated types/consts
+            // Hide all functions, but not associated types/consts.
 
             if (mode === "toggle") {
                 if (hasClass(relatedDoc, "fns-now-collapsed") ||
@@ -2000,16 +2017,17 @@
                 }
             }
 
+            var dontApplyBlockRule = toggle.parentNode.parentNode.id !== "main";
             if (action === "show") {
                 removeClass(relatedDoc, "fns-now-collapsed");
                 removeClass(docblock, "hidden-by-usual-hider");
-                onEachLazy(toggle.childNodes, adjustToggle(false));
-                onEachLazy(relatedDoc.childNodes, implHider(false));
+                onEachLazy(toggle.childNodes, adjustToggle(false, dontApplyBlockRule));
+                onEachLazy(relatedDoc.childNodes, implHider(false, dontApplyBlockRule));
             } else if (action === "hide") {
                 addClass(relatedDoc, "fns-now-collapsed");
                 addClass(docblock, "hidden-by-usual-hider");
-                onEachLazy(toggle.childNodes, adjustToggle(true));
-                onEachLazy(relatedDoc.childNodes, implHider(true));
+                onEachLazy(toggle.childNodes, adjustToggle(true, dontApplyBlockRule));
+                onEachLazy(relatedDoc.childNodes, implHider(true, dontApplyBlockRule));
             }
         }
     }
@@ -2414,7 +2432,7 @@
             // for vertical layout (column-oriented flex layout for divs caused
             // errors in mobile browsers).
             if (e.tagName === "H2" || e.tagName === "H3") {
-                let nextTagName = e.nextElementSibling.tagName;
+                var nextTagName = e.nextElementSibling.tagName;
                 if (nextTagName == "H2" || nextTagName == "H3") {
                     e.nextElementSibling.style.display = "flex";
                 } else {
diff --git a/src/librustdoc/html/static/rustdoc.css b/src/librustdoc/html/static/rustdoc.css
index 3676549..4ec8637 100644
--- a/src/librustdoc/html/static/rustdoc.css
+++ b/src/librustdoc/html/static/rustdoc.css
@@ -767,11 +767,14 @@
 }
 
 .module-item .stab {
-	display: inline;
-	border-width: 0;
-	padding: 0;
-	margin: 0;
-	background: inherit !important;
+	border-radius: 3px;
+	display: inline-block;
+	font-size: 80%;
+	line-height: 1.2;
+	margin-bottom: 0;
+	margin-right: .3em;
+	padding: 2px;
+	vertical-align: text-bottom;
 }
 
 .module-item.unstable {
@@ -1570,5 +1573,6 @@
 }
 div.name.expand::before {
 	transform: rotate(90deg);
-	left: -14px;
+	left: -15px;
+	top: 2px;
 }
diff --git a/src/librustdoc/html/static/source-script.js b/src/librustdoc/html/static/source-script.js
index c5d6fa1..509c628 100644
--- a/src/librustdoc/html/static/source-script.js
+++ b/src/librustdoc/html/static/source-script.js
@@ -94,7 +94,7 @@
     inner1.style.position = "relative";
 
     var inner2 = document.createElement("div");
-    inner2.style.marginTop = "-2px";
+    inner2.style.paddingTop = "3px";
     if (getCurrentValue("rustdoc-source-sidebar-show") === "true") {
         inner2.innerText = "<";
     } else {
diff --git a/src/librustdoc/html/static/themes/dark.css b/src/librustdoc/html/static/themes/dark.css
index 6935ecd..333fe76 100644
--- a/src/librustdoc/html/static/themes/dark.css
+++ b/src/librustdoc/html/static/themes/dark.css
@@ -94,6 +94,7 @@
 }
 .content .highlighted a, .content .highlighted span { color: #eee !important; }
 .content .highlighted.trait { background-color: #013191; }
+.content .highlighted.traitalias { background-color: #013191; }
 .content .highlighted.mod,
 .content .highlighted.externcrate { background-color: #afc6e4; }
 .content .highlighted.mod { background-color: #803a1b; }
@@ -128,6 +129,7 @@
 .content span.externcrate,
 .content span.mod, .content a.mod, .block a.current.mod { color: #bda000; }
 .content span.trait, .content a.trait, .block a.current.trait { color: #b78cf2; }
+.content span.traitalias, .content a.traitalias, .block a.current.traitalias { color: #b397da; }
 .content span.fn, .content a.fn, .block a.current.fn,
 .content span.method, .content a.method, .block a.current.method,
 .content span.tymethod, .content a.tymethod, .block a.current.tymethod,
diff --git a/src/librustdoc/html/static/themes/light.css b/src/librustdoc/html/static/themes/light.css
index 306e8dc..19ae67b 100644
--- a/src/librustdoc/html/static/themes/light.css
+++ b/src/librustdoc/html/static/themes/light.css
@@ -96,6 +96,7 @@
 }
 .content .highlighted a, .content .highlighted span { color: #000 !important; }
 .content .highlighted.trait { background-color: #c7b6ff; }
+.content .highlighted.traitalias { background-color: #c7b6ff; }
 .content .highlighted.mod,
 .content .highlighted.externcrate { background-color: #afc6e4; }
 .content .highlighted.enum { background-color: #b4d1b9; }
@@ -128,6 +129,7 @@
 .content span.externcrate,
 .content span.mod, .content a.mod, .block a.current.mod { color: #4d76ae; }
 .content span.trait, .content a.trait, .block a.current.trait { color: #7c5af3; }
+.content span.traitalias, .content a.traitalias, .block a.current.traitalias { color: #6841f1; }
 .content span.fn, .content a.fn, .block a.current.fn,
 .content span.method, .content a.method, .block a.current.method,
 .content span.tymethod, .content a.tymethod, .block a.current.tymethod,
diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs
index f4149b5..ddb7306 100644
--- a/src/librustdoc/lib.rs
+++ b/src/librustdoc/lib.rs
@@ -1,6 +1,4 @@
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/",
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
        html_playground_url = "https://play.rust-lang.org/")]
 
 #![feature(bind_by_move_pattern_guards)]
diff --git a/src/librustdoc/passes/mod.rs b/src/librustdoc/passes/mod.rs
index c9a3a2c..5f3da4c 100644
--- a/src/librustdoc/passes/mod.rs
+++ b/src/librustdoc/passes/mod.rs
@@ -224,6 +224,7 @@
             | clean::ConstantItem(..)
             | clean::UnionItem(..)
             | clean::AssociatedConstItem(..)
+            | clean::TraitAliasItem(..)
             | clean::ForeignTypeItem => {
                 if i.def_id.is_local() {
                     if !self.access_levels.is_exported(i.def_id) {
diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs
index b8eb777..352ff78 100644
--- a/src/librustdoc/visit_ast.rs
+++ b/src/librustdoc/visit_ast.rs
@@ -547,8 +547,19 @@
                 };
                 om.traits.push(t);
             },
-            hir::ItemKind::TraitAlias(..) => {
-                unimplemented!("trait objects are not yet implemented")
+            hir::ItemKind::TraitAlias(ref gen, ref b) => {
+                let t = TraitAlias {
+                    name: ident.name,
+                    generics: gen.clone(),
+                    bounds: b.iter().cloned().collect(),
+                    id: item.id,
+                    attrs: item.attrs.clone(),
+                    whence: item.span,
+                    vis: item.vis.clone(),
+                    stab: self.stability(item.id),
+                    depr: self.deprecation(item.id),
+                };
+                om.trait_aliases.push(t);
             },
 
             hir::ItemKind::Impl(unsafety,
diff --git a/src/libserialize/lib.rs b/src/libserialize/lib.rs
index e8d185a..fe93a2d 100644
--- a/src/libserialize/lib.rs
+++ b/src/libserialize/lib.rs
@@ -4,9 +4,7 @@
 Core encoding and decoding interfaces.
 */
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/",
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
        html_playground_url = "https://play.rust-lang.org/",
        test(attr(allow(unused_variables), deny(warnings))))]
 
diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs
index 244caf2..8ecba3e 100644
--- a/src/libstd/lib.rs
+++ b/src/libstd/lib.rs
@@ -196,9 +196,7 @@
 //! [primitive types]: ../book/ch03-02-data-types.html
 
 #![stable(feature = "rust1", since = "1.0.0")]
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/",
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
        html_playground_url = "https://play.rust-lang.org/",
        issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
        test(no_crate_inject, attr(deny(warnings))),
diff --git a/src/libstd/net/ip.rs b/src/libstd/net/ip.rs
index f45cd8b..4e06467 100644
--- a/src/libstd/net/ip.rs
+++ b/src/libstd/net/ip.rs
@@ -392,8 +392,7 @@
     /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn octets(&self) -> [u8; 4] {
-        let bits = u32::from_be(self.inner.s_addr);
-        [(bits >> 24) as u8, (bits >> 16) as u8, (bits >> 8) as u8, bits as u8]
+        self.inner.s_addr.to_ne_bytes()
     }
 
     /// Returns [`true`] for the special 'unspecified' address (0.0.0.0).
diff --git a/src/libstd/sys/sgx/ext/arch.rs b/src/libstd/sys/sgx/ext/arch.rs
index 3bd87b5..97f7d91 100644
--- a/src/libstd/sys/sgx/ext/arch.rs
+++ b/src/libstd/sys/sgx/ext/arch.rs
@@ -41,7 +41,7 @@
         );
 
         match error {
-            0 => Ok(out.into_inner()),
+            0 => Ok(out.into_initialized()),
             err => Err(err),
         }
     }
@@ -69,6 +69,6 @@
               "{rdx}"(report.as_mut_ptr())
         );
 
-        report.into_inner()
+        report.into_initialized()
     }
 }
diff --git a/src/libstd/sys/unix/stdio.rs b/src/libstd/sys/unix/stdio.rs
index 8a6b7b5f..715f2ea 100644
--- a/src/libstd/sys/unix/stdio.rs
+++ b/src/libstd/sys/unix/stdio.rs
@@ -12,7 +12,7 @@
     pub fn read(&self, data: &mut [u8]) -> io::Result<usize> {
         let fd = FileDesc::new(libc::STDIN_FILENO);
         let ret = fd.read(data);
-        fd.into_raw();
+        fd.into_raw(); // do not close this FD
         ret
     }
 }
@@ -23,7 +23,7 @@
     pub fn write(&self, data: &[u8]) -> io::Result<usize> {
         let fd = FileDesc::new(libc::STDOUT_FILENO);
         let ret = fd.write(data);
-        fd.into_raw();
+        fd.into_raw(); // do not close this FD
         ret
     }
 
@@ -38,7 +38,7 @@
     pub fn write(&self, data: &[u8]) -> io::Result<usize> {
         let fd = FileDesc::new(libc::STDERR_FILENO);
         let ret = fd.write(data);
-        fd.into_raw();
+        fd.into_raw(); // do not close this FD
         ret
     }
 
diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs
index 2cfe2cc..681d8ee 100644
--- a/src/libsyntax/ast.rs
+++ b/src/libsyntax/ast.rs
@@ -167,6 +167,17 @@
 pub enum GenericArg {
     Lifetime(Lifetime),
     Type(P<Ty>),
+    Const(AnonConst),
+}
+
+impl GenericArg {
+    pub fn span(&self) -> Span {
+        match self {
+            GenericArg::Lifetime(lt) => lt.ident.span,
+            GenericArg::Type(ty) => ty.span,
+            GenericArg::Const(ct) => ct.value.span,
+        }
+    }
 }
 
 /// A path like `Foo<'a, T>`
@@ -296,13 +307,32 @@
 
 pub type GenericBounds = Vec<GenericBound>;
 
+/// Specifies the enforced ordering for generic parameters. In the future,
+/// if we wanted to relax this order, we could override `PartialEq` and
+/// `PartialOrd`, to allow the kinds to be unordered.
+#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
+pub enum ParamKindOrd {
+    Lifetime,
+    Type,
+    Const,
+}
+
+impl fmt::Display for ParamKindOrd {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match self {
+            ParamKindOrd::Lifetime => "lifetime".fmt(f),
+            ParamKindOrd::Type => "type".fmt(f),
+            ParamKindOrd::Const => "const".fmt(f),
+        }
+    }
+}
+
 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
 pub enum GenericParamKind {
     /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`).
     Lifetime,
-    Type {
-        default: Option<P<Ty>>,
-    },
+    Type { default: Option<P<Ty>> },
+    Const { ty: P<Ty> },
 }
 
 #[derive(Clone, RustcEncodable, RustcDecodable, Debug)]
diff --git a/src/libsyntax/early_buffered_lints.rs b/src/libsyntax/early_buffered_lints.rs
index 977e6d4..29cb9cd 100644
--- a/src/libsyntax/early_buffered_lints.rs
+++ b/src/libsyntax/early_buffered_lints.rs
@@ -12,6 +12,8 @@
     /// Usage of `?` as a macro separator is deprecated.
     QuestionMarkMacroSep,
     IllFormedAttributeInput,
+    /// Usage of a duplicate macro matcher binding name.
+    DuplicateMacroMatcherBindingName,
 }
 
 /// Stores buffered lint info which can later be passed to `librustc`.
diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs
index 1e83f6c..6708e3c 100644
--- a/src/libsyntax/ext/build.rs
+++ b/src/libsyntax/ext/build.rs
@@ -38,12 +38,14 @@
                 bindings: Vec<ast::TypeBinding>)
                 -> (ast::QSelf, ast::Path);
 
-    // types
+    // types and consts
     fn ty_mt(&self, ty: P<ast::Ty>, mutbl: ast::Mutability) -> ast::MutTy;
 
     fn ty(&self, span: Span, ty: ast::TyKind) -> P<ast::Ty>;
     fn ty_path(&self, path: ast::Path) -> P<ast::Ty>;
     fn ty_ident(&self, span: Span, idents: ast::Ident) -> P<ast::Ty>;
+    fn anon_const(&self, span: Span, expr: ast::ExprKind) -> ast::AnonConst;
+    fn const_ident(&self, span: Span, idents: ast::Ident) -> ast::AnonConst;
 
     fn ty_rptr(&self, span: Span,
                ty: P<ast::Ty>,
@@ -394,6 +396,22 @@
         self.ty_path(self.path_ident(span, ident))
     }
 
+    fn anon_const(&self, span: Span, expr: ast::ExprKind) -> ast::AnonConst {
+        ast::AnonConst {
+            id: ast::DUMMY_NODE_ID,
+            value: P(ast::Expr {
+                id: ast::DUMMY_NODE_ID,
+                node: expr,
+                span,
+                attrs: ThinVec::new(),
+            })
+        }
+    }
+
+    fn const_ident(&self, span: Span, ident: ast::Ident) -> ast::AnonConst {
+        self.anon_const(span, ast::ExprKind::Path(None, self.path_ident(span, ident)))
+    }
+
     fn ty_rptr(&self,
                span: Span,
                ty: P<ast::Ty>,
diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs
index b3ecaea..33ea675 100644
--- a/src/libsyntax/ext/tt/macro_rules.rs
+++ b/src/libsyntax/ext/tt/macro_rules.rs
@@ -17,10 +17,10 @@
 use crate::symbol::Symbol;
 use crate::tokenstream::{DelimSpan, TokenStream, TokenTree};
 
-use syntax_pos::{Span, DUMMY_SP};
+use syntax_pos::{Span, DUMMY_SP, symbol::Ident};
 use log::debug;
 
-use rustc_data_structures::fx::FxHashMap;
+use rustc_data_structures::fx::{FxHashMap};
 use std::borrow::Cow;
 use std::collections::hash_map::Entry;
 
@@ -246,8 +246,12 @@
 // Holy self-referential!
 
 /// Converts a `macro_rules!` invocation into a syntax extension.
-pub fn compile(sess: &ParseSess, features: &Features, def: &ast::Item, edition: Edition)
-               -> SyntaxExtension {
+pub fn compile(
+    sess: &ParseSess,
+    features: &Features,
+    def: &ast::Item,
+    edition: Edition
+) -> SyntaxExtension {
     let lhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("lhs"));
     let rhs_nm = ast::Ident::with_empty_ctxt(Symbol::gensym("rhs"));
 
@@ -355,7 +359,13 @@
 
     // don't abort iteration early, so that errors for multiple lhses can be reported
     for lhs in &lhses {
-        valid &= check_lhs_no_empty_seq(sess, &[lhs.clone()])
+        valid &= check_lhs_no_empty_seq(sess, &[lhs.clone()]);
+        valid &= check_lhs_duplicate_matcher_bindings(
+            sess,
+            &[lhs.clone()],
+            &mut FxHashMap::default(),
+            def.id
+        );
     }
 
     let expander: Box<_> = Box::new(MacroRulesMacroExpander {
@@ -456,6 +466,53 @@
     true
 }
 
+/// Check that the LHS contains no duplicate matcher bindings. e.g. `$a:expr, $a:expr` would be
+/// illegal, since it would be ambiguous which `$a` to use if we ever needed to.
+fn check_lhs_duplicate_matcher_bindings(
+    sess: &ParseSess,
+    tts: &[quoted::TokenTree],
+    metavar_names: &mut FxHashMap<Ident, Span>,
+    node_id: ast::NodeId,
+) -> bool {
+    use self::quoted::TokenTree;
+    use crate::early_buffered_lints::BufferedEarlyLintId;
+    for tt in tts {
+        match *tt {
+            TokenTree::MetaVarDecl(span, name, _kind) => {
+                if let Some(&prev_span) = metavar_names.get(&name) {
+                    // FIXME(mark-i-m): in a few cycles, make this a hard error.
+                    // sess.span_diagnostic
+                    //     .struct_span_err(span, "duplicate matcher binding")
+                    //     .span_note(prev_span, "previous declaration was here")
+                    //     .emit();
+                    sess.buffer_lint(
+                        BufferedEarlyLintId::DuplicateMacroMatcherBindingName,
+                        crate::source_map::MultiSpan::from(vec![prev_span, span]),
+                        node_id,
+                        "duplicate matcher binding"
+                    );
+                    return false;
+                } else {
+                    metavar_names.insert(name, span);
+                }
+            }
+            TokenTree::Delimited(_, ref del) => {
+                if !check_lhs_duplicate_matcher_bindings(sess, &del.tts, metavar_names, node_id) {
+                    return false;
+                }
+            },
+            TokenTree::Sequence(_, ref seq) => {
+                if !check_lhs_duplicate_matcher_bindings(sess, &seq.tts, metavar_names, node_id) {
+                    return false;
+                }
+            }
+            _ => {}
+        }
+    }
+
+    true
+}
+
 fn check_rhs(sess: &ParseSess, rhs: &quoted::TokenTree) -> bool {
     match *rhs {
         quoted::TokenTree::Delimited(..) => return true,
diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs
index e7b9a88..0853b43 100644
--- a/src/libsyntax/feature_gate.rs
+++ b/src/libsyntax/feature_gate.rs
@@ -15,7 +15,7 @@
 use AttributeType::*;
 use AttributeGate::*;
 
-use crate::ast::{self, NodeId, PatKind, RangeEnd};
+use crate::ast::{self, NodeId, GenericParam, GenericParamKind, PatKind, RangeEnd};
 use crate::attr;
 use crate::early_buffered_lints::BufferedEarlyLintId;
 use crate::source_map::Spanned;
@@ -462,6 +462,9 @@
     // Re-Rebalance coherence
     (active, re_rebalance_coherence, "1.32.0", Some(55437), None),
 
+    // Const generic types.
+    (active, const_generics, "1.34.0", Some(44580), None),
+
     // #[optimize(X)]
     (active, optimize_attribute, "1.34.0", Some(54882), None),
 
@@ -1899,6 +1902,14 @@
         visit::walk_fn(self, fn_kind, fn_decl, span);
     }
 
+    fn visit_generic_param(&mut self, param: &'a GenericParam) {
+        if let GenericParamKind::Const { .. } = param.kind {
+            gate_feature_post!(&self, const_generics, param.ident.span,
+                "const generics are unstable");
+        }
+        visit::walk_generic_param(self, param);
+    }
+
     fn visit_trait_item(&mut self, ti: &'a ast::TraitItem) {
         match ti.node {
             ast::TraitItemKind::Method(ref sig, ref block) => {
@@ -1984,7 +1995,7 @@
     // Some features are known to be incomplete and using them is likely to have
     // unanticipated results, such as compiler crashes. We warn the user about these
     // to alert them.
-    let incomplete_features = ["generic_associated_types"];
+    let incomplete_features = ["generic_associated_types", "const_generics"];
 
     let mut features = Features::new();
     let mut edition_enabled_features = FxHashMap::default();
diff --git a/src/libsyntax/lib.rs b/src/libsyntax/lib.rs
index c04391b..878d06c 100644
--- a/src/libsyntax/lib.rs
+++ b/src/libsyntax/lib.rs
@@ -4,9 +4,7 @@
 //!
 //! This API is completely unstable and subject to change.
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/",
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
        test(attr(deny(warnings))))]
 
 #![deny(rust_2018_idioms)]
diff --git a/src/libsyntax/mut_visit.rs b/src/libsyntax/mut_visit.rs
index 0fd8bbf..1e5eb09 100644
--- a/src/libsyntax/mut_visit.rs
+++ b/src/libsyntax/mut_visit.rs
@@ -480,6 +480,7 @@
     match arg {
         GenericArg::Lifetime(lt) => vis.visit_lifetime(lt),
         GenericArg::Type(ty) => vis.visit_ty(ty),
+        GenericArg::Const(ct) => vis.visit_anon_const(ct),
     }
 }
 
@@ -698,6 +699,9 @@
         GenericParamKind::Type { default } => {
             visit_opt(default, |default| vis.visit_ty(default));
         }
+        GenericParamKind::Const { ty } => {
+            vis.visit_ty(ty);
+        }
     }
 }
 
diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs
index 2e3233c..d3fc1c0 100644
--- a/src/libsyntax/parse/lexer/mod.rs
+++ b/src/libsyntax/parse/lexer/mod.rs
@@ -33,6 +33,15 @@
     }
 }
 
+#[derive(Clone, Debug)]
+pub struct UnmatchedBrace {
+    pub expected_delim: token::DelimToken,
+    pub found_delim: token::DelimToken,
+    pub found_span: Span,
+    pub unclosed_span: Option<Span>,
+    pub candidate_span: Option<Span>,
+}
+
 pub struct StringReader<'a> {
     pub sess: &'a ParseSess,
     /// The absolute offset within the source_map of the next character to read
@@ -58,6 +67,7 @@
     span_src_raw: Span,
     /// Stack of open delimiters and their spans. Used for error message.
     open_braces: Vec<(token::DelimToken, Span)>,
+    crate unmatched_braces: Vec<UnmatchedBrace>,
     /// The type and spans for all braces
     ///
     /// Used only for error recovery when arriving to EOF with mismatched braces.
@@ -222,6 +232,7 @@
             span: syntax_pos::DUMMY_SP,
             span_src_raw: syntax_pos::DUMMY_SP,
             open_braces: Vec::new(),
+            unmatched_braces: Vec::new(),
             matching_delim_spans: Vec::new(),
             override_span,
             last_unclosed_found_span: None,
diff --git a/src/libsyntax/parse/lexer/tokentrees.rs b/src/libsyntax/parse/lexer/tokentrees.rs
index 7699d9e..0db36c8 100644
--- a/src/libsyntax/parse/lexer/tokentrees.rs
+++ b/src/libsyntax/parse/lexer/tokentrees.rs
@@ -1,5 +1,5 @@
 use crate::print::pprust::token_to_string;
-use crate::parse::lexer::StringReader;
+use crate::parse::lexer::{StringReader, UnmatchedBrace};
 use crate::parse::{token, PResult};
 use crate::tokenstream::{DelimSpan, IsJoint::*, TokenStream, TokenTree, TreeAndJoint};
 
@@ -101,38 +101,38 @@
                     }
                     // Incorrect delimiter.
                     token::CloseDelim(other) => {
-                        let token_str = token_to_string(&self.token);
+                        let mut unclosed_delimiter = None;
+                        let mut candidate = None;
                         if self.last_unclosed_found_span != Some(self.span) {
                             // do not complain about the same unclosed delimiter multiple times
                             self.last_unclosed_found_span = Some(self.span);
-                            let msg = format!("incorrect close delimiter: `{}`", token_str);
-                            let mut err = self.sess.span_diagnostic.struct_span_err(
-                                self.span,
-                                &msg,
-                            );
-                            err.span_label(self.span, "incorrect close delimiter");
                             // This is a conservative error: only report the last unclosed
                             // delimiter. The previous unclosed delimiters could actually be
                             // closed! The parser just hasn't gotten to them yet.
                             if let Some(&(_, sp)) = self.open_braces.last() {
-                                err.span_label(sp, "un-closed delimiter");
+                                unclosed_delimiter = Some(sp);
                             };
                             if let Some(current_padding) = sm.span_to_margin(self.span) {
                                 for (brace, brace_span) in &self.open_braces {
                                     if let Some(padding) = sm.span_to_margin(*brace_span) {
                                         // high likelihood of these two corresponding
                                         if current_padding == padding && brace == &other {
-                                            err.span_label(
-                                                *brace_span,
-                                                "close delimiter possibly meant for this",
-                                            );
+                                            candidate = Some(*brace_span);
                                         }
                                     }
                                 }
                             }
-                            err.emit();
+                            let (tok, _) = self.open_braces.pop().unwrap();
+                            self.unmatched_braces.push(UnmatchedBrace {
+                                expected_delim: tok,
+                                found_delim: other,
+                                found_span: self.span,
+                                unclosed_span: unclosed_delimiter,
+                                candidate_span: candidate,
+                            });
+                        } else {
+                            self.open_braces.pop();
                         }
-                        self.open_braces.pop().unwrap();
 
                         // If the incorrect delimiter matches an earlier opening
                         // delimiter, then don't consume it (it can be used to
diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs
index c723d59..317d693 100644
--- a/src/libsyntax/parse/mod.rs
+++ b/src/libsyntax/parse/mod.rs
@@ -9,6 +9,7 @@
 use crate::symbol::Symbol;
 use crate::tokenstream::{TokenStream, TokenTree};
 use crate::diagnostics::plugin::ErrorMap;
+use crate::print::pprust::token_to_string;
 
 use rustc_data_structures::sync::{Lrc, Lock};
 use syntax_pos::{Span, SourceFile, FileName, MultiSpan};
@@ -136,15 +137,17 @@
     new_parser_from_source_str(sess, name, source).parse_inner_attributes()
 }
 
-pub fn parse_stream_from_source_str(name: FileName, source: String, sess: &ParseSess,
-                                    override_span: Option<Span>)
-                                    -> TokenStream {
+pub fn parse_stream_from_source_str(
+    name: FileName,
+    source: String,
+    sess: &ParseSess,
+    override_span: Option<Span>,
+) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
     source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span)
 }
 
 /// Create a new parser from a source string
-pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String)
-                                      -> Parser<'_> {
+pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> {
     panictry_buffer!(&sess.span_diagnostic, maybe_new_parser_from_source_str(sess, name, source))
 }
 
@@ -195,12 +198,14 @@
 
 /// Given a source_file and config, return a parser. Returns any buffered errors from lexing the
 /// initial token stream.
-fn maybe_source_file_to_parser(sess: &ParseSess, source_file: Lrc<SourceFile>)
-    -> Result<Parser<'_>, Vec<Diagnostic>>
-{
+fn maybe_source_file_to_parser(
+    sess: &ParseSess,
+    source_file: Lrc<SourceFile>,
+) -> Result<Parser<'_>, Vec<Diagnostic>> {
     let end_pos = source_file.end_pos;
-    let mut parser = stream_to_parser(sess, maybe_file_to_stream(sess, source_file, None)?);
-
+    let (stream, unclosed_delims) = maybe_file_to_stream(sess, source_file, None)?;
+    let mut parser = stream_to_parser(sess, stream);
+    parser.unclosed_delims = unclosed_delims;
     if parser.token == token::Eof && parser.span.is_dummy() {
         parser.span = Span::new(end_pos, end_pos, parser.span.ctxt());
     }
@@ -247,25 +252,44 @@
 }
 
 /// Given a source_file, produce a sequence of token-trees
-pub fn source_file_to_stream(sess: &ParseSess,
-                             source_file: Lrc<SourceFile>,
-                             override_span: Option<Span>) -> TokenStream {
+pub fn source_file_to_stream(
+    sess: &ParseSess,
+    source_file: Lrc<SourceFile>,
+    override_span: Option<Span>,
+) -> (TokenStream, Vec<lexer::UnmatchedBrace>) {
     panictry_buffer!(&sess.span_diagnostic, maybe_file_to_stream(sess, source_file, override_span))
 }
 
 /// Given a source file, produce a sequence of token-trees. Returns any buffered errors from
 /// parsing the token tream.
-pub fn maybe_file_to_stream(sess: &ParseSess,
-                            source_file: Lrc<SourceFile>,
-                            override_span: Option<Span>) -> Result<TokenStream, Vec<Diagnostic>> {
+pub fn maybe_file_to_stream(
+    sess: &ParseSess,
+    source_file: Lrc<SourceFile>,
+    override_span: Option<Span>,
+) -> Result<(TokenStream, Vec<lexer::UnmatchedBrace>), Vec<Diagnostic>> {
     let mut srdr = lexer::StringReader::new_or_buffered_errs(sess, source_file, override_span)?;
     srdr.real_token();
 
     match srdr.parse_all_token_trees() {
-        Ok(stream) => Ok(stream),
+        Ok(stream) => Ok((stream, srdr.unmatched_braces)),
         Err(err) => {
             let mut buffer = Vec::with_capacity(1);
             err.buffer(&mut buffer);
+            // Not using `emit_unclosed_delims` to use `db.buffer`
+            for unmatched in srdr.unmatched_braces {
+                let mut db = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!(
+                    "incorrect close delimiter: `{}`",
+                    token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
+                ));
+                db.span_label(unmatched.found_span, "incorrect close delimiter");
+                if let Some(sp) = unmatched.candidate_span {
+                    db.span_label(sp, "close delimiter possibly meant for this");
+                }
+                if let Some(sp) = unmatched.unclosed_span {
+                    db.span_label(sp, "un-closed delimiter");
+                }
+                db.buffer(&mut buffer);
+            }
             Err(buffer)
         }
     }
diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs
index cacdab9..69d6407 100644
--- a/src/libsyntax/parse/parser.rs
+++ b/src/libsyntax/parse/parser.rs
@@ -35,7 +35,7 @@
 use crate::source_map::{self, SourceMap, Spanned, respan};
 use crate::errors::{self, Applicability, DiagnosticBuilder, DiagnosticId};
 use crate::parse::{self, SeqSep, classify, token};
-use crate::parse::lexer::TokenAndSpan;
+use crate::parse::lexer::{TokenAndSpan, UnmatchedBrace};
 use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
 use crate::parse::token::DelimToken;
 use crate::parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
@@ -251,6 +251,11 @@
     ///
     /// See the comments in the `parse_path_segment` function for more details.
     crate unmatched_angle_bracket_count: u32,
+    crate max_angle_bracket_count: u32,
+    /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery
+    /// it gets removed from here. Every entry left at the end gets emitted as an independent
+    /// error.
+    crate unclosed_delims: Vec<UnmatchedBrace>,
 }
 
 
@@ -397,6 +402,7 @@
     Ident,
     Path,
     Type,
+    Const,
 }
 
 impl TokenType {
@@ -409,6 +415,7 @@
             TokenType::Ident => "identifier".to_string(),
             TokenType::Path => "path".to_string(),
             TokenType::Type => "type".to_string(),
+            TokenType::Const => "const".to_string(),
         }
     }
 }
@@ -573,6 +580,8 @@
             desugar_doc_comments,
             cfg_mods: true,
             unmatched_angle_bracket_count: 0,
+            max_angle_bracket_count: 0,
+            unclosed_delims: Vec::new(),
         };
 
         let tok = parser.next_tok();
@@ -642,11 +651,11 @@
 
     /// Expect and consume the token t. Signal an error if
     /// the next token is not t.
-    pub fn expect(&mut self, t: &token::Token) -> PResult<'a,  ()> {
+    pub fn expect(&mut self, t: &token::Token) -> PResult<'a,  bool /* recovered */> {
         if self.expected_tokens.is_empty() {
             if self.token == *t {
                 self.bump();
-                Ok(())
+                Ok(false)
             } else {
                 let token_str = pprust::token_to_string(t);
                 let this_token_str = self.this_token_descr();
@@ -661,6 +670,12 @@
                     self.sess.source_map().next_point(self.prev_span)
                 };
                 let label_exp = format!("expected `{}`", token_str);
+                match self.recover_closing_delimiter(&[t.clone()], err) {
+                    Err(e) => err = e,
+                    Ok(recovered) => {
+                        return Ok(recovered);
+                    }
+                }
                 let cm = self.sess.source_map();
                 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
                     (Ok(ref a), Ok(ref b)) if a.line == b.line => {
@@ -680,12 +695,64 @@
         }
     }
 
+    fn recover_closing_delimiter(
+        &mut self,
+        tokens: &[token::Token],
+        mut err: DiagnosticBuilder<'a>,
+    ) -> PResult<'a, bool> {
+        let mut pos = None;
+        // we want to use the last closing delim that would apply
+        for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
+            if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
+                && Some(self.span) > unmatched.unclosed_span
+            {
+                pos = Some(i);
+            }
+        }
+        match pos {
+            Some(pos) => {
+                // Recover and assume that the detected unclosed delimiter was meant for
+                // this location. Emit the diagnostic and act as if the delimiter was
+                // present for the parser's sake.
+
+                 // Don't attempt to recover from this unclosed delimiter more than once.
+                let unmatched = self.unclosed_delims.remove(pos);
+                let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
+
+                 // We want to suggest the inclusion of the closing delimiter where it makes
+                // the most sense, which is immediately after the last token:
+                //
+                //  {foo(bar {}}
+                //      -      ^
+                //      |      |
+                //      |      help: `)` may belong here (FIXME: #58270)
+                //      |
+                //      unclosed delimiter
+                if let Some(sp) = unmatched.unclosed_span {
+                    err.span_label(sp, "unclosed delimiter");
+                }
+                err.span_suggestion_short(
+                    self.sess.source_map().next_point(self.prev_span),
+                    &format!("{} may belong here", delim.to_string()),
+                    delim.to_string(),
+                    Applicability::MaybeIncorrect,
+                );
+                err.emit();
+                self.expected_tokens.clear();  // reduce errors
+                Ok(true)
+            }
+            _ => Err(err),
+        }
+    }
+
     /// Expect next token to be edible or inedible token.  If edible,
     /// then consume it; if inedible, then return without consuming
     /// anything.  Signal a fatal error if next token is unexpected.
-    pub fn expect_one_of(&mut self,
-                         edible: &[token::Token],
-                         inedible: &[token::Token]) -> PResult<'a,  ()>{
+    pub fn expect_one_of(
+        &mut self,
+        edible: &[token::Token],
+        inedible: &[token::Token],
+    ) -> PResult<'a, bool /* recovered */> {
         fn tokens_to_string(tokens: &[TokenType]) -> String {
             let mut i = tokens.iter();
             // This might be a sign we need a connect method on Iterator.
@@ -705,10 +772,10 @@
         }
         if edible.contains(&self.token) {
             self.bump();
-            Ok(())
+            Ok(false)
         } else if inedible.contains(&self.token) {
             // leave it in the input
-            Ok(())
+            Ok(false)
         } else {
             let mut expected = edible.iter()
                 .map(|x| TokenType::Token(x.clone()))
@@ -759,6 +826,15 @@
             } else {
                 label_sp
             };
+            match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt {
+                TokenType::Token(t) => Some(t.clone()),
+                _ => None,
+            }).collect::<Vec<_>>(), err) {
+                Err(e) => err = e,
+                Ok(recovered) => {
+                    return Ok(recovered);
+                }
+            }
 
             let cm = self.sess.source_map();
             match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
@@ -946,6 +1022,15 @@
         }
     }
 
+    fn check_const_arg(&mut self) -> bool {
+        if self.token.can_begin_const_arg() {
+            true
+        } else {
+            self.expected_tokens.push(TokenType::Const);
+            false
+        }
+    }
+
     /// Expect and consume a `+`. if `+=` is seen, replace it with a `=`
     /// and continue. If a `+` is not seen, return false.
     ///
@@ -1031,7 +1116,8 @@
     }
 
     /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
-    /// `<` and continue. If a `<` is not seen, return false.
+    /// `<` and continue. If `<-` is seen, replace it with a single `<`
+    /// and continue. If a `<` is not seen, return false.
     ///
     /// This is meant to be used when parsing generics on a path to get the
     /// starting token.
@@ -1047,12 +1133,18 @@
                 self.bump_with(token::Lt, span);
                 true
             }
+            token::LArrow => {
+                let span = self.span.with_lo(self.span.lo() + BytePos(1));
+                self.bump_with(token::BinOp(token::Minus), span);
+                true
+            }
             _ => false,
         };
 
         if ate {
             // See doc comment for `unmatched_angle_bracket_count`.
             self.unmatched_angle_bracket_count += 1;
+            self.max_angle_bracket_count += 1;
             debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
         }
 
@@ -1093,12 +1185,12 @@
         };
 
         match ate {
-            Some(x) => {
+            Some(_) => {
                 // See doc comment for `unmatched_angle_bracket_count`.
                 self.unmatched_angle_bracket_count -= 1;
                 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
 
-                Ok(x)
+                Ok(())
             },
             None => self.unexpected(),
         }
@@ -1127,19 +1219,22 @@
                                   -> PResult<'a, Vec<T>> where
         F: FnMut(&mut Parser<'a>) -> PResult<'a,  T>,
     {
-        let val = self.parse_seq_to_before_end(ket, sep, f)?;
-        self.bump();
+        let (val, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
+        if !recovered {
+            self.bump();
+        }
         Ok(val)
     }
 
     /// Parse a sequence, not including the closing delimiter. The function
     /// f must consume tokens until reaching the next separator or
     /// closing bracket.
-    pub fn parse_seq_to_before_end<T, F>(&mut self,
-                                         ket: &token::Token,
-                                         sep: SeqSep,
-                                         f: F)
-                                         -> PResult<'a, Vec<T>>
+    pub fn parse_seq_to_before_end<T, F>(
+        &mut self,
+        ket: &token::Token,
+        sep: SeqSep,
+        f: F,
+    ) -> PResult<'a, (Vec<T>, bool)>
         where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
     {
         self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
@@ -1151,10 +1246,11 @@
         sep: SeqSep,
         expect: TokenExpectType,
         mut f: F,
-    ) -> PResult<'a, Vec<T>>
+    ) -> PResult<'a, (Vec<T>, bool /* recovered */)>
         where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
     {
-        let mut first: bool = true;
+        let mut first = true;
+        let mut recovered = false;
         let mut v = vec![];
         while !kets.iter().any(|k| {
                 match expect {
@@ -1170,23 +1266,30 @@
                 if first {
                     first = false;
                 } else {
-                    if let Err(mut e) = self.expect(t) {
-                        // Attempt to keep parsing if it was a similar separator
-                        if let Some(ref tokens) = t.similar_tokens() {
-                            if tokens.contains(&self.token) {
-                                self.bump();
-                            }
+                    match self.expect(t) {
+                        Ok(false) => {}
+                        Ok(true) => {
+                            recovered = true;
+                            break;
                         }
-                        e.emit();
-                        // Attempt to keep parsing if it was an omitted separator
-                        match f(self) {
-                            Ok(t) => {
-                                v.push(t);
-                                continue;
-                            },
-                            Err(mut e) => {
-                                e.cancel();
-                                break;
+                        Err(mut e) => {
+                            // Attempt to keep parsing if it was a similar separator
+                            if let Some(ref tokens) = t.similar_tokens() {
+                                if tokens.contains(&self.token) {
+                                    self.bump();
+                                }
+                            }
+                            e.emit();
+                            // Attempt to keep parsing if it was an omitted separator
+                            match f(self) {
+                                Ok(t) => {
+                                    v.push(t);
+                                    continue;
+                                },
+                                Err(mut e) => {
+                                    e.cancel();
+                                    break;
+                                }
                             }
                         }
                     }
@@ -1205,23 +1308,26 @@
             v.push(t);
         }
 
-        Ok(v)
+        Ok((v, recovered))
     }
 
     /// Parse a sequence, including the closing delimiter. The function
     /// f must consume tokens until reaching the next separator or
     /// closing bracket.
-    fn parse_unspanned_seq<T, F>(&mut self,
-                                     bra: &token::Token,
-                                     ket: &token::Token,
-                                     sep: SeqSep,
-                                     f: F)
-                                     -> PResult<'a, Vec<T>> where
+    fn parse_unspanned_seq<T, F>(
+        &mut self,
+        bra: &token::Token,
+        ket: &token::Token,
+        sep: SeqSep,
+        f: F,
+    ) -> PResult<'a, Vec<T>> where
         F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
     {
         self.expect(bra)?;
-        let result = self.parse_seq_to_before_end(ket, sep, f)?;
-        self.eat(ket);
+        let (result, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
+        if !recovered {
+            self.eat(ket);
+        }
         Ok(result)
     }
 
@@ -2273,7 +2379,10 @@
             // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
             // it isn't, then we reset the unmatched angle bracket count as we're about to start
             // parsing a new path.
-            if style == PathStyle::Expr { self.unmatched_angle_bracket_count = 0; }
+            if style == PathStyle::Expr {
+                self.unmatched_angle_bracket_count = 0;
+                self.max_angle_bracket_count = 0;
+            }
 
             let args = if self.eat_lt() {
                 // `<'a, T, A = U>`
@@ -2285,12 +2394,14 @@
             } else {
                 // `(T, U) -> R`
                 self.bump(); // `(`
-                let inputs = self.parse_seq_to_before_tokens(
+                let (inputs, recovered) = self.parse_seq_to_before_tokens(
                     &[&token::CloseDelim(token::Paren)],
                     SeqSep::trailing_allowed(token::Comma),
                     TokenExpectType::Expect,
                     |p| p.parse_ty())?;
-                self.bump(); // `)`
+                if !recovered {
+                    self.bump(); // `)`
+                }
                 let span = lo.to(self.prev_span);
                 let output = if self.eat(&token::RArrow) {
                     Some(self.parse_ty_common(false, false)?)
@@ -2496,9 +2607,13 @@
                 // (e,) is a tuple with only one field, e
                 let mut es = vec![];
                 let mut trailing_comma = false;
+                let mut recovered = false;
                 while self.token != token::CloseDelim(token::Paren) {
                     es.push(self.parse_expr()?);
-                    self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
+                    recovered = self.expect_one_of(
+                        &[],
+                        &[token::Comma, token::CloseDelim(token::Paren)],
+                    )?;
                     if self.eat(&token::Comma) {
                         trailing_comma = true;
                     } else {
@@ -2506,7 +2621,9 @@
                         break;
                     }
                 }
-                self.bump();
+                if !recovered {
+                    self.bump();
+                }
 
                 hi = self.prev_span;
                 ex = if es.len() == 1 && !trailing_comma {
@@ -2703,6 +2820,21 @@
                     hi = pth.span;
                     ex = ExprKind::Path(None, pth);
                 } else {
+                    if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
+                        // Don't complain about bare semicolons after unclosed braces
+                        // recovery in order to keep the error count down. Fixing the
+                        // delimiters will possibly also fix the bare semicolon found in
+                        // expression context. For example, silence the following error:
+                        // ```
+                        // error: expected expression, found `;`
+                        //  --> file.rs:2:13
+                        //   |
+                        // 2 |     foo(bar(;
+                        //   |             ^ expected expression
+                        // ```
+                        self.bump();
+                        return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new()));
+                    }
                     match self.parse_literal_maybe_minus() {
                         Ok(expr) => {
                             hi = expr.span;
@@ -2802,7 +2934,7 @@
 
             match self.expect_one_of(&[token::Comma],
                                      &[token::CloseDelim(token::Brace)]) {
-                Ok(()) => if let Some(f) = parsed_field.or(recovery_field) {
+                Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
                     // only include the field if there's no parse error for the field name
                     fields.push(f);
                 }
@@ -5482,15 +5614,27 @@
         Ok((ident, TraitItemKind::Type(bounds, default), generics))
     }
 
+    fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
+        self.expect_keyword(keywords::Const)?;
+        let ident = self.parse_ident()?;
+        self.expect(&token::Colon)?;
+        let ty = self.parse_ty()?;
+
+        Ok(GenericParam {
+            ident,
+            id: ast::DUMMY_NODE_ID,
+            attrs: preceding_attrs.into(),
+            bounds: Vec::new(),
+            kind: GenericParamKind::Const {
+                ty,
+            }
+        })
+    }
+
     /// Parses (possibly empty) list of lifetime and type parameters, possibly including
     /// trailing comma and erroneous trailing attributes.
     crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
-        let mut lifetimes = Vec::new();
         let mut params = Vec::new();
-        let mut seen_ty_param: Option<Span> = None;
-        let mut last_comma_span = None;
-        let mut bad_lifetime_pos = vec![];
-        let mut suggestions = vec![];
         loop {
             let attrs = self.parse_outer_attributes()?;
             if self.check_lifetime() {
@@ -5501,39 +5645,40 @@
                 } else {
                     Vec::new()
                 };
-                lifetimes.push(ast::GenericParam {
+                params.push(ast::GenericParam {
                     ident: lifetime.ident,
                     id: lifetime.id,
                     attrs: attrs.into(),
                     bounds,
                     kind: ast::GenericParamKind::Lifetime,
                 });
-                if let Some(sp) = seen_ty_param {
-                    let remove_sp = last_comma_span.unwrap_or(self.prev_span).to(self.prev_span);
-                    bad_lifetime_pos.push(self.prev_span);
-                    if let Ok(snippet) = self.sess.source_map().span_to_snippet(self.prev_span) {
-                        suggestions.push((remove_sp, String::new()));
-                        suggestions.push((
-                            sp.shrink_to_lo(),
-                            format!("{}, ", snippet)));
-                    }
-                }
+            } else if self.check_keyword(keywords::Const) {
+                // Parse const parameter.
+                params.push(self.parse_const_param(attrs)?);
             } else if self.check_ident() {
                 // Parse type parameter.
                 params.push(self.parse_ty_param(attrs)?);
-                if seen_ty_param.is_none() {
-                    seen_ty_param = Some(self.prev_span);
-                }
             } else {
                 // Check for trailing attributes and stop parsing.
                 if !attrs.is_empty() {
-                    let param_kind = if seen_ty_param.is_some() { "type" } else { "lifetime" };
-                    self.struct_span_err(
-                        attrs[0].span,
-                        &format!("trailing attribute after {} parameters", param_kind),
-                    )
-                    .span_label(attrs[0].span, "attributes must go before parameters")
-                    .emit();
+                    if !params.is_empty() {
+                        self.struct_span_err(
+                            attrs[0].span,
+                            &format!("trailing attribute after generic parameter"),
+                        )
+                        .span_label(attrs[0].span, "attributes must go before parameters")
+                        .emit();
+                    } else {
+                        self.struct_span_err(
+                            attrs[0].span,
+                            &format!("attribute without generic parameters"),
+                        )
+                        .span_label(
+                            attrs[0].span,
+                            "attributes are only permitted when preceding parameters",
+                        )
+                        .emit();
+                    }
                 }
                 break
             }
@@ -5541,24 +5686,8 @@
             if !self.eat(&token::Comma) {
                 break
             }
-            last_comma_span = Some(self.prev_span);
         }
-        if !bad_lifetime_pos.is_empty() {
-            let mut err = self.struct_span_err(
-                bad_lifetime_pos,
-                "lifetime parameters must be declared prior to type parameters",
-            );
-            if !suggestions.is_empty() {
-                err.multipart_suggestion(
-                    "move the lifetime parameter prior to the first type parameter",
-                    suggestions,
-                    Applicability::MachineApplicable,
-                );
-            }
-            err.emit();
-        }
-        lifetimes.extend(params);  // ensure the correct order of lifetimes and type params
-        Ok(lifetimes)
+        Ok(params)
     }
 
     /// Parse a set of optional generic type parameter declarations. Where
@@ -5740,35 +5869,16 @@
     fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
         let mut args = Vec::new();
         let mut bindings = Vec::new();
+        let mut misplaced_assoc_ty_bindings: Vec<Span> = Vec::new();
+        let mut assoc_ty_bindings: Vec<Span> = Vec::new();
 
-        let mut seen_type = false;
-        let mut seen_binding = false;
+        let args_lo = self.span;
 
-        let mut last_comma_span = None;
-        let mut first_type_or_binding_span: Option<Span> = None;
-        let mut first_binding_span: Option<Span> = None;
-
-        let mut bad_lifetime_pos = vec![];
-        let mut bad_type_pos = vec![];
-
-        let mut lifetime_suggestions = vec![];
-        let mut type_suggestions = vec![];
         loop {
             if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
                 // Parse lifetime argument.
                 args.push(GenericArg::Lifetime(self.expect_lifetime()));
-
-                if seen_type || seen_binding {
-                    let remove_sp = last_comma_span.unwrap_or(self.prev_span).to(self.prev_span);
-                    bad_lifetime_pos.push(self.prev_span);
-
-                    if let Ok(snippet) = self.sess.source_map().span_to_snippet(self.prev_span) {
-                        lifetime_suggestions.push((remove_sp, String::new()));
-                        lifetime_suggestions.push((
-                            first_type_or_binding_span.unwrap().shrink_to_lo(),
-                            format!("{}, ", snippet)));
-                    }
-                }
+                misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
             } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
                 // Parse associated type binding.
                 let lo = self.span;
@@ -5782,133 +5892,66 @@
                     ty,
                     span,
                 });
+                assoc_ty_bindings.push(span);
+            } else if self.check_const_arg() {
+                // FIXME(const_generics): to distinguish between idents for types and consts,
+                // we should introduce a GenericArg::Ident in the AST and distinguish when
+                // lowering to the HIR. For now, idents for const args are not permitted.
 
-                seen_binding = true;
-                if first_type_or_binding_span.is_none() {
-                    first_type_or_binding_span = Some(span);
-                }
-                if first_binding_span.is_none() {
-                    first_binding_span = Some(span);
-                }
+                // Parse const argument.
+                let expr = if let token::OpenDelim(token::Brace) = self.token {
+                    self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())?
+                } else if self.token.is_ident() {
+                    // FIXME(const_generics): to distinguish between idents for types and consts,
+                    // we should introduce a GenericArg::Ident in the AST and distinguish when
+                    // lowering to the HIR. For now, idents for const args are not permitted.
+                    return Err(
+                        self.fatal("identifiers may currently not be used for const generics")
+                    );
+                } else {
+                    // FIXME(const_generics): this currently conflicts with emplacement syntax
+                    // with negative integer literals.
+                    self.parse_literal_maybe_minus()?
+                };
+                let value = AnonConst {
+                    id: ast::DUMMY_NODE_ID,
+                    value: expr,
+                };
+                args.push(GenericArg::Const(value));
+                misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
             } else if self.check_type() {
                 // Parse type argument.
-                let ty_param = self.parse_ty()?;
-                if seen_binding {
-                    let remove_sp = last_comma_span.unwrap_or(self.prev_span).to(self.prev_span);
-                    bad_type_pos.push(self.prev_span);
-
-                    if let Ok(snippet) = self.sess.source_map().span_to_snippet(self.prev_span) {
-                        type_suggestions.push((remove_sp, String::new()));
-                        type_suggestions.push((
-                            first_binding_span.unwrap().shrink_to_lo(),
-                            format!("{}, ", snippet)));
-                    }
-                }
-
-                if first_type_or_binding_span.is_none() {
-                    first_type_or_binding_span = Some(ty_param.span);
-                }
-                args.push(GenericArg::Type(ty_param));
-                seen_type = true;
+                args.push(GenericArg::Type(self.parse_ty()?));
+                misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
             } else {
                 break
             }
 
             if !self.eat(&token::Comma) {
                 break
-            } else {
-                last_comma_span = Some(self.prev_span);
             }
         }
 
-        self.maybe_report_incorrect_generic_argument_order(
-            bad_lifetime_pos, bad_type_pos, lifetime_suggestions, type_suggestions
-        );
+        // FIXME: we would like to report this in ast_validation instead, but we currently do not
+        // preserve ordering of generic parameters with respect to associated type binding, so we
+        // lose that information after parsing.
+        if misplaced_assoc_ty_bindings.len() > 0 {
+            let mut err = self.struct_span_err(
+                args_lo.to(self.prev_span),
+                "associated type bindings must be declared after generic parameters",
+            );
+            for span in misplaced_assoc_ty_bindings {
+                err.span_label(
+                    span,
+                    "this associated type binding should be moved after the generic parameters",
+                );
+            }
+            err.emit();
+        }
 
         Ok((args, bindings))
     }
 
-    /// Maybe report an error about incorrect generic argument order - "lifetime parameters
-    /// must be declared before type parameters", "type parameters must be declared before
-    /// associated type bindings" or both.
-    fn maybe_report_incorrect_generic_argument_order(
-        &self,
-        bad_lifetime_pos: Vec<Span>,
-        bad_type_pos: Vec<Span>,
-        lifetime_suggestions: Vec<(Span, String)>,
-        type_suggestions: Vec<(Span, String)>,
-    ) {
-        let mut err = if !bad_lifetime_pos.is_empty() && !bad_type_pos.is_empty() {
-            let mut positions = bad_lifetime_pos.clone();
-            positions.extend_from_slice(&bad_type_pos);
-
-            self.struct_span_err(
-                positions,
-                "generic arguments must declare lifetimes, types and associated type bindings in \
-                 that order",
-            )
-        } else if !bad_lifetime_pos.is_empty() {
-            self.struct_span_err(
-                bad_lifetime_pos.clone(),
-                "lifetime parameters must be declared prior to type parameters"
-            )
-        } else if !bad_type_pos.is_empty() {
-            self.struct_span_err(
-                bad_type_pos.clone(),
-                "type parameters must be declared prior to associated type bindings"
-            )
-        } else {
-            return;
-        };
-
-        if !bad_lifetime_pos.is_empty() {
-            for sp in &bad_lifetime_pos {
-                err.span_label(*sp, "must be declared prior to type parameters");
-            }
-        }
-
-        if !bad_type_pos.is_empty() {
-            for sp in &bad_type_pos {
-                err.span_label(*sp, "must be declared prior to associated type bindings");
-            }
-        }
-
-        if !lifetime_suggestions.is_empty() && !type_suggestions.is_empty() {
-            let mut suggestions = lifetime_suggestions;
-            suggestions.extend_from_slice(&type_suggestions);
-
-            let plural = bad_lifetime_pos.len() + bad_type_pos.len() > 1;
-            err.multipart_suggestion(
-                &format!(
-                    "move the parameter{}",
-                    if plural { "s" } else { "" },
-                ),
-                suggestions,
-                Applicability::MachineApplicable,
-            );
-        } else if !lifetime_suggestions.is_empty() {
-            err.multipart_suggestion(
-                &format!(
-                    "move the lifetime parameter{} prior to the first type parameter",
-                    if bad_lifetime_pos.len() > 1 { "s" } else { "" },
-                ),
-                lifetime_suggestions,
-                Applicability::MachineApplicable,
-            );
-        } else if !type_suggestions.is_empty() {
-            err.multipart_suggestion(
-                &format!(
-                    "move the type parameter{} prior to the first associated type binding",
-                    if bad_type_pos.len() > 1 { "s" } else { "" },
-                ),
-                type_suggestions,
-                Applicability::MachineApplicable,
-            );
-        }
-
-        err.emit();
-    }
-
     /// Parses an optional `where` clause and places it in `generics`.
     ///
     /// ```ignore (only-for-syntax-highlight)
@@ -6011,7 +6054,7 @@
 
         let sp = self.span;
         let mut variadic = false;
-        let args: Vec<Option<Arg>> =
+        let (args, recovered): (Vec<Option<Arg>>, bool) =
             self.parse_seq_to_before_end(
                 &token::CloseDelim(token::Paren),
                 SeqSep::trailing_allowed(token::Comma),
@@ -6059,7 +6102,9 @@
                 }
             )?;
 
-        self.eat(&token::CloseDelim(token::Paren));
+        if !recovered {
+            self.eat(&token::CloseDelim(token::Paren));
+        }
 
         let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
 
@@ -6204,15 +6249,15 @@
 
         // Parse the rest of the function parameter list.
         let sep = SeqSep::trailing_allowed(token::Comma);
-        let fn_inputs = if let Some(self_arg) = self_arg {
+        let (fn_inputs, recovered) = if let Some(self_arg) = self_arg {
             if self.check(&token::CloseDelim(token::Paren)) {
-                vec![self_arg]
+                (vec![self_arg], false)
             } else if self.eat(&token::Comma) {
                 let mut fn_inputs = vec![self_arg];
-                fn_inputs.append(&mut self.parse_seq_to_before_end(
-                    &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
-                );
-                fn_inputs
+                let (mut input, recovered) = self.parse_seq_to_before_end(
+                    &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
+                fn_inputs.append(&mut input);
+                (fn_inputs, recovered)
             } else {
                 return self.unexpected();
             }
@@ -6220,8 +6265,10 @@
             self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
         };
 
-        // Parse closing paren and return type.
-        self.expect(&token::CloseDelim(token::Paren))?;
+        if !recovered {
+            // Parse closing paren and return type.
+            self.expect(&token::CloseDelim(token::Paren))?;
+        }
         Ok(P(FnDecl {
             inputs: fn_inputs,
             output: self.parse_ret_ty(true)?,
@@ -6241,7 +6288,7 @@
                     SeqSep::trailing_allowed(token::Comma),
                     TokenExpectType::NoExpect,
                     |p| p.parse_fn_block_arg()
-                )?;
+                )?.0;
                 self.expect_or()?;
                 args
             }
@@ -6526,6 +6573,7 @@
         //     `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
         //     `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
         //     `<` (LIFETIME|IDENT) `=` - generic parameter with a default
+        //     `<` const                - generic const parameter
         // The only truly ambiguous case is
         //     `<` IDENT `>` `::` IDENT ...
         // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
@@ -6535,7 +6583,8 @@
             (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
              self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
                 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
-                                       t == &token::Colon || t == &token::Eq))
+                                       t == &token::Colon || t == &token::Eq) ||
+             self.look_ahead(1, |t| t.is_keyword(keywords::Const)))
     }
 
     fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
@@ -8238,7 +8287,7 @@
             // eat a matched-delimiter token tree:
             let (delim, tts) = self.expect_delimited_token_tree()?;
             if delim != MacDelimiter::Brace {
-                self.expect(&token::Semi)?
+                self.expect(&token::Semi)?;
             }
 
             Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
@@ -8383,11 +8432,14 @@
     /// entry point for the parser.
     pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
         let lo = self.span;
-        Ok(ast::Crate {
+        let krate = Ok(ast::Crate {
             attrs: self.parse_inner_attributes()?,
             module: self.parse_mod_items(&token::Eof, lo)?,
             span: lo.to(self.span),
-        })
+        });
+        emit_unclosed_delims(&self.unclosed_delims, self.diagnostic());
+        self.unclosed_delims.clear();
+        krate
     }
 
     pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
@@ -8416,3 +8468,20 @@
         }
     }
 }
+
+pub fn emit_unclosed_delims(unclosed_delims: &[UnmatchedBrace], handler: &errors::Handler) {
+    for unmatched in unclosed_delims {
+        let mut err = handler.struct_span_err(unmatched.found_span, &format!(
+            "incorrect close delimiter: `{}`",
+            pprust::token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
+        ));
+        err.span_label(unmatched.found_span, "incorrect close delimiter");
+        if let Some(sp) = unmatched.candidate_span {
+            err.span_label(sp, "close delimiter possibly meant for this");
+        }
+        if let Some(sp) = unmatched.unclosed_span {
+            err.span_label(sp, "un-closed delimiter");
+        }
+        err.emit();
+    }
+}
diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs
index 3b1fa5e..09924e3 100644
--- a/src/libsyntax/parse/token.rs
+++ b/src/libsyntax/parse/token.rs
@@ -10,6 +10,7 @@
 use crate::ptr::P;
 use crate::symbol::keywords;
 use crate::syntax::parse::parse_stream_from_source_str;
+use crate::syntax::parse::parser::emit_unclosed_delims;
 use crate::tokenstream::{self, DelimSpan, TokenStream, TokenTree};
 
 use serialize::{Decodable, Decoder, Encodable, Encoder};
@@ -279,6 +280,20 @@
         }
     }
 
+    /// Returns `true` if the token can appear at the start of a const param.
+    pub fn can_begin_const_arg(&self) -> bool {
+        match self {
+            OpenDelim(Brace) => true,
+            Interpolated(ref nt) => match nt.0 {
+                NtExpr(..) => true,
+                NtBlock(..) => true,
+                NtLiteral(..) => true,
+                _ => false,
+            }
+            _ => self.can_begin_literal_or_bool(),
+        }
+    }
+
     /// Returns `true` if the token can appear at the start of a generic bound.
     crate fn can_begin_bound(&self) -> bool {
         self.is_path_start() || self.is_lifetime() || self.is_keyword(keywords::For) ||
@@ -293,7 +308,7 @@
         }
     }
 
-    /// Returns `true` if the token is any literal, a minus (which can follow a literal,
+    /// Returns `true` if the token is any literal, a minus (which can prefix a literal,
     /// for example a '-42', or one of the boolean idents).
     crate fn can_begin_literal_or_bool(&self) -> bool {
         match *self {
@@ -487,8 +502,8 @@
     /// Enables better error recovery when the wrong token is found.
     crate fn similar_tokens(&self) -> Option<Vec<Token>> {
         match *self {
-            Comma => Some(vec![Dot, Lt]),
-            Semi => Some(vec![Colon]),
+            Comma => Some(vec![Dot, Lt, Semi]),
+            Semi => Some(vec![Colon, Comma]),
             _ => None
         }
     }
@@ -545,7 +560,10 @@
             // FIXME(#43081): Avoid this pretty-print + reparse hack
             let source = pprust::token_to_string(self);
             let filename = FileName::macro_expansion_source_code(&source);
-            parse_stream_from_source_str(filename, source, sess, Some(span))
+            let (tokens, errors) = parse_stream_from_source_str(
+                filename, source, sess, Some(span));
+            emit_unclosed_delims(&errors, &sess.span_diagnostic);
+            tokens
         });
 
         // During early phases of the compiler the AST could get modified
@@ -786,12 +804,13 @@
         let source = pprust::attr_to_string(attr);
         let macro_filename = FileName::macro_expansion_source_code(&source);
         if attr.is_sugared_doc {
-            let stream = parse_stream_from_source_str(
+            let (stream, errors) = parse_stream_from_source_str(
                 macro_filename,
                 source,
                 sess,
                 Some(span),
             );
+            emit_unclosed_delims(&errors, &sess.span_diagnostic);
             builder.push(stream);
             continue
         }
@@ -808,12 +827,13 @@
         // ... and for more complicated paths, fall back to a reparse hack that
         // should eventually be removed.
         } else {
-            let stream = parse_stream_from_source_str(
+            let (stream, errors) = parse_stream_from_source_str(
                 macro_filename,
                 source,
                 sess,
                 Some(span),
             );
+            emit_unclosed_delims(&errors, &sess.span_diagnostic);
             brackets.push(stream);
         }
 
diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs
index c7c4c4f..c670f47 100644
--- a/src/libsyntax/print/pprust.rs
+++ b/src/libsyntax/print/pprust.rs
@@ -1025,6 +1025,7 @@
         match generic_arg {
             GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
             GenericArg::Type(ty) => self.print_type(ty),
+            GenericArg::Const(ct) => self.print_expr(&ct.value),
         }
     }
 
@@ -2929,7 +2930,7 @@
                     s.print_outer_attributes_inline(&param.attrs)?;
                     let lt = ast::Lifetime { id: param.id, ident: param.ident };
                     s.print_lifetime_bounds(lt, &param.bounds)
-                },
+                }
                 ast::GenericParamKind::Type { ref default } => {
                     s.print_outer_attributes_inline(&param.attrs)?;
                     s.print_ident(param.ident)?;
@@ -2943,6 +2944,15 @@
                         _ => Ok(())
                     }
                 }
+                ast::GenericParamKind::Const { ref ty } => {
+                    s.print_outer_attributes_inline(&param.attrs)?;
+                    s.word_space("const")?;
+                    s.print_ident(param.ident)?;
+                    s.s.space()?;
+                    s.word_space(":")?;
+                    s.print_type(ty)?;
+                    s.print_type_bounds(":", &param.bounds)
+                }
             }
         })?;
 
diff --git a/src/libsyntax/util/parser_testing.rs b/src/libsyntax/util/parser_testing.rs
index dbe2b8d..bcf1da6 100644
--- a/src/libsyntax/util/parser_testing.rs
+++ b/src/libsyntax/util/parser_testing.rs
@@ -12,8 +12,11 @@
 /// Map a string to tts, using a made-up filename:
 pub fn string_to_stream(source_str: String) -> TokenStream {
     let ps = ParseSess::new(FilePathMapping::empty());
-    source_file_to_stream(&ps, ps.source_map()
-                             .new_source_file(PathBuf::from("bogofile").into(), source_str), None)
+    source_file_to_stream(
+        &ps,
+        ps.source_map().new_source_file(PathBuf::from("bogofile").into(),
+        source_str,
+    ), None).0
 }
 
 /// Map string to parser (via tts)
diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs
index acbb58a..bb3b0ea 100644
--- a/src/libsyntax/visit.rs
+++ b/src/libsyntax/visit.rs
@@ -126,6 +126,7 @@
         match generic_arg {
             GenericArg::Lifetime(lt) => self.visit_lifetime(lt),
             GenericArg::Type(ty) => self.visit_ty(ty),
+            GenericArg::Const(ct) => self.visit_anon_const(ct),
         }
     }
     fn visit_assoc_type_binding(&mut self, type_binding: &'ast TypeBinding) {
@@ -486,6 +487,7 @@
     match param.kind {
         GenericParamKind::Lifetime => {}
         GenericParamKind::Type { ref default } => walk_list!(visitor, visit_ty, default),
+        GenericParamKind::Const { ref ty, .. } => visitor.visit_ty(ty),
     }
 }
 
diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs
index e6fe125..4678c75 100644
--- a/src/libsyntax_ext/deriving/generic/mod.rs
+++ b/src/libsyntax_ext/deriving/generic/mod.rs
@@ -560,6 +560,7 @@
 
                 cx.typaram(self.span, param.ident, vec![], bounds, None)
             }
+            GenericParamKind::Const { .. } => param.clone(),
         }));
 
         // and similarly for where clauses
@@ -657,6 +658,9 @@
             GenericParamKind::Type { .. } => {
                 GenericArg::Type(cx.ty_ident(self.span, param.ident))
             }
+            GenericParamKind::Const { .. } => {
+                GenericArg::Const(cx.const_ident(self.span, param.ident))
+            }
         }).collect();
 
         // Create the type of `self`.
diff --git a/src/libsyntax_ext/deriving/generic/ty.rs b/src/libsyntax_ext/deriving/generic/ty.rs
index ea6e079..100ec00 100644
--- a/src/libsyntax_ext/deriving/generic/ty.rs
+++ b/src/libsyntax_ext/deriving/generic/ty.rs
@@ -94,7 +94,7 @@
     }
 }
 
-/// A type. Supports pointers, Self, and literals
+/// A type. Supports pointers, Self, and literals.
 #[derive(Clone)]
 pub enum Ty<'a> {
     Self_,
@@ -107,6 +107,13 @@
     Tuple(Vec<Ty<'a>>),
 }
 
+/// A const expression. Supports literals and blocks.
+#[derive(Clone, Eq, PartialEq)]
+pub enum Const {
+    Literal,
+    Block,
+}
+
 pub fn borrowed_ptrty<'r>() -> PtrTy<'r> {
     Borrowed(None, ast::Mutability::Immutable)
 }
@@ -180,6 +187,9 @@
                     GenericParamKind::Type { .. } => {
                         GenericArg::Type(cx.ty_ident(span, param.ident))
                     }
+                    GenericParamKind::Const { .. } => {
+                        GenericArg::Const(cx.const_ident(span, param.ident))
+                    }
                 }).collect();
 
                 cx.path_all(span, false, vec![self_ty], params, vec![])
diff --git a/src/libsyntax_ext/lib.rs b/src/libsyntax_ext/lib.rs
index 9308cfb..670d71f 100644
--- a/src/libsyntax_ext/lib.rs
+++ b/src/libsyntax_ext/lib.rs
@@ -1,8 +1,6 @@
 //! Syntax extensions in the Rust compiler.
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 
 #![deny(rust_2018_idioms)]
 
diff --git a/src/libsyntax_ext/proc_macro_server.rs b/src/libsyntax_ext/proc_macro_server.rs
index 7302626..2158cfc 100644
--- a/src/libsyntax_ext/proc_macro_server.rs
+++ b/src/libsyntax_ext/proc_macro_server.rs
@@ -12,6 +12,7 @@
 use syntax::ext::base::ExtCtxt;
 use syntax::parse::lexer::comments;
 use syntax::parse::{self, token, ParseSess};
+use syntax::parse::parser::emit_unclosed_delims;
 use syntax::tokenstream::{self, DelimSpan, IsJoint::*, TokenStream, TreeAndJoint};
 use syntax_pos::hygiene::{SyntaxContext, Transparency};
 use syntax_pos::symbol::{keywords, Symbol};
@@ -409,12 +410,14 @@
         stream.is_empty()
     }
     fn from_str(&mut self, src: &str) -> Self::TokenStream {
-        parse::parse_stream_from_source_str(
+        let (tokens, errors) = parse::parse_stream_from_source_str(
             FileName::proc_macro_source_code(src.clone()),
             src.to_string(),
             self.sess,
             Some(self.call_site),
-        )
+        );
+        emit_unclosed_delims(&errors, &self.sess.span_diagnostic);
+        tokens
     }
     fn to_string(&mut self, stream: &Self::TokenStream) -> String {
         stream.to_string()
diff --git a/src/libsyntax_pos/lib.rs b/src/libsyntax_pos/lib.rs
index 13e7307..70c45f7 100644
--- a/src/libsyntax_pos/lib.rs
+++ b/src/libsyntax_pos/lib.rs
@@ -4,9 +4,7 @@
 //!
 //! This API is completely unstable and subject to change.
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-      html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-      html_root_url = "https://doc.rust-lang.org/nightly/")]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
 
 #![deny(rust_2018_idioms)]
 
diff --git a/src/libterm/Cargo.toml b/src/libterm/Cargo.toml
index 8021e81..4eba9a9 100644
--- a/src/libterm/Cargo.toml
+++ b/src/libterm/Cargo.toml
@@ -2,6 +2,7 @@
 authors = ["The Rust Project Developers"]
 name = "term"
 version = "0.0.0"
+edition = "2018"
 
 [lib]
 name = "term"
diff --git a/src/libterm/lib.rs b/src/libterm/lib.rs
index 115dffa..caca9fa 100644
--- a/src/libterm/lib.rs
+++ b/src/libterm/lib.rs
@@ -30,27 +30,25 @@
 //! [win]: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682010%28v=vs.85%29.aspx
 //! [ti]: https://en.wikipedia.org/wiki/Terminfo
 
-#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-       html_root_url = "https://doc.rust-lang.org/nightly/",
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
        html_playground_url = "https://play.rust-lang.org/",
        test(attr(deny(warnings))))]
 #![deny(missing_docs)]
 
+#![deny(rust_2018_idioms)]
+
 #![cfg_attr(windows, feature(libc))]
 // Handle rustfmt skips
 #![feature(custom_attribute)]
-#![feature(nll)]
 #![allow(unused_attributes)]
 
 use std::io::prelude::*;
+use std::io::{self, Stdout, Stderr};
 
 pub use terminfo::TerminfoTerminal;
 #[cfg(windows)]
 pub use win::WinConsole;
 
-use std::io::{self, Stdout, Stderr};
-
 pub mod terminfo;
 
 #[cfg(windows)]
diff --git a/src/libterm/terminfo/mod.rs b/src/libterm/terminfo/mod.rs
index eaa96df..4c3b0b1 100644
--- a/src/libterm/terminfo/mod.rs
+++ b/src/libterm/terminfo/mod.rs
@@ -5,18 +5,16 @@
 use std::error;
 use std::fmt;
 use std::fs::File;
-use std::io::prelude::*;
-use std::io;
-use std::io::BufReader;
+use std::io::{self, prelude::*, BufReader};
 use std::path::Path;
 
-use Attr;
-use color;
-use Terminal;
-use self::searcher::get_dbpath_for_term;
-use self::parser::compiled::{parse, msys_terminfo};
-use self::parm::{expand, Variables, Param};
+use crate::Attr;
+use crate::color;
+use crate::Terminal;
 
+use searcher::get_dbpath_for_term;
+use parser::compiled::{parse, msys_terminfo};
+use parm::{expand, Variables, Param};
 
 /// A parsed terminfo database entry.
 #[derive(Debug)]
@@ -49,7 +47,7 @@
     }
 
     fn cause(&self) -> Option<&dyn error::Error> {
-        use self::Error::*;
+        use Error::*;
         match *self {
             IoError(ref e) => Some(e),
             _ => None,
@@ -58,8 +56,8 @@
 }
 
 impl fmt::Display for Error {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        use self::Error::*;
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        use Error::*;
         match *self {
             TermUnset => Ok(()),
             MalformedTerminfo(ref e) => e.fmt(f),
diff --git a/src/libterm/terminfo/parm.rs b/src/libterm/terminfo/parm.rs
index 434dd4a..4e81b8a 100644
--- a/src/libterm/terminfo/parm.rs
+++ b/src/libterm/terminfo/parm.rs
@@ -40,23 +40,27 @@
 /// Container for static and dynamic variable arrays
 pub struct Variables {
     /// Static variables A-Z
-    sta: [Param; 26],
+    sta_va: [Param; 26],
     /// Dynamic variables a-z
-    dyn: [Param; 26],
+    dyn_va: [Param; 26],
 }
 
 impl Variables {
     /// Return a new zero-initialized Variables
     pub fn new() -> Variables {
         Variables {
-            sta: [Number(0), Number(0), Number(0), Number(0), Number(0), Number(0), Number(0),
-                  Number(0), Number(0), Number(0), Number(0), Number(0), Number(0), Number(0),
-                  Number(0), Number(0), Number(0), Number(0), Number(0), Number(0), Number(0),
-                  Number(0), Number(0), Number(0), Number(0), Number(0)],
-            dyn: [Number(0), Number(0), Number(0), Number(0), Number(0), Number(0), Number(0),
-                  Number(0), Number(0), Number(0), Number(0), Number(0), Number(0), Number(0),
-                  Number(0), Number(0), Number(0), Number(0), Number(0), Number(0), Number(0),
-                  Number(0), Number(0), Number(0), Number(0), Number(0)],
+            sta_va: [
+                Number(0), Number(0), Number(0), Number(0), Number(0), Number(0), Number(0),
+                Number(0), Number(0), Number(0), Number(0), Number(0), Number(0), Number(0),
+                Number(0), Number(0), Number(0), Number(0), Number(0), Number(0), Number(0),
+                Number(0), Number(0), Number(0), Number(0), Number(0)
+            ],
+            dyn_va: [
+                Number(0), Number(0), Number(0), Number(0), Number(0), Number(0), Number(0),
+                Number(0), Number(0), Number(0), Number(0), Number(0), Number(0), Number(0),
+                Number(0), Number(0), Number(0), Number(0), Number(0), Number(0), Number(0),
+                Number(0), Number(0), Number(0), Number(0), Number(0)
+            ],
         }
     }
 }
@@ -249,14 +253,14 @@
                 if cur >= 'A' && cur <= 'Z' {
                     if let Some(arg) = stack.pop() {
                         let idx = (cur as u8) - b'A';
-                        vars.sta[idx as usize] = arg;
+                        vars.sta_va[idx as usize] = arg;
                     } else {
                         return Err("stack is empty".to_string());
                     }
                 } else if cur >= 'a' && cur <= 'z' {
                     if let Some(arg) = stack.pop() {
                         let idx = (cur as u8) - b'a';
-                        vars.dyn[idx as usize] = arg;
+                        vars.dyn_va[idx as usize] = arg;
                     } else {
                         return Err("stack is empty".to_string());
                     }
@@ -267,10 +271,10 @@
             GetVar => {
                 if cur >= 'A' && cur <= 'Z' {
                     let idx = (cur as u8) - b'A';
-                    stack.push(vars.sta[idx as usize].clone());
+                    stack.push(vars.sta_va[idx as usize].clone());
                 } else if cur >= 'a' && cur <= 'z' {
                     let idx = (cur as u8) - b'a';
-                    stack.push(vars.dyn[idx as usize].clone());
+                    stack.push(vars.dyn_va[idx as usize].clone());
                 } else {
                     return Err("bad variable name in %g".to_string());
                 }
diff --git a/src/libterm/terminfo/parser/compiled.rs b/src/libterm/terminfo/parser/compiled.rs
index 63d0183..b7b9ce8 100644
--- a/src/libterm/terminfo/parser/compiled.rs
+++ b/src/libterm/terminfo/parser/compiled.rs
@@ -3,14 +3,14 @@
 //! ncurses-compatible compiled terminfo format parsing (term(5))
 
 use std::collections::HashMap;
-use std::io::prelude::*;
 use std::io;
+use std::io::prelude::*;
 use super::super::TermInfo;
 
 // These are the orders ncurses uses in its compiled format (as of 5.9). Not sure if portable.
 
 #[rustfmt_skip]
-pub static boolfnames: &'static[&'static str] = &["auto_left_margin", "auto_right_margin",
+pub static boolfnames: &[&str] = &["auto_left_margin", "auto_right_margin",
     "no_esc_ctlc", "ceol_standout_glitch", "eat_newline_glitch", "erase_overstrike", "generic_type",
     "hard_copy", "has_meta_key", "has_status_line", "insert_null_glitch", "memory_above",
     "memory_below", "move_insert_mode", "move_standout_mode", "over_strike", "status_line_esc_ok",
@@ -23,13 +23,13 @@
     "return_does_clr_eol"];
 
 #[rustfmt_skip]
-pub static boolnames: &'static[&'static str] = &["bw", "am", "xsb", "xhp", "xenl", "eo",
+pub static boolnames: &[&str] = &["bw", "am", "xsb", "xhp", "xenl", "eo",
     "gn", "hc", "km", "hs", "in", "db", "da", "mir", "msgr", "os", "eslok", "xt", "hz", "ul", "xon",
     "nxon", "mc5i", "chts", "nrrmc", "npc", "ndscr", "ccc", "bce", "hls", "xhpa", "crxm", "daisy",
     "xvpa", "sam", "cpix", "lpix", "OTbs", "OTns", "OTnc", "OTMT", "OTNL", "OTpt", "OTxr"];
 
 #[rustfmt_skip]
-pub static numfnames: &'static[&'static str] = &[ "columns", "init_tabs", "lines",
+pub static numfnames: &[&str] = &[ "columns", "init_tabs", "lines",
     "lines_of_memory", "magic_cookie_glitch", "padding_baud_rate", "virtual_terminal",
     "width_status_line", "num_labels", "label_height", "label_width", "max_attributes",
     "maximum_windows", "max_colors", "max_pairs", "no_color_video", "buffer_capacity",
@@ -40,13 +40,13 @@
     "new_line_delay", "backspace_delay", "horizontal_tab_delay", "number_of_function_keys"];
 
 #[rustfmt_skip]
-pub static numnames: &'static[&'static str] = &[ "cols", "it", "lines", "lm", "xmc", "pb",
+pub static numnames: &[&str] = &[ "cols", "it", "lines", "lm", "xmc", "pb",
     "vt", "wsl", "nlab", "lh", "lw", "ma", "wnum", "colors", "pairs", "ncv", "bufsz", "spinv",
     "spinh", "maddr", "mjump", "mcs", "mls", "npins", "orc", "orl", "orhi", "orvi", "cps", "widcs",
     "btns", "bitwin", "bitype", "UTug", "OTdC", "OTdN", "OTdB", "OTdT", "OTkn"];
 
 #[rustfmt_skip]
-pub static stringfnames: &'static[&'static str] = &[ "back_tab", "bell", "carriage_return",
+pub static stringfnames: &[&str] = &[ "back_tab", "bell", "carriage_return",
     "change_scroll_region", "clear_all_tabs", "clear_screen", "clr_eol", "clr_eos",
     "column_address", "command_character", "cursor_address", "cursor_down", "cursor_home",
     "cursor_invisible", "cursor_left", "cursor_mem_address", "cursor_normal", "cursor_right",
@@ -120,7 +120,7 @@
     "acs_plus", "memory_lock", "memory_unlock", "box_chars_1"];
 
 #[rustfmt_skip]
-pub static stringnames: &'static[&'static str] = &[ "cbt", "_", "cr", "csr", "tbc", "clear",
+pub static stringnames: &[&str] = &[ "cbt", "_", "cr", "csr", "tbc", "clear",
     "_", "_", "hpa", "cmdch", "cup", "cud1", "home", "civis", "cub1", "mrcup", "cnorm", "cuf1",
     "ll", "cuu1", "cvvis", "dch1", "dl1", "dsl", "hd", "smacs", "blink", "bold", "smcup", "smdc",
     "dim", "smir", "invis", "prot", "rev", "smso", "smul", "ech", "rmacs", "sgr0", "rmcup", "rmdc",
diff --git a/src/libterm/win.rs b/src/libterm/win.rs
index 25b03ba..1051ddf 100644
--- a/src/libterm/win.rs
+++ b/src/libterm/win.rs
@@ -7,9 +7,9 @@
 use std::io;
 use std::io::prelude::*;
 
-use Attr;
-use color;
-use Terminal;
+use crate::Attr;
+use crate::color;
+use crate::Terminal;
 
 /// A Terminal implementation which uses the Win32 Console API.
 pub struct WinConsole<T> {
diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs
index cced66f..ae046f6 100644
--- a/src/libtest/lib.rs
+++ b/src/libtest/lib.rs
@@ -20,12 +20,7 @@
 #![deny(rust_2018_idioms)]
 #![crate_name = "test"]
 #![unstable(feature = "test", issue = "27812")]
-#![doc(
-    html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
-    html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
-    html_root_url = "https://doc.rust-lang.org/nightly/",
-    test(attr(deny(warnings)))
-)]
+#![doc(html_root_url = "https://doc.rust-lang.org/nightly/", test(attr(deny(warnings))))]
 #![feature(asm)]
 #![feature(fnbox)]
 #![cfg_attr(any(unix, target_os = "cloudabi"), feature(libc, rustc_private))]
diff --git a/src/test/codegen/box-maybe-uninit.rs b/src/test/codegen/box-maybe-uninit.rs
index a7fb74c..ad1d259 100644
--- a/src/test/codegen/box-maybe-uninit.rs
+++ b/src/test/codegen/box-maybe-uninit.rs
@@ -9,5 +9,8 @@
 pub fn box_uninitialized() -> Box<MaybeUninit<usize>> {
     // CHECK-LABEL: @box_uninitialized
     // CHECK-NOT: store
+    // CHECK-NOT: alloca
+    // CHECK-NOT: memcpy
+    // CHECK-NOT: memset
     Box::new(MaybeUninit::uninitialized())
 }
diff --git a/src/test/incremental/hashes/call_expressions.rs b/src/test/incremental/hashes/call_expressions.rs
index 52de065..f0f1f09 100644
--- a/src/test/incremental/hashes/call_expressions.rs
+++ b/src/test/incremental/hashes/call_expressions.rs
@@ -25,7 +25,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized,TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_callee_function() {
     callee2(1, 2)
@@ -40,7 +40,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_argument_function() {
     callee1(1, 3)
@@ -81,7 +81,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized,TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_callee_method() {
     let s = Struct;
@@ -98,7 +98,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_argument_method() {
     let s = Struct;
@@ -115,7 +115,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized,TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_ufcs_callee_method() {
     let s = Struct;
@@ -132,7 +132,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_argument_method_ufcs() {
     let s = Struct;
@@ -149,7 +149,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized,TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 // One might think this would be expanded in the HirBody/Mir, but it actually
 // results in slightly different Hir/Mir.
@@ -171,7 +171,7 @@
     #[cfg(not(cfail1))]
     use super::Struct2 as Struct;
 
-    #[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized,TypeckTables")]
+    #[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized,TypeckTables")]
     #[rustc_clean(cfg="cfail3")]
 
 
diff --git a/src/test/incremental/hashes/closure_expressions.rs b/src/test/incremental/hashes/closure_expressions.rs
index 0e8cf80..4e82729 100644
--- a/src/test/incremental/hashes/closure_expressions.rs
+++ b/src/test/incremental/hashes/closure_expressions.rs
@@ -37,7 +37,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized, TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized, TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn add_parameter() {
     let x = 0u32;
@@ -53,7 +53,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_parameter_pattern() {
     let _ = |&x: &u32| x;
@@ -84,7 +84,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn add_type_ascription_to_parameter() {
     let closure = |x: u32| x + 1u32;
@@ -101,7 +101,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized, TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized, TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_parameter_type() {
     let closure = |x: u16| (x as u64) + 1;
diff --git a/src/test/incremental/hashes/enum_constructors.rs b/src/test/incremental/hashes/enum_constructors.rs
index e9b557b..a74c3ab 100644
--- a/src/test/incremental/hashes/enum_constructors.rs
+++ b/src/test/incremental/hashes/enum_constructors.rs
@@ -34,7 +34,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirValidated")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirBuilt")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_field_value_struct_like() -> Enum {
     Enum::Struct {
@@ -96,7 +96,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirValidated,TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirBuilt,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_constructor_path_struct_like() {
     let _ = Enum2::Struct {
@@ -119,7 +119,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirValidated")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirBuilt")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_constructor_variant_struct_like() {
     let _ = Enum2::Struct2 {
@@ -139,7 +139,7 @@
 
     #[rustc_clean(
         cfg="cfail2",
-        except="FnSignature,Hir,HirBody,MirOptimized,MirValidated,\
+        except="FnSignature,Hir,HirBody,MirOptimized,MirBuilt,\
                 TypeckTables"
     )]
     #[rustc_clean(cfg="cfail3")]
@@ -161,7 +161,7 @@
     #[cfg(not(cfail1))]
     use super::Enum2::Struct2 as Variant;
 
-    #[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirValidated")]
+    #[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirBuilt")]
     #[rustc_clean(cfg="cfail3")]
     pub fn function() -> Enum2 {
         Variant {
@@ -180,7 +180,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirValidated")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirBuilt")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_field_value_tuple_like() -> Enum {
     Enum::Tuple(0, 1, 3)
@@ -197,7 +197,7 @@
 #[cfg(not(cfail1))]
 #[rustc_clean(
     cfg="cfail2",
-    except="HirBody,MirOptimized,MirValidated,TypeckTables"
+    except="HirBody,MirOptimized,MirBuilt,TypeckTables"
 )]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_constructor_path_tuple_like() {
@@ -215,7 +215,7 @@
 #[cfg(not(cfail1))]
 #[rustc_clean(
     cfg="cfail2",
-    except="HirBody,MirOptimized,MirValidated,TypeckTables"
+    except="HirBody,MirOptimized,MirBuilt,TypeckTables"
 )]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_constructor_variant_tuple_like() {
@@ -232,7 +232,7 @@
 
     #[rustc_clean(
         cfg="cfail2",
-        except="FnSignature,Hir,HirBody,MirOptimized,MirValidated,\
+        except="FnSignature,Hir,HirBody,MirOptimized,MirBuilt,\
                 TypeckTables"
     )]
     #[rustc_clean(cfg="cfail3")]
@@ -251,7 +251,7 @@
     #[cfg(not(cfail1))]
     use super::Enum2::Tuple2 as Variant;
 
-    #[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirValidated,TypeckTables")]
+    #[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirBuilt,TypeckTables")]
     #[rustc_clean(cfg="cfail3")]
     pub fn function() -> Enum2 {
         Variant(0, 1, 2)
@@ -278,7 +278,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirValidated,TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirBuilt,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_constructor_path_c_like() {
     let _ = Clike2::B;
@@ -293,7 +293,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirValidated")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirBuilt")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_constructor_variant_c_like() {
     let _ = Clike::C;
@@ -309,7 +309,7 @@
 
     #[rustc_clean(
         cfg="cfail2",
-        except="FnSignature,Hir,HirBody,MirOptimized,MirValidated,\
+        except="FnSignature,Hir,HirBody,MirOptimized,MirBuilt,\
                 TypeckTables"
     )]
     #[rustc_clean(cfg="cfail3")]
@@ -328,7 +328,7 @@
     #[cfg(not(cfail1))]
     use super::Clike::B as Variant;
 
-    #[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirValidated")]
+    #[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirBuilt")]
     #[rustc_clean(cfg="cfail3")]
     pub fn function() -> Clike {
         Variant
diff --git a/src/test/incremental/hashes/exported_vs_not.rs b/src/test/incremental/hashes/exported_vs_not.rs
index 1880dd2..c9f844f 100644
--- a/src/test/incremental/hashes/exported_vs_not.rs
+++ b/src/test/incremental/hashes/exported_vs_not.rs
@@ -16,7 +16,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn body_not_exported_to_metadata() -> u32 {
     2
@@ -35,7 +35,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 #[inline]
 pub fn body_exported_to_metadata_because_of_inline() -> u32 {
@@ -55,7 +55,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 #[inline]
 pub fn body_exported_to_metadata_because_of_generic() -> u32 {
diff --git a/src/test/incremental/hashes/for_loops.rs b/src/test/incremental/hashes/for_loops.rs
index 90c1ecf..da093de 100644
--- a/src/test/incremental/hashes/for_loops.rs
+++ b/src/test/incremental/hashes/for_loops.rs
@@ -25,7 +25,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_loop_body() {
     let mut _x = 0;
@@ -48,7 +48,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_iteration_variable_name() {
     let mut _x = 0;
@@ -71,7 +71,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized, TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized, TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_iteration_variable_pattern() {
     let mut _x = 0;
@@ -94,7 +94,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_iterable() {
     let mut _x = 0;
@@ -116,7 +116,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized, TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized, TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn add_break() {
     let mut _x = 0;
@@ -187,7 +187,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_break_label() {
     let mut _x = 0;
@@ -237,7 +237,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_continue_label() {
     let mut _x = 0;
@@ -262,7 +262,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_continue_to_break() {
     let mut _x = 0;
diff --git a/src/test/incremental/hashes/function_interfaces.rs b/src/test/incremental/hashes/function_interfaces.rs
index 21263c8..4330b00 100644
--- a/src/test/incremental/hashes/function_interfaces.rs
+++ b/src/test/incremental/hashes/function_interfaces.rs
@@ -24,7 +24,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg = "cfail2",
-              except = "Hir, HirBody, MirValidated, MirOptimized, TypeckTables, FnSignature")]
+              except = "Hir, HirBody, MirBuilt, MirOptimized, TypeckTables, FnSignature")]
 #[rustc_clean(cfg = "cfail3")]
 pub fn add_parameter(p: i32) {}
 
@@ -47,7 +47,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg = "cfail2",
-              except = "Hir, HirBody, MirValidated, MirOptimized, TypeckTables, FnSignature")]
+              except = "Hir, HirBody, MirBuilt, MirOptimized, TypeckTables, FnSignature")]
 #[rustc_clean(cfg = "cfail3")]
 pub fn type_of_parameter(p: i64) {}
 
@@ -59,7 +59,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg = "cfail2",
-              except = "Hir, HirBody, MirValidated, MirOptimized, TypeckTables, FnSignature")]
+              except = "Hir, HirBody, MirBuilt, MirOptimized, TypeckTables, FnSignature")]
 #[rustc_clean(cfg = "cfail3")]
 pub fn type_of_parameter_ref(p: &mut i32) {}
 
@@ -71,7 +71,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg = "cfail2",
-              except = "Hir, HirBody, MirValidated, MirOptimized, TypeckTables, FnSignature")]
+              except = "Hir, HirBody, MirBuilt, MirOptimized, TypeckTables, FnSignature")]
 #[rustc_clean(cfg = "cfail3")]
 pub fn order_of_parameters(p2: i64, p1: i32) {}
 
@@ -83,7 +83,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg = "cfail2",
-              except = "Hir, HirBody, MirValidated, MirOptimized, TypeckTables, FnSignature")]
+              except = "Hir, HirBody, MirBuilt, MirOptimized, TypeckTables, FnSignature")]
 #[rustc_clean(cfg = "cfail3")]
 pub unsafe fn make_unsafe() {}
 
@@ -94,7 +94,7 @@
 pub fn make_extern() {}
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg = "cfail2", except = "Hir, HirBody, TypeckTables, FnSignature")]
+#[rustc_clean(cfg = "cfail2", except = "Hir, HirBody, MirBuilt, TypeckTables, FnSignature")]
 #[rustc_clean(cfg = "cfail3")]
 pub extern "C" fn make_extern() {}
 
@@ -292,7 +292,7 @@
     use super::ReferencedType2 as ReturnType;
 
     #[rustc_clean(cfg = "cfail2",
-                  except = "Hir, HirBody, MirValidated, MirOptimized, TypeckTables, FnSignature")]
+                  except = "Hir, HirBody, MirBuilt, MirOptimized, TypeckTables, FnSignature")]
     #[rustc_clean(cfg = "cfail3")]
     pub fn indirect_return_type() -> ReturnType {
         ReturnType {}
@@ -309,7 +309,7 @@
     use super::ReferencedType2 as ParameterType;
 
     #[rustc_clean(cfg = "cfail2",
-                  except = "Hir, HirBody, MirValidated, MirOptimized, TypeckTables, FnSignature")]
+                  except = "Hir, HirBody, MirBuilt, MirOptimized, TypeckTables, FnSignature")]
     #[rustc_clean(cfg = "cfail3")]
     pub fn indirect_parameter_type(p: ParameterType) {}
 }
diff --git a/src/test/incremental/hashes/if_expressions.rs b/src/test/incremental/hashes/if_expressions.rs
index 18dba63..a01247f 100644
--- a/src/test/incremental/hashes/if_expressions.rs
+++ b/src/test/incremental/hashes/if_expressions.rs
@@ -25,7 +25,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized,TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_condition(x: bool) -> u32 {
     if !x {
@@ -46,7 +46,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_then_branch(x: bool) -> u32 {
     if x {
@@ -69,7 +69,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_else_branch(x: bool) -> u32 {
     if x {
@@ -120,7 +120,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized,TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_condition_if_let(x: Option<u32>) -> u32 {
     if let Some(_) = x {
@@ -143,7 +143,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized,TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_then_branch_if_let(x: Option<u32>) -> u32 {
     if let Some(x) = x {
@@ -166,7 +166,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_else_branch_if_let(x: Option<u32>) -> u32 {
     if let Some(x) = x {
diff --git a/src/test/incremental/hashes/inherent_impls.rs b/src/test/incremental/hashes/inherent_impls.rs
index 92ce5a6..d1574ae 100644
--- a/src/test/incremental/hashes/inherent_impls.rs
+++ b/src/test/incremental/hashes/inherent_impls.rs
@@ -42,7 +42,7 @@
 #[rustc_clean(cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 impl Foo {
-    #[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirValidated,TypeckTables")]
+    #[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirBuilt,TypeckTables")]
     #[rustc_clean(cfg="cfail3")]
     pub fn method_body() {
         println!("Hello, world!");
@@ -63,7 +63,7 @@
 #[rustc_clean(cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 impl Foo {
-    #[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirValidated,TypeckTables")]
+    #[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirBuilt,TypeckTables")]
     #[rustc_clean(cfg="cfail3")]
     #[inline]
     pub fn method_body_inlined() {
@@ -114,7 +114,7 @@
 impl Foo {
     #[rustc_clean(
         cfg="cfail2",
-        except="Hir,HirBody,FnSignature,TypeckTables,MirOptimized,MirValidated"
+        except="Hir,HirBody,FnSignature,TypeckTables,MirOptimized,MirBuilt"
     )]
     #[rustc_clean(cfg="cfail3")]
     pub fn method_selfmutness(&mut self) { }
@@ -154,7 +154,7 @@
 impl Foo {
     #[rustc_clean(
         cfg="cfail2",
-        except="Hir,HirBody,FnSignature,TypeckTables,MirOptimized,MirValidated"
+        except="Hir,HirBody,FnSignature,TypeckTables,MirOptimized,MirBuilt"
     )]
     #[rustc_clean(cfg="cfail3")]
     pub fn add_method_parameter(&self, _: i32) { }
@@ -172,7 +172,7 @@
 #[rustc_clean(cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 impl Foo {
-    #[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirValidated")]
+    #[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirBuilt")]
     #[rustc_clean(cfg="cfail3")]
     pub fn change_method_parameter_name(&self, b: i64) { }
 }
@@ -191,7 +191,7 @@
 impl Foo {
     #[rustc_clean(
         cfg="cfail2",
-        except="Hir,HirBody,FnSignature,MirOptimized,MirValidated,TypeckTables")]
+        except="Hir,HirBody,FnSignature,MirOptimized,MirBuilt,TypeckTables")]
     #[rustc_clean(cfg="cfail3")]
     pub fn change_method_return_type(&self) -> u8 { 0 }
 }
@@ -226,7 +226,7 @@
 #[rustc_clean(cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 impl Foo {
-    #[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirValidated")]
+    #[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirBuilt")]
     #[rustc_clean(cfg="cfail3")]
     pub fn change_method_parameter_order(&self, b: i64, a: i64) { }
 }
@@ -245,7 +245,7 @@
 impl Foo {
     #[rustc_clean(
         cfg="cfail2",
-        except="Hir,HirBody,FnSignature,TypeckTables,MirOptimized,MirValidated"
+        except="Hir,HirBody,FnSignature,TypeckTables,MirOptimized,MirBuilt"
     )]
     #[rustc_clean(cfg="cfail3")]
     pub unsafe fn make_method_unsafe(&self) { }
@@ -263,7 +263,7 @@
 #[rustc_clean(cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 impl Foo {
-    #[rustc_clean(cfg="cfail2", except="Hir,HirBody,FnSignature,TypeckTables")]
+    #[rustc_clean(cfg="cfail2", except="Hir,HirBody,MirBuilt,FnSignature,TypeckTables")]
     #[rustc_clean(cfg="cfail3")]
     pub extern fn make_method_extern(&self) { }
 }
@@ -447,7 +447,7 @@
 impl<T> Bar<T> {
     #[rustc_clean(
         cfg="cfail2",
-        except="GenericsOfItem,FnSignature,TypeckTables,TypeOfItem,MirOptimized,MirValidated"
+        except="GenericsOfItem,FnSignature,TypeckTables,TypeOfItem,MirOptimized,MirBuilt"
     )]
     #[rustc_clean(cfg="cfail3")]
     pub fn add_type_parameter_to_impl(&self) { }
@@ -465,7 +465,7 @@
 #[rustc_clean(cfg="cfail2", except="Hir,HirBody")]
 #[rustc_clean(cfg="cfail3")]
 impl Bar<u64> {
-    #[rustc_clean(cfg="cfail2", except="FnSignature,MirOptimized,MirValidated,TypeckTables")]
+    #[rustc_clean(cfg="cfail2", except="FnSignature,MirOptimized,MirBuilt,TypeckTables")]
     #[rustc_clean(cfg="cfail3")]
     pub fn change_impl_self_type(&self) { }
 }
diff --git a/src/test/incremental/hashes/inline_asm.rs b/src/test/incremental/hashes/inline_asm.rs
index e73aa89..c5e7f52 100644
--- a/src/test/incremental/hashes/inline_asm.rs
+++ b/src/test/incremental/hashes/inline_asm.rs
@@ -33,7 +33,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
 pub fn change_template(a: i32) -> i32 {
@@ -69,7 +69,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
 pub fn change_output(a: i32) -> i32 {
@@ -105,7 +105,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
 pub fn change_input(_a: i32, _b: i32) -> i32 {
@@ -140,7 +140,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
 pub fn change_input_constraint(_a: i32, _b: i32) -> i32 {
@@ -175,7 +175,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
 pub fn change_clobber(_a: i32) -> i32 {
@@ -210,7 +210,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
 pub fn change_options(_a: i32) -> i32 {
diff --git a/src/test/incremental/hashes/let_expressions.rs b/src/test/incremental/hashes/let_expressions.rs
index b6050f0..a2b33fe 100644
--- a/src/test/incremental/hashes/let_expressions.rs
+++ b/src/test/incremental/hashes/let_expressions.rs
@@ -22,7 +22,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,MirValidated,MirOptimized")]
+    except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_name() {
     let _y = 2u64;
@@ -38,7 +38,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,TypeckTables,MirValidated,MirOptimized")]
+    except="HirBody,TypeckTables,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn add_type() {
     let _x: u32 = 2u32;
@@ -54,7 +54,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,TypeckTables,MirValidated,MirOptimized")]
+    except="HirBody,TypeckTables,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_type() {
     let _x: u8 = 2;
@@ -70,7 +70,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,TypeckTables,MirValidated,MirOptimized")]
+    except="HirBody,TypeckTables,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_mutability_of_reference_type() {
     let _x: &mut u64;
@@ -86,7 +86,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,TypeckTables,MirValidated,MirOptimized")]
+    except="HirBody,TypeckTables,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_mutability_of_slot() {
     let _x: u64 = 0;
@@ -102,7 +102,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,TypeckTables,MirValidated,MirOptimized")]
+    except="HirBody,TypeckTables,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_simple_binding_to_pattern() {
     let (_a, _b) = (0u8, 'x');
@@ -118,7 +118,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,MirValidated,MirOptimized")]
+    except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_name_in_pattern() {
     let (_a, _c) = (1u8, 'y');
@@ -134,7 +134,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,TypeckTables,MirValidated,MirOptimized")]
+    except="HirBody,TypeckTables,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn add_ref_in_pattern() {
     let (ref _a, _b) = (1u8, 'y');
@@ -150,7 +150,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,TypeckTables,MirValidated,MirOptimized")]
+    except="HirBody,TypeckTables,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn add_amp_in_pattern() {
     let (&_a, _b) = (&1u8, 'y');
@@ -166,7 +166,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,TypeckTables,MirValidated,MirOptimized")]
+    except="HirBody,TypeckTables,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_mutability_of_binding_in_pattern() {
     let (mut _a, _b) = (99u8, 'q');
@@ -182,7 +182,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,TypeckTables,MirValidated,MirOptimized")]
+    except="HirBody,TypeckTables,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn add_initializer() {
     let _x: i16 = 3i16;
@@ -198,7 +198,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,MirValidated,MirOptimized")]
+    except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_initializer() {
     let _x = 5u16;
diff --git a/src/test/incremental/hashes/loop_expressions.rs b/src/test/incremental/hashes/loop_expressions.rs
index a218b01..a48d150 100644
--- a/src/test/incremental/hashes/loop_expressions.rs
+++ b/src/test/incremental/hashes/loop_expressions.rs
@@ -25,7 +25,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_loop_body() {
     let mut _x = 0;
@@ -47,7 +47,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized, TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized, TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn add_break() {
     let mut _x = 0;
@@ -118,7 +118,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized, TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized, TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_break_label() {
     let mut _x = 0;
@@ -168,7 +168,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_continue_label() {
     let mut _x = 0;
@@ -193,7 +193,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized, TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized, TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_continue_to_break() {
     let mut _x = 0;
diff --git a/src/test/incremental/hashes/match_expressions.rs b/src/test/incremental/hashes/match_expressions.rs
index b6b934e..11fe84d 100644
--- a/src/test/incremental/hashes/match_expressions.rs
+++ b/src/test/incremental/hashes/match_expressions.rs
@@ -26,7 +26,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,MirValidated,MirOptimized,TypeckTables")]
+    except="HirBody,MirBuilt,MirOptimized,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn add_arm(x: u32) -> u32 {
     match x {
@@ -51,7 +51,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,MirValidated,MirOptimized")]
+    except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_order_of_arms(x: u32) -> u32 {
     match x {
@@ -75,7 +75,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,MirValidated,MirOptimized,TypeckTables")]
+    except="HirBody,MirBuilt,MirOptimized,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn add_guard_clause(x: u32, y: bool) -> u32 {
     match x {
@@ -99,7 +99,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,MirValidated,MirOptimized,TypeckTables")]
+    except="HirBody,MirBuilt,MirOptimized,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_guard_clause(x: u32, y: bool) -> u32 {
     match x {
@@ -123,7 +123,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,MirValidated,MirOptimized,TypeckTables")]
+    except="HirBody,MirBuilt,MirOptimized,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn add_at_binding(x: u32) -> u32 {
     match x {
@@ -147,7 +147,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,MirValidated,MirOptimized")]
+    except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_name_of_at_binding(x: u32) -> u32 {
     match x {
@@ -170,7 +170,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,MirValidated,MirOptimized,TypeckTables")]
+    except="HirBody,MirBuilt,MirOptimized,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_simple_name_to_pattern(x: u32) -> u32 {
     match (x, x & 1) {
@@ -193,7 +193,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,MirValidated,MirOptimized")]
+    except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_name_in_pattern(x: u32) -> u32 {
     match (x, x & 1) {
@@ -216,7 +216,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,MirValidated,MirOptimized,TypeckTables")]
+    except="HirBody,MirBuilt,MirOptimized,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_mutability_of_binding_in_pattern(x: u32) -> u32 {
     match (x, x & 1) {
@@ -238,7 +238,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,MirValidated,MirOptimized,TypeckTables")]
+    except="HirBody,MirBuilt,MirOptimized,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn add_ref_to_binding_in_pattern(x: u32) -> u32 {
     match (x, x & 1) {
@@ -260,7 +260,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-except="HirBody,MirValidated,MirOptimized,TypeckTables")]
+except="HirBody,MirBuilt,MirOptimized,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn add_amp_to_binding_in_pattern(x: u32) -> u32 {
     match (&x, x & 1) {
@@ -283,7 +283,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,MirValidated,MirOptimized")]
+    except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_rhs_of_arm(x: u32) -> u32 {
     match x {
@@ -307,7 +307,7 @@
 
 #[cfg(not(cfail1))]
 #[rustc_clean(cfg="cfail2",
-    except="HirBody,MirValidated,MirOptimized,TypeckTables")]
+    except="HirBody,MirBuilt,MirOptimized,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn add_alternative_to_arm(x: u32) -> u32 {
     match x {
diff --git a/src/test/incremental/hashes/panic_exprs.rs b/src/test/incremental/hashes/panic_exprs.rs
index 3ae2c39..9a3c931 100644
--- a/src/test/incremental/hashes/panic_exprs.rs
+++ b/src/test/incremental/hashes/panic_exprs.rs
@@ -18,7 +18,7 @@
 
 
 // Indexing expression ---------------------------------------------------------
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn indexing(slice: &[u8]) -> u8 {
     #[cfg(cfail1)]
@@ -33,7 +33,7 @@
 
 
 // Arithmetic overflow plus ----------------------------------------------------
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn arithmetic_overflow_plus(val: i32) -> i32 {
     #[cfg(cfail1)]
@@ -48,7 +48,7 @@
 
 
 // Arithmetic overflow minus ----------------------------------------------------
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn arithmetic_overflow_minus(val: i32) -> i32 {
     #[cfg(cfail1)]
@@ -63,7 +63,7 @@
 
 
 // Arithmetic overflow mult ----------------------------------------------------
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn arithmetic_overflow_mult(val: i32) -> i32 {
     #[cfg(cfail1)]
@@ -78,7 +78,7 @@
 
 
 // Arithmetic overflow negation ------------------------------------------------
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn arithmetic_overflow_negation(val: i32) -> i32 {
     #[cfg(cfail1)]
@@ -93,7 +93,7 @@
 
 
 // Division by zero ------------------------------------------------------------
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn division_by_zero(val: i32) -> i32 {
     #[cfg(cfail1)]
@@ -107,7 +107,7 @@
 }
 
 // Division by zero ------------------------------------------------------------
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn mod_by_zero(val: i32) -> i32 {
     #[cfg(cfail1)]
@@ -122,7 +122,7 @@
 
 
 // shift left ------------------------------------------------------------------
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn shift_left(val: i32, shift: usize) -> i32 {
     #[cfg(cfail1)]
@@ -137,7 +137,7 @@
 
 
 // shift right ------------------------------------------------------------------
-#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirBuilt,MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn shift_right(val: i32, shift: usize) -> i32 {
     #[cfg(cfail1)]
diff --git a/src/test/incremental/hashes/struct_constructors.rs b/src/test/incremental/hashes/struct_constructors.rs
index 5444fe7..a42fda3 100644
--- a/src/test/incremental/hashes/struct_constructors.rs
+++ b/src/test/incremental/hashes/struct_constructors.rs
@@ -31,7 +31,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirValidated")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirBuilt")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_field_value_regular_struct() -> RegularStruct {
     RegularStruct {
@@ -82,7 +82,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirValidated,TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirBuilt,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn add_field_regular_struct() -> RegularStruct {
     let struct1 = RegularStruct {
@@ -117,7 +117,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirValidated,TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirBuilt,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_field_label_regular_struct() -> RegularStruct {
     let struct1 = RegularStruct {
@@ -152,7 +152,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirValidated,TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirBuilt,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_constructor_path_regular_struct() {
     let _ = RegularStruct2 {
@@ -173,7 +173,7 @@
 
     #[rustc_clean(
         cfg="cfail2",
-        except="FnSignature,Hir,HirBody,MirOptimized,MirValidated,TypeckTables"
+        except="FnSignature,Hir,HirBody,MirOptimized,MirBuilt,TypeckTables"
     )]
     #[rustc_clean(cfg="cfail3")]
     pub fn function() -> Struct {
@@ -196,7 +196,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirValidated")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirBuilt")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_field_value_tuple_struct() -> TupleStruct {
     TupleStruct(0, 1, 3)
@@ -213,7 +213,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirValidated,TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody,MirOptimized,MirBuilt,TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_constructor_path_tuple_struct() {
     let _ = TupleStruct2(0, 1, 2);
@@ -230,7 +230,7 @@
 
     #[rustc_clean(
         cfg="cfail2",
-        except="FnSignature,Hir,HirBody,MirOptimized,MirValidated,TypeckTables"
+        except="FnSignature,Hir,HirBody,MirOptimized,MirBuilt,TypeckTables"
     )]
     #[rustc_clean(cfg="cfail3")]
     pub fn function() -> Struct {
diff --git a/src/test/incremental/hashes/unary_and_binary_exprs.rs b/src/test/incremental/hashes/unary_and_binary_exprs.rs
index 26cc41f..ef8035a 100644
--- a/src/test/incremental/hashes/unary_and_binary_exprs.rs
+++ b/src/test/incremental/hashes/unary_and_binary_exprs.rs
@@ -21,7 +21,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn const_negation() -> i32 {
     -1
@@ -36,7 +36,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn const_bitwise_not() -> i32 {
     !99
@@ -51,7 +51,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn var_negation(x: i32, y: i32) -> i32 {
     -y
@@ -66,7 +66,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn var_bitwise_not(x: i32, y: i32) -> i32 {
     !y
@@ -81,7 +81,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated,TypeckTables", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt,TypeckTables", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn var_deref(x: &i32, y: &i32) -> i32 {
     *y
@@ -96,7 +96,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn first_const_add() -> i32 {
     2 + 3
@@ -111,7 +111,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn second_const_add() -> i32 {
     1 + 3
@@ -126,7 +126,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn first_var_add(a: i32, b: i32) -> i32 {
     b + 2
@@ -141,7 +141,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn second_var_add(a: i32, b: i32) -> i32 {
     1 + b
@@ -156,7 +156,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn plus_to_minus(a: i32) -> i32 {
     1 - a
@@ -171,7 +171,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn plus_to_mult(a: i32) -> i32 {
     1 * a
@@ -186,7 +186,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn plus_to_div(a: i32) -> i32 {
     1 / a
@@ -201,7 +201,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn plus_to_mod(a: i32) -> i32 {
     1 % a
@@ -216,7 +216,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn and_to_or(a: bool, b: bool) -> bool {
     a || b
@@ -231,7 +231,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn bitwise_and_to_bitwise_or(a: i32) -> i32 {
     1 | a
@@ -246,7 +246,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn bitwise_and_to_bitwise_xor(a: i32) -> i32 {
     1 ^ a
@@ -261,7 +261,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn bitwise_and_to_lshift(a: i32) -> i32 {
     a << 1
@@ -276,7 +276,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn bitwise_and_to_rshift(a: i32) -> i32 {
     a >> 1
@@ -291,7 +291,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn eq_to_uneq(a: i32) -> bool {
     a != 1
@@ -306,7 +306,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn eq_to_lt(a: i32) -> bool {
     a < 1
@@ -321,7 +321,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn eq_to_gt(a: i32) -> bool {
     a > 1
@@ -336,7 +336,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn eq_to_le(a: i32) -> bool {
     a <= 1
@@ -351,7 +351,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn eq_to_ge(a: i32) -> bool {
     a >= 1
@@ -368,7 +368,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated,TypeckTables", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt,TypeckTables", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn type_cast(a: u8) -> u64 {
     let b = a as u32;
@@ -385,7 +385,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn value_cast(a: u32) -> i32 {
     2 as i32
@@ -403,7 +403,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn place() -> i32 {
     let mut x = 10;
@@ -423,7 +423,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn rvalue() -> i32 {
     let mut x = 10;
@@ -440,7 +440,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(except="HirBody,MirOptimized,MirValidated", cfg="cfail2")]
+#[rustc_clean(except="HirBody,MirOptimized,MirBuilt", cfg="cfail2")]
 #[rustc_clean(cfg="cfail3")]
 pub fn index_to_slice(s: &[u8], i: usize, j: usize) -> u8 {
     s[j]
diff --git a/src/test/incremental/hashes/while_let_loops.rs b/src/test/incremental/hashes/while_let_loops.rs
index edfea05..c708d5b 100644
--- a/src/test/incremental/hashes/while_let_loops.rs
+++ b/src/test/incremental/hashes/while_let_loops.rs
@@ -25,7 +25,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_loop_body() {
     let mut _x = 0;
@@ -48,7 +48,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_loop_condition() {
     let mut _x = 0;
@@ -70,7 +70,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized, TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized, TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn add_break() {
     let mut _x = 0;
@@ -141,7 +141,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized, TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized, TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_break_label() {
     let mut _x = 0;
@@ -191,7 +191,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized, TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized, TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_continue_label() {
     let mut _x = 0;
@@ -216,7 +216,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_continue_to_break() {
     let mut _x = 0;
diff --git a/src/test/incremental/hashes/while_loops.rs b/src/test/incremental/hashes/while_loops.rs
index 85c2c9f..c7b84a1 100644
--- a/src/test/incremental/hashes/while_loops.rs
+++ b/src/test/incremental/hashes/while_loops.rs
@@ -25,7 +25,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_loop_body() {
     let mut _x = 0;
@@ -48,7 +48,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_loop_condition() {
     let mut _x = 0;
@@ -70,7 +70,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized, TypeckTables")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized, TypeckTables")]
 #[rustc_clean(cfg="cfail3")]
 pub fn add_break() {
     let mut _x = 0;
@@ -141,7 +141,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_break_label() {
     let mut _x = 0;
@@ -191,7 +191,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_continue_label() {
     let mut _x = 0;
@@ -216,7 +216,7 @@
 }
 
 #[cfg(not(cfail1))]
-#[rustc_clean(cfg="cfail2", except="HirBody, MirValidated, MirOptimized")]
+#[rustc_clean(cfg="cfail2", except="HirBody, MirBuilt, MirOptimized")]
 #[rustc_clean(cfg="cfail3")]
 pub fn change_continue_to_break() {
     let mut _x = 0;
diff --git a/src/test/run-pass/macros/macro-follow.rs b/src/test/run-pass/macros/macro-follow.rs
index f90afce..488339b 100644
--- a/src/test/run-pass/macros/macro-follow.rs
+++ b/src/test/run-pass/macros/macro-follow.rs
@@ -73,7 +73,7 @@
     ($b:block $t:ty) => {};
     ($b:block $s:stmt) => {};
     ($b:block $p:path) => {};
-    ($b:block $b:block) => {};
+    ($b:block $c:block) => {};
     ($b:block $i:ident) => {};
     ($b:block $t:tt) => {};
     ($b:block $i:item) => {};
@@ -99,9 +99,9 @@
     ($i:ident $s:stmt) => {};
     ($i:ident $p:path) => {};
     ($i:ident $b:block) => {};
-    ($i:ident $i:ident) => {};
+    ($i:ident $j:ident) => {};
     ($i:ident $t:tt) => {};
-    ($i:ident $i:item) => {};
+    ($i:ident $j:item) => {};
     ($i:ident $m:meta) => {};
 }
 // FOLLOW(tt) = any token
@@ -120,12 +120,12 @@
     ($t:tt ident) => {};
     ($t:tt $p:pat) => {};
     ($t:tt $e:expr) => {};
-    ($t:tt $t:ty) => {};
+    ($t:tt $v:ty) => {};
     ($t:tt $s:stmt) => {};
     ($t:tt $p:path) => {};
     ($t:tt $b:block) => {};
     ($t:tt $i:ident) => {};
-    ($t:tt $t:tt) => {};
+    ($t:tt $v:tt) => {};
     ($t:tt $i:item) => {};
     ($t:tt $m:meta) => {};
 }
@@ -149,9 +149,9 @@
     ($i:item $s:stmt) => {};
     ($i:item $p:path) => {};
     ($i:item $b:block) => {};
-    ($i:item $i:ident) => {};
+    ($i:item $j:ident) => {};
     ($i:item $t:tt) => {};
-    ($i:item $i:item) => {};
+    ($i:item $j:item) => {};
     ($i:item $m:meta) => {};
 }
 // FOLLOW(meta) = any token
@@ -177,7 +177,7 @@
     ($m:meta $i:ident) => {};
     ($m:meta $t:tt) => {};
     ($m:meta $i:item) => {};
-    ($m:meta $m:meta) => {};
+    ($m:meta $n:meta) => {};
 }
 
 fn main() {}
diff --git a/src/test/run-pass/methods/method-probe-no-guessing-dyn-trait.rs b/src/test/run-pass/methods/method-probe-no-guessing-dyn-trait.rs
new file mode 100644
index 0000000..8c8165a
--- /dev/null
+++ b/src/test/run-pass/methods/method-probe-no-guessing-dyn-trait.rs
@@ -0,0 +1,59 @@
+// Check that method matching does not make "guesses" depending on
+// Deref impls that don't eventually end up being picked.
+
+use std::ops::Deref;
+
+// An impl with less derefs will get called over an impl with more derefs,
+// so `(t: Foo<_>).my_fn()` will use `<Foo<u32> as MyTrait1>::my_fn(t)`,
+// and does *not* force the `_` to equal `()`, because the Deref impl
+// was *not* used.
+
+trait MyTrait1 {
+    fn my_fn(&self) {}
+}
+
+impl MyTrait1 for Foo<u32> {}
+
+struct Foo<T>(T);
+
+impl Deref for Foo<()> {
+    type Target = dyn MyTrait1 + 'static;
+    fn deref(&self) -> &(dyn MyTrait1 + 'static) {
+        panic!()
+    }
+}
+
+// ...but if there is no impl with less derefs, the "guess" will be
+// forced, so `(t: Bar<_>).my_fn2()` is `<dyn MyTrait2 as MyTrait2>::my_fn2(*t)`,
+// and because the deref impl is used, the `_` is forced to equal `u8`.
+
+trait MyTrait2 {
+    fn my_fn2(&self) {}
+}
+
+impl MyTrait2 for u32 {}
+struct Bar<T>(T, u32);
+impl Deref for Bar<u8> {
+    type Target = dyn MyTrait2 + 'static;
+    fn deref(&self) -> &(dyn MyTrait2 + 'static) {
+        &self.1
+    }
+}
+
+// actually invoke things
+
+fn main() {
+    let mut foo: Option<Foo<_>> = None;
+    let mut bar: Option<Bar<_>> = None;
+    let mut first_iter = true;
+    loop {
+        if !first_iter {
+            foo.as_ref().unwrap().my_fn();
+            bar.as_ref().unwrap().my_fn2();
+            break;
+        }
+        foo = Some(Foo(0));
+        bar = Some(Bar(Default::default(), 0));
+        first_iter = false;
+    }
+}
diff --git a/src/test/run-pass/panic-uninitialized-zeroed.rs b/src/test/run-pass/panic-uninitialized-zeroed.rs
index d47ff6c..31c0d29 100644
--- a/src/test/run-pass/panic-uninitialized-zeroed.rs
+++ b/src/test/run-pass/panic-uninitialized-zeroed.rs
@@ -36,7 +36,7 @@
 
         assert_eq!(
             panic::catch_unwind(|| {
-                mem::MaybeUninit::<!>::uninitialized().into_inner()
+                mem::MaybeUninit::<!>::uninitialized().into_initialized()
             }).err().and_then(|a| a.downcast_ref::<String>().map(|s| {
                 s == "Attempted to instantiate uninhabited type !"
             })),
@@ -63,7 +63,7 @@
 
         assert_eq!(
             panic::catch_unwind(|| {
-                mem::MaybeUninit::<Foo>::uninitialized().into_inner()
+                mem::MaybeUninit::<Foo>::uninitialized().into_initialized()
             }).err().and_then(|a| a.downcast_ref::<String>().map(|s| {
                 s == "Attempted to instantiate uninhabited type Foo"
             })),
@@ -90,7 +90,7 @@
 
         assert_eq!(
             panic::catch_unwind(|| {
-                mem::MaybeUninit::<Bar>::uninitialized().into_inner()
+                mem::MaybeUninit::<Bar>::uninitialized().into_initialized()
             }).err().and_then(|a| a.downcast_ref::<String>().map(|s| {
                 s == "Attempted to instantiate uninhabited type Bar"
             })),
diff --git a/src/test/rustdoc/async-fn.rs b/src/test/rustdoc/async-fn.rs
index a0b6c29..ba4997a 100644
--- a/src/test/rustdoc/async-fn.rs
+++ b/src/test/rustdoc/async-fn.rs
@@ -1,14 +1,35 @@
 // edition:2018
-// compile-flags:-Z unstable-options
-
-// FIXME: once `--edition` is stable in rustdoc, remove that `compile-flags` directive
 
 #![feature(async_await, futures_api)]
 
-// @has async_fn/struct.S.html
-// @has - '//code' 'pub async fn f()'
-pub struct S;
+// @has async_fn/fn.foo.html '//pre[@class="rust fn"]' 'pub async fn foo() -> Option<Foo>'
+pub async fn foo() -> Option<Foo> {
+    None
+}
 
-impl S {
+// @has async_fn/fn.bar.html '//pre[@class="rust fn"]' 'pub async fn bar(a: i32, b: i32) -> i32'
+pub async fn bar(a: i32, b: i32) -> i32 {
+    0
+}
+
+// @has async_fn/fn.baz.html '//pre[@class="rust fn"]' 'pub async fn baz<T>(a: T) -> T'
+pub async fn baz<T>(a: T) -> T {
+    a
+}
+
+trait Bar {}
+
+impl Bar for () {}
+
+// @has async_fn/fn.quux.html '//pre[@class="rust fn"]' 'pub async fn quux() -> impl Bar'
+pub async fn quux() -> impl Bar {
+    ()
+}
+
+// @has async_fn/struct.Foo.html
+// @matches - '//code' 'pub async fn f\(\)$'
+pub struct Foo;
+
+impl Foo {
     pub async fn f() {}
 }
diff --git a/src/test/rustdoc/deprecated.rs b/src/test/rustdoc/deprecated.rs
index ca3f380..74bd945 100644
--- a/src/test/rustdoc/deprecated.rs
+++ b/src/test/rustdoc/deprecated.rs
@@ -1,7 +1,9 @@
 #![feature(deprecated)]
 
-// @matches deprecated/index.html '//*[@class="docblock-short"]' \
-//      '^\[Deprecated\] Deprecated docs'
+// @has deprecated/index.html '//*[@class="docblock-short"]/span[@class="stab deprecated"]' \
+//      'Deprecated'
+// @has - '//*[@class="docblock-short"]' 'Deprecated docs'
+
 // @has deprecated/struct.S.html '//*[@class="stab deprecated"]' \
 //      'Deprecated since 1.0.0: text'
 /// Deprecated docs
diff --git a/src/test/rustdoc/inline_cross/macros.rs b/src/test/rustdoc/inline_cross/macros.rs
index 4e37006..f9bf982 100644
--- a/src/test/rustdoc/inline_cross/macros.rs
+++ b/src/test/rustdoc/inline_cross/macros.rs
@@ -7,7 +7,8 @@
 
 extern crate macros;
 
-// @has foo/index.html '//*[@class="docblock-short"]' '[Deprecated] [Experimental]'
+// @has foo/index.html '//*[@class="docblock-short"]/span[@class="stab deprecated"]' Deprecated
+// @has - '//*[@class="docblock-short"]/span[@class="stab unstable"]' Experimental
 
 // @has foo/macro.my_macro.html
 // @has - '//*[@class="docblock"]' 'docs for my_macro'
diff --git a/src/test/rustdoc/internal.rs b/src/test/rustdoc/internal.rs
index ba58da1..2cb7c47 100644
--- a/src/test/rustdoc/internal.rs
+++ b/src/test/rustdoc/internal.rs
@@ -1,7 +1,9 @@
 // compile-flags: -Z force-unstable-if-unmarked
 
-// @matches internal/index.html '//*[@class="docblock-short"]' \
-//      '^\[Internal\] Docs'
+// @matches internal/index.html '//*[@class="docblock-short"]/span[@class="stab internal"]' \
+//      'Internal'
+// @matches - '//*[@class="docblock-short"]' 'Docs'
+
 // @has internal/struct.S.html '//*[@class="stab internal"]' \
 //      'This is an internal compiler API. (rustc_private)'
 /// Docs
diff --git a/src/test/rustdoc/issue-32374.rs b/src/test/rustdoc/issue-32374.rs
index 58876a1..7babfaf 100644
--- a/src/test/rustdoc/issue-32374.rs
+++ b/src/test/rustdoc/issue-32374.rs
@@ -3,8 +3,11 @@
 
 #![unstable(feature="test", issue = "32374")]
 
-// @matches issue_32374/index.html '//*[@class="docblock-short"]' \
-//      '^\[Deprecated\] \[Experimental\] Docs'
+// @matches issue_32374/index.html '//*[@class="docblock-short"]/span[@class="stab deprecated"]' \
+//      'Deprecated'
+// @matches issue_32374/index.html '//*[@class="docblock-short"]/span[@class="stab unstable"]' \
+//      'Experimental'
+// @matches issue_32374/index.html '//*[@class="docblock-short"]/text()' 'Docs'
 
 // @has issue_32374/struct.T.html '//*[@class="stab deprecated"]' \
 //      'Deprecated since 1.0.0: text'
diff --git a/src/test/rustdoc/keyword.rs b/src/test/rustdoc/keyword.rs
index d3327ae..c721c02 100644
--- a/src/test/rustdoc/keyword.rs
+++ b/src/test/rustdoc/keyword.rs
@@ -7,7 +7,7 @@
 // @has foo/keyword.match.html '//a[@class="keyword"]' 'match'
 // @has foo/keyword.match.html '//span[@class="in-band"]' 'Keyword match'
 // @has foo/keyword.match.html '//section[@id="main"]//div[@class="docblock"]//p' 'this is a test!'
-// @!has foo/index.html '//a/@href' 'foo/index.html'
+// @has foo/index.html '//a/@href' '../foo/index.html'
 // @!has foo/foo/index.html
 // @!has-dir foo/foo
 #[doc(keyword = "match")]
diff --git a/src/test/rustdoc/stability.rs b/src/test/rustdoc/stability.rs
new file mode 100644
index 0000000..18a2160
--- /dev/null
+++ b/src/test/rustdoc/stability.rs
@@ -0,0 +1,12 @@
+#![feature(staged_api)]
+
+#![unstable(feature = "test", issue = "0")]
+
+pub struct Unstable {
+    // @has stability/struct.Unstable.html \
+    //      '//div[@class="stability"]//div[@class="stab unstable"]' \
+    //      'This is a nightly-only experimental API'
+    // @count stability/struct.Unstable.html '//span[@class="stab unstable"]' 0
+    pub foo: u32,
+    pub bar: u32,
+}
diff --git a/src/test/rustdoc/trait_alias.rs b/src/test/rustdoc/trait_alias.rs
new file mode 100644
index 0000000..98b8d87
--- /dev/null
+++ b/src/test/rustdoc/trait_alias.rs
@@ -0,0 +1,21 @@
+#![feature(trait_alias)]
+
+#![crate_name = "foo"]
+
+use std::fmt::Debug;
+
+// @has foo/all.html '//a[@href="traitalias.CopyAlias.html"]' 'CopyAlias'
+// @has foo/all.html '//a[@href="traitalias.Alias2.html"]' 'Alias2'
+// @has foo/all.html '//a[@href="traitalias.Foo.html"]' 'Foo'
+
+// @has foo/index.html '//h2[@id="trait-aliases"]' 'Trait aliases'
+// @has foo/index.html '//a[@class="traitalias"]' 'CopyAlias'
+// @has foo/index.html '//a[@class="traitalias"]' 'Alias2'
+// @has foo/index.html '//a[@class="traitalias"]' 'Foo'
+
+// @has foo/traitalias.CopyAlias.html '//section[@id="main"]/pre' 'trait CopyAlias = Copy;'
+pub trait CopyAlias = Copy;
+// @has foo/traitalias.Alias2.html '//section[@id="main"]/pre' 'trait Alias2 = Copy + Debug;'
+pub trait Alias2 = Copy + Debug;
+// @has foo/traitalias.Foo.html '//section[@id="main"]/pre' 'trait Foo<T> = Into<T> + Debug;'
+pub trait Foo<T> = Into<T> + Debug;
diff --git a/src/test/ui/attribute-with-no-generics-in-parameter-list.rs b/src/test/ui/attribute-with-no-generics-in-parameter-list.rs
new file mode 100644
index 0000000..c2cc91d
--- /dev/null
+++ b/src/test/ui/attribute-with-no-generics-in-parameter-list.rs
@@ -0,0 +1,3 @@
+fn foo<#[attr]>() {} //~ ERROR attribute without generic parameters
+
+fn main() {}
diff --git a/src/test/ui/attribute-with-no-generics-in-parameter-list.stderr b/src/test/ui/attribute-with-no-generics-in-parameter-list.stderr
new file mode 100644
index 0000000..f08f107
--- /dev/null
+++ b/src/test/ui/attribute-with-no-generics-in-parameter-list.stderr
@@ -0,0 +1,8 @@
+error: attribute without generic parameters
+  --> $DIR/attribute-with-no-generics-in-parameter-list.rs:1:8
+   |
+LL | fn foo<#[attr]>() {} //~ ERROR attribute without generic parameters
+   |        ^^^^^^^ attributes are only permitted when preceding parameters
+
+error: aborting due to previous error
+
diff --git a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-1.rs b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-1.rs
index d7feb03..ca5fdd9 100644
--- a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-1.rs
+++ b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-1.rs
@@ -7,7 +7,7 @@
 struct RefIntPair<'a, 'b>(&'a u32, &'b u32);
 
 impl<#[rustc_1] 'a, 'b, #[oops]> RefIntPair<'a, 'b> {
-    //~^ ERROR trailing attribute after lifetime parameters
+    //~^ ERROR trailing attribute after generic parameter
 }
 
 fn main() {
diff --git a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-1.stderr b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-1.stderr
index c4c0cee..55e7a98 100644
--- a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-1.stderr
+++ b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-1.stderr
@@ -1,4 +1,4 @@
-error: trailing attribute after lifetime parameters
+error: trailing attribute after generic parameter
   --> $DIR/attrs-with-no-formal-in-generics-1.rs:9:25
    |
 LL | impl<#[rustc_1] 'a, 'b, #[oops]> RefIntPair<'a, 'b> {
diff --git a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-2.rs b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-2.rs
index f9db6a5..c795612 100644
--- a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-2.rs
+++ b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-2.rs
@@ -7,6 +7,6 @@
 struct RefAny<'a, T>(&'a T);
 
 impl<#[rustc_1] 'a, #[rustc_2] T, #[oops]> RefAny<'a, T> {}
-//~^ ERROR trailing attribute after type parameters
+//~^ ERROR trailing attribute after generic parameter
 
 fn main() {}
diff --git a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-2.stderr b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-2.stderr
index 9099d74..acd0ae3 100644
--- a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-2.stderr
+++ b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-2.stderr
@@ -1,4 +1,4 @@
-error: trailing attribute after type parameters
+error: trailing attribute after generic parameter
   --> $DIR/attrs-with-no-formal-in-generics-2.rs:9:35
    |
 LL | impl<#[rustc_1] 'a, #[rustc_2] T, #[oops]> RefAny<'a, T> {}
diff --git a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-3.rs b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-3.rs
index e9f908d..3cfc70b 100644
--- a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-3.rs
+++ b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-3.rs
@@ -6,7 +6,7 @@
 
 fn hof_lt<Q>(_: Q)
     where Q: for <#[allow(unused)] 'a, 'b, #[oops]> Fn(RefIntPair<'a,'b>) -> &'b u32
-    //~^ ERROR trailing attribute after lifetime parameters
+    //~^ ERROR trailing attribute after generic parameter
 {}
 
 fn main() {}
diff --git a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-3.stderr b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-3.stderr
index 452f0ea..b9ca009 100644
--- a/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-3.stderr
+++ b/src/test/ui/attrs-with-no-formal-in-generics/attrs-with-no-formal-in-generics-3.stderr
@@ -1,4 +1,4 @@
-error: trailing attribute after lifetime parameters
+error: trailing attribute after generic parameter
   --> $DIR/attrs-with-no-formal-in-generics-3.rs:8:44
    |
 LL |     where Q: for <#[allow(unused)] 'a, 'b, #[oops]> Fn(RefIntPair<'a,'b>) -> &'b u32
diff --git a/src/test/ui/augmented-assignments.nll.stderr b/src/test/ui/augmented-assignments.nll.stderr
index 840b377..33c94d6 100644
--- a/src/test/ui/augmented-assignments.nll.stderr
+++ b/src/test/ui/augmented-assignments.nll.stderr
@@ -9,7 +9,7 @@
 LL | |     //~^ value used here after move
 LL | |     +=
 LL | |     x;  //~ value moved here
-   | |     -
+   | |     ^
    | |     |
    | |_____move out of `x` occurs here
    |       borrow later used here
diff --git a/src/test/ui/bad/bad-lint-cap2.stderr b/src/test/ui/bad/bad-lint-cap2.stderr
index d7ec414..b963872 100644
--- a/src/test/ui/bad/bad-lint-cap2.stderr
+++ b/src/test/ui/bad/bad-lint-cap2.stderr
@@ -2,7 +2,7 @@
   --> $DIR/bad-lint-cap2.rs:6:5
    |
 LL | use std::option; //~ ERROR
-   |     ^^^^^^^^^^^
+   | ----^^^^^^^^^^^- help: remove the whole `use` item
    |
 note: lint level defined here
   --> $DIR/bad-lint-cap2.rs:4:9
diff --git a/src/test/ui/bad/bad-lint-cap3.stderr b/src/test/ui/bad/bad-lint-cap3.stderr
index 5bf0b08..21ed50b 100644
--- a/src/test/ui/bad/bad-lint-cap3.stderr
+++ b/src/test/ui/bad/bad-lint-cap3.stderr
@@ -2,7 +2,7 @@
   --> $DIR/bad-lint-cap3.rs:7:5
    |
 LL | use std::option; //~ WARN
-   |     ^^^^^^^^^^^
+   | ----^^^^^^^^^^^- help: remove the whole `use` item
    |
 note: lint level defined here
   --> $DIR/bad-lint-cap3.rs:4:9
diff --git a/src/test/ui/bad/bad-type-env-capture.rs b/src/test/ui/bad/bad-type-env-capture.rs
index d2e6dff..53dfb13 100644
--- a/src/test/ui/bad/bad-type-env-capture.rs
+++ b/src/test/ui/bad/bad-type-env-capture.rs
@@ -1,4 +1,4 @@
 fn foo<T>() {
-    fn bar(b: T) { } //~ ERROR can't use type parameters from outer
+    fn bar(b: T) { } //~ ERROR can't use generic parameters from outer
 }
 fn main() { }
diff --git a/src/test/ui/bad/bad-type-env-capture.stderr b/src/test/ui/bad/bad-type-env-capture.stderr
index 5558a44..ce803e9 100644
--- a/src/test/ui/bad/bad-type-env-capture.stderr
+++ b/src/test/ui/bad/bad-type-env-capture.stderr
@@ -1,12 +1,12 @@
-error[E0401]: can't use type parameters from outer function
+error[E0401]: can't use generic parameters from outer function
   --> $DIR/bad-type-env-capture.rs:2:15
    |
 LL | fn foo<T>() {
    |        - type variable from outer function
-LL |     fn bar(b: T) { } //~ ERROR can't use type parameters from outer
-   |        ---    ^ use of type variable from outer function
+LL |     fn bar(b: T) { } //~ ERROR can't use generic parameters from outer
+   |        ---    ^ use of generic parameter from outer function
    |        |
-   |        help: try using a local type parameter instead: `bar<T>`
+   |        help: try using a local generic parameter instead: `bar<T>`
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/const-generics/const-expression-parameter.rs b/src/test/ui/const-generics/const-expression-parameter.rs
new file mode 100644
index 0000000..f4e9008
--- /dev/null
+++ b/src/test/ui/const-generics/const-expression-parameter.rs
@@ -0,0 +1,23 @@
+#![feature(const_generics)]
+//~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash
+
+fn u32_identity<const X: u32>() -> u32 {
+    //~^ ERROR const generics in any position are currently unsupported
+    5
+}
+
+fn foo_a() {
+    u32_identity::<-1>(); //~ ERROR expected identifier, found `<-`
+}
+
+fn foo_b() {
+    u32_identity::<1 + 2>(); //~ ERROR expected one of `,` or `>`, found `+`
+}
+
+fn foo_c() {
+    u32_identity::< -1 >(); // ok
+}
+
+fn main() {
+    u32_identity::<5>(); // ok
+}
diff --git a/src/test/ui/const-generics/const-expression-parameter.stderr b/src/test/ui/const-generics/const-expression-parameter.stderr
new file mode 100644
index 0000000..1dd3a96
--- /dev/null
+++ b/src/test/ui/const-generics/const-expression-parameter.stderr
@@ -0,0 +1,26 @@
+error: expected identifier, found `<-`
+  --> $DIR/const-expression-parameter.rs:10:19
+   |
+LL |     u32_identity::<-1>(); //~ ERROR expected identifier, found `<-`
+   |                   ^^ expected identifier
+
+error: expected one of `,` or `>`, found `+`
+  --> $DIR/const-expression-parameter.rs:14:22
+   |
+LL |     u32_identity::<1 + 2>(); //~ ERROR expected one of `,` or `>`, found `+`
+   |                      ^ expected one of `,` or `>` here
+
+warning: the feature `const_generics` is incomplete and may cause the compiler to crash
+  --> $DIR/const-expression-parameter.rs:1:12
+   |
+LL | #![feature(const_generics)]
+   |            ^^^^^^^^^^^^^^
+
+error: const generics in any position are currently unsupported
+  --> $DIR/const-expression-parameter.rs:4:23
+   |
+LL | fn u32_identity<const X: u32>() -> u32 {
+   |                       ^
+
+error: aborting due to 3 previous errors
+
diff --git a/src/test/ui/const-generics/const-fn-with-const-param.rs b/src/test/ui/const-generics/const-fn-with-const-param.rs
new file mode 100644
index 0000000..052d723
--- /dev/null
+++ b/src/test/ui/const-generics/const-fn-with-const-param.rs
@@ -0,0 +1,12 @@
+#![feature(const_generics)]
+//~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash
+
+const fn const_u32_identity<const X: u32>() -> u32 {
+    //~^ ERROR const parameters are not permitted in `const fn`
+    //~^^ ERROR const generics in any position are currently unsupported
+    X
+}
+
+fn main() {
+    println!("{:?}", const_u32_identity::<18>());
+}
diff --git a/src/test/ui/const-generics/const-fn-with-const-param.stderr b/src/test/ui/const-generics/const-fn-with-const-param.stderr
new file mode 100644
index 0000000..a08ebfb
--- /dev/null
+++ b/src/test/ui/const-generics/const-fn-with-const-param.stderr
@@ -0,0 +1,24 @@
+warning: the feature `const_generics` is incomplete and may cause the compiler to crash
+  --> $DIR/const-fn-with-const-param.rs:1:12
+   |
+LL | #![feature(const_generics)]
+   |            ^^^^^^^^^^^^^^
+
+error: const parameters are not permitted in `const fn`
+  --> $DIR/const-fn-with-const-param.rs:4:1
+   |
+LL | / const fn const_u32_identity<const X: u32>() -> u32 {
+LL | |     //~^ ERROR const parameters are not permitted in `const fn`
+LL | |     //~^^ ERROR const generics in any position are currently unsupported
+LL | |     X
+LL | | }
+   | |_^
+
+error: const generics in any position are currently unsupported
+  --> $DIR/const-fn-with-const-param.rs:4:35
+   |
+LL | const fn const_u32_identity<const X: u32>() -> u32 {
+   |                                   ^
+
+error: aborting due to 2 previous errors
+
diff --git a/src/test/ui/const-generics/const-param-before-other-params.rs b/src/test/ui/const-generics/const-param-before-other-params.rs
new file mode 100644
index 0000000..3f120cb
--- /dev/null
+++ b/src/test/ui/const-generics/const-param-before-other-params.rs
@@ -0,0 +1,13 @@
+#![feature(const_generics)]
+//~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash
+
+fn foo<const X: (), T>(_: T) {
+    //~^ ERROR type parameters must be declared prior to const parameters
+    //~^^ ERROR const generics in any position are currently unsupported
+}
+
+fn bar<const X: (), 'a>(_: &'a ()) {
+    //~^ ERROR lifetime parameters must be declared prior to const parameters
+}
+
+fn main() {}
diff --git a/src/test/ui/const-generics/const-param-before-other-params.stderr b/src/test/ui/const-generics/const-param-before-other-params.stderr
new file mode 100644
index 0000000..aedcaf5
--- /dev/null
+++ b/src/test/ui/const-generics/const-param-before-other-params.stderr
@@ -0,0 +1,26 @@
+warning: the feature `const_generics` is incomplete and may cause the compiler to crash
+  --> $DIR/const-param-before-other-params.rs:1:12
+   |
+LL | #![feature(const_generics)]
+   |            ^^^^^^^^^^^^^^
+
+error: type parameters must be declared prior to const parameters
+  --> $DIR/const-param-before-other-params.rs:4:21
+   |
+LL | fn foo<const X: (), T>(_: T) {
+   |       --------------^- help: reorder the parameters: lifetimes, then types, then consts: `<T, const X: ()>`
+
+error: lifetime parameters must be declared prior to const parameters
+  --> $DIR/const-param-before-other-params.rs:9:21
+   |
+LL | fn bar<const X: (), 'a>(_: &'a ()) {
+   |       --------------^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, const X: ()>`
+
+error: const generics in any position are currently unsupported
+  --> $DIR/const-param-before-other-params.rs:4:14
+   |
+LL | fn foo<const X: (), T>(_: T) {
+   |              ^
+
+error: aborting due to 3 previous errors
+
diff --git a/src/test/ui/const-generics/const-param-from-outer-fn.rs b/src/test/ui/const-generics/const-param-from-outer-fn.rs
new file mode 100644
index 0000000..5a8dd92
--- /dev/null
+++ b/src/test/ui/const-generics/const-param-from-outer-fn.rs
@@ -0,0 +1,11 @@
+#![feature(const_generics)]
+//~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash
+
+fn foo<const X: u32>() {
+    //~^ ERROR const generics in any position are currently unsupported
+    fn bar() -> u32 {
+        X //~ ERROR can't use generic parameters from outer function
+    }
+}
+
+fn main() {}
diff --git a/src/test/ui/const-generics/const-param-from-outer-fn.stderr b/src/test/ui/const-generics/const-param-from-outer-fn.stderr
new file mode 100644
index 0000000..b238b3a
--- /dev/null
+++ b/src/test/ui/const-generics/const-param-from-outer-fn.stderr
@@ -0,0 +1,26 @@
+warning: the feature `const_generics` is incomplete and may cause the compiler to crash
+  --> $DIR/const-param-from-outer-fn.rs:1:12
+   |
+LL | #![feature(const_generics)]
+   |            ^^^^^^^^^^^^^^
+
+error[E0401]: can't use generic parameters from outer function
+  --> $DIR/const-param-from-outer-fn.rs:7:9
+   |
+LL | fn foo<const X: u32>() {
+   |              - const variable from outer function
+LL |     //~^ ERROR const generics in any position are currently unsupported
+LL |     fn bar() -> u32 {
+   |        --- try adding a local generic parameter in this method instead
+LL |         X //~ ERROR can't use generic parameters from outer function
+   |         ^ use of generic parameter from outer function
+
+error: const generics in any position are currently unsupported
+  --> $DIR/const-param-from-outer-fn.rs:4:14
+   |
+LL | fn foo<const X: u32>() {
+   |              ^
+
+error: aborting due to 2 previous errors
+
+For more information about this error, try `rustc --explain E0401`.
diff --git a/src/test/ui/duplicate/duplicate-type-parameter.stderr b/src/test/ui/duplicate/duplicate-type-parameter.stderr
index 41750d4..17d48ed 100644
--- a/src/test/ui/duplicate/duplicate-type-parameter.stderr
+++ b/src/test/ui/duplicate/duplicate-type-parameter.stderr
@@ -1,4 +1,4 @@
-error[E0403]: the name `T` is already used for a type parameter in this type parameter list
+error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters
   --> $DIR/duplicate-type-parameter.rs:1:12
    |
 LL | type Foo<T,T> = Option<T>;
@@ -6,7 +6,7 @@
    |          |
    |          first use of `T`
 
-error[E0403]: the name `T` is already used for a type parameter in this type parameter list
+error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters
   --> $DIR/duplicate-type-parameter.rs:4:14
    |
 LL | struct Bar<T,T>(T);
@@ -14,7 +14,7 @@
    |            |
    |            first use of `T`
 
-error[E0403]: the name `T` is already used for a type parameter in this type parameter list
+error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters
   --> $DIR/duplicate-type-parameter.rs:7:14
    |
 LL | struct Baz<T,T> {
@@ -22,7 +22,7 @@
    |            |
    |            first use of `T`
 
-error[E0403]: the name `T` is already used for a type parameter in this type parameter list
+error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters
   --> $DIR/duplicate-type-parameter.rs:12:12
    |
 LL | enum Boo<T,T> {
@@ -30,7 +30,7 @@
    |          |
    |          first use of `T`
 
-error[E0403]: the name `T` is already used for a type parameter in this type parameter list
+error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters
   --> $DIR/duplicate-type-parameter.rs:18:11
    |
 LL | fn quux<T,T>(x: T) {}
@@ -38,7 +38,7 @@
    |         |
    |         first use of `T`
 
-error[E0403]: the name `T` is already used for a type parameter in this type parameter list
+error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters
   --> $DIR/duplicate-type-parameter.rs:21:13
    |
 LL | trait Qux<T,T> {}
@@ -46,7 +46,7 @@
    |           |
    |           first use of `T`
 
-error[E0403]: the name `T` is already used for a type parameter in this type parameter list
+error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters
   --> $DIR/duplicate-type-parameter.rs:24:8
    |
 LL | impl<T,T> Qux<T,T> for Option<T> {}
diff --git a/src/test/ui/error-codes/E0401.stderr b/src/test/ui/error-codes/E0401.stderr
index c94fa49..27f281e 100644
--- a/src/test/ui/error-codes/E0401.stderr
+++ b/src/test/ui/error-codes/E0401.stderr
@@ -1,26 +1,26 @@
-error[E0401]: can't use type parameters from outer function
+error[E0401]: can't use generic parameters from outer function
   --> $DIR/E0401.rs:4:39
    |
 LL | fn foo<T>(x: T) {
    |        - type variable from outer function
 LL |     fn bfnr<U, V: Baz<U>, W: Fn()>(y: T) { //~ ERROR E0401
-   |        ---------------------------    ^ use of type variable from outer function
+   |        ---------------------------    ^ use of generic parameter from outer function
    |        |
-   |        help: try using a local type parameter instead: `bfnr<U, V: Baz<U>, W: Fn(), T>`
+   |        help: try using a local generic parameter instead: `bfnr<U, V: Baz<U>, W: Fn(), T>`
 
-error[E0401]: can't use type parameters from outer function
+error[E0401]: can't use generic parameters from outer function
   --> $DIR/E0401.rs:9:16
    |
 LL | fn foo<T>(x: T) {
    |        - type variable from outer function
 ...
 LL |     fn baz<U,
-   |        --- try adding a local type parameter in this method instead
+   |        --- try adding a local generic parameter in this method instead
 ...
 LL |            (y: T) { //~ ERROR E0401
-   |                ^ use of type variable from outer function
+   |                ^ use of generic parameter from outer function
 
-error[E0401]: can't use type parameters from outer function
+error[E0401]: can't use generic parameters from outer function
   --> $DIR/E0401.rs:22:25
    |
 LL | impl<T> Iterator for A<T> {
@@ -29,7 +29,7 @@
 LL |         fn helper(sel: &Self) -> u8 { //~ ERROR E0401
    |                         ^^^^
    |                         |
-   |                         use of type variable from outer function
+   |                         use of generic parameter from outer function
    |                         use a type here instead
 
 error: aborting due to 3 previous errors
diff --git a/src/test/ui/error-codes/E0403.stderr b/src/test/ui/error-codes/E0403.stderr
index 919a82d..b924647 100644
--- a/src/test/ui/error-codes/E0403.stderr
+++ b/src/test/ui/error-codes/E0403.stderr
@@ -1,4 +1,4 @@
-error[E0403]: the name `T` is already used for a type parameter in this type parameter list
+error[E0403]: the name `T` is already used for a generic parameter in this list of generic parameters
   --> $DIR/E0403.rs:1:11
    |
 LL | fn foo<T, T>(s: T, u: T) {} //~ ERROR E0403
diff --git a/src/test/ui/feature-gates/feature-gate-const_generics.rs b/src/test/ui/feature-gates/feature-gate-const_generics.rs
new file mode 100644
index 0000000..a8a4ed5
--- /dev/null
+++ b/src/test/ui/feature-gates/feature-gate-const_generics.rs
@@ -0,0 +1,6 @@
+fn foo<const X: ()>() {} //~ ERROR const generics are unstable
+//~^ const generics in any position are currently unsupported
+
+struct Foo<const X: usize>([(); X]); //~ ERROR const generics are unstable
+
+fn main() {}
diff --git a/src/test/ui/feature-gates/feature-gate-const_generics.stderr b/src/test/ui/feature-gates/feature-gate-const_generics.stderr
new file mode 100644
index 0000000..905cc07
--- /dev/null
+++ b/src/test/ui/feature-gates/feature-gate-const_generics.stderr
@@ -0,0 +1,25 @@
+error[E0658]: const generics are unstable (see issue #44580)
+  --> $DIR/feature-gate-const_generics.rs:1:14
+   |
+LL | fn foo<const X: ()>() {} //~ ERROR const generics are unstable
+   |              ^
+   |
+   = help: add #![feature(const_generics)] to the crate attributes to enable
+
+error[E0658]: const generics are unstable (see issue #44580)
+  --> $DIR/feature-gate-const_generics.rs:4:18
+   |
+LL | struct Foo<const X: usize>([(); X]); //~ ERROR const generics are unstable
+   |                  ^
+   |
+   = help: add #![feature(const_generics)] to the crate attributes to enable
+
+error: const generics in any position are currently unsupported
+  --> $DIR/feature-gate-const_generics.rs:1:14
+   |
+LL | fn foo<const X: ()>() {} //~ ERROR const generics are unstable
+   |              ^
+
+error: aborting due to 3 previous errors
+
+For more information about this error, try `rustc --explain E0658`.
diff --git a/src/test/ui/impl-trait/bindings.rs b/src/test/ui/impl-trait/bindings.rs
index 8993036..91d0926 100644
--- a/src/test/ui/impl-trait/bindings.rs
+++ b/src/test/ui/impl-trait/bindings.rs
@@ -2,27 +2,27 @@
 
 fn a<T: Clone>(x: T) {
     const foo: impl Clone = x;
-//~^ ERROR can't capture dynamic environment in a fn item
+    //~^ ERROR attempt to use a non-constant value in a constant
 }
 
 fn b<T: Clone>(x: T) {
     let _ = move || {
         const foo: impl Clone = x;
-//~^ ERROR can't capture dynamic environment in a fn item
+        //~^ ERROR attempt to use a non-constant value in a constant
     };
 }
 
 trait Foo<T: Clone> {
     fn a(x: T) {
         const foo: impl Clone = x;
-//~^ ERROR can't capture dynamic environment in a fn item
+        //~^ ERROR attempt to use a non-constant value in a constant
     }
 }
 
 impl<T: Clone> Foo<T> for i32 {
     fn a(x: T) {
         const foo: impl Clone = x;
-//~^ ERROR can't capture dynamic environment in a fn item
+        //~^ ERROR attempt to use a non-constant value in a constant
     }
 }
 
diff --git a/src/test/ui/impl-trait/bindings.stderr b/src/test/ui/impl-trait/bindings.stderr
index 2a9be7a..a5bf583 100644
--- a/src/test/ui/impl-trait/bindings.stderr
+++ b/src/test/ui/impl-trait/bindings.stderr
@@ -1,35 +1,27 @@
-error[E0434]: can't capture dynamic environment in a fn item
+error[E0435]: attempt to use a non-constant value in a constant
   --> $DIR/bindings.rs:4:29
    |
 LL |     const foo: impl Clone = x;
-   |                             ^
-   |
-   = help: use the `|| { ... }` closure form instead
+   |                             ^ non-constant value
 
-error[E0434]: can't capture dynamic environment in a fn item
+error[E0435]: attempt to use a non-constant value in a constant
   --> $DIR/bindings.rs:10:33
    |
 LL |         const foo: impl Clone = x;
-   |                                 ^
-   |
-   = help: use the `|| { ... }` closure form instead
+   |                                 ^ non-constant value
 
-error[E0434]: can't capture dynamic environment in a fn item
+error[E0435]: attempt to use a non-constant value in a constant
   --> $DIR/bindings.rs:17:33
    |
 LL |         const foo: impl Clone = x;
-   |                                 ^
-   |
-   = help: use the `|| { ... }` closure form instead
+   |                                 ^ non-constant value
 
-error[E0434]: can't capture dynamic environment in a fn item
+error[E0435]: attempt to use a non-constant value in a constant
   --> $DIR/bindings.rs:24:33
    |
 LL |         const foo: impl Clone = x;
-   |                                 ^
-   |
-   = help: use the `|| { ... }` closure form instead
+   |                                 ^ non-constant value
 
 error: aborting due to 4 previous errors
 
-For more information about this error, try `rustc --explain E0434`.
+For more information about this error, try `rustc --explain E0435`.
diff --git a/src/test/ui/imports/unused.stderr b/src/test/ui/imports/unused.stderr
index b56e930..fa82e97 100644
--- a/src/test/ui/imports/unused.stderr
+++ b/src/test/ui/imports/unused.stderr
@@ -2,7 +2,7 @@
   --> $DIR/unused.rs:7:24
    |
 LL |         pub(super) use super::f; //~ ERROR unused
-   |                        ^^^^^^^^
+   |         ---------------^^^^^^^^- help: remove the whole `use` item
    |
 note: lint level defined here
   --> $DIR/unused.rs:1:9
diff --git a/src/test/ui/inner-static-type-parameter.rs b/src/test/ui/inner-static-type-parameter.rs
index 60b4c5b..c08ccd2 100644
--- a/src/test/ui/inner-static-type-parameter.rs
+++ b/src/test/ui/inner-static-type-parameter.rs
@@ -4,7 +4,7 @@
 
 fn foo<T>() {
     static a: Bar<T> = Bar::What;
-//~^ ERROR can't use type parameters from outer function
+//~^ ERROR can't use generic parameters from outer function
 }
 
 fn main() {
diff --git a/src/test/ui/inner-static-type-parameter.stderr b/src/test/ui/inner-static-type-parameter.stderr
index 2f2856e..87fb364 100644
--- a/src/test/ui/inner-static-type-parameter.stderr
+++ b/src/test/ui/inner-static-type-parameter.stderr
@@ -1,12 +1,12 @@
-error[E0401]: can't use type parameters from outer function
+error[E0401]: can't use generic parameters from outer function
   --> $DIR/inner-static-type-parameter.rs:6:19
    |
 LL | fn foo<T>() {
    |    --- - type variable from outer function
    |    |
-   |    try adding a local type parameter in this method instead
+   |    try adding a local generic parameter in this method instead
 LL |     static a: Bar<T> = Bar::What;
-   |                   ^ use of type variable from outer function
+   |                   ^ use of generic parameter from outer function
 
 error[E0392]: parameter `T` is never used
   --> $DIR/inner-static-type-parameter.rs:3:10
diff --git a/src/test/ui/issues/issue-12796.rs b/src/test/ui/issues/issue-12796.rs
index acd4584..942d6b9 100644
--- a/src/test/ui/issues/issue-12796.rs
+++ b/src/test/ui/issues/issue-12796.rs
@@ -1,7 +1,7 @@
 trait Trait {
     fn outer(&self) {
         fn inner(_: &Self) {
-            //~^ ERROR can't use type parameters from outer function
+            //~^ ERROR can't use generic parameters from outer function
         }
     }
 }
diff --git a/src/test/ui/issues/issue-12796.stderr b/src/test/ui/issues/issue-12796.stderr
index 4bc29fd..a01fd2d 100644
--- a/src/test/ui/issues/issue-12796.stderr
+++ b/src/test/ui/issues/issue-12796.stderr
@@ -1,10 +1,10 @@
-error[E0401]: can't use type parameters from outer function
+error[E0401]: can't use generic parameters from outer function
   --> $DIR/issue-12796.rs:3:22
    |
 LL |         fn inner(_: &Self) {
    |                      ^^^^
    |                      |
-   |                      use of type variable from outer function
+   |                      use of generic parameter from outer function
    |                      can't use `Self` here
 
 error: aborting due to previous error
diff --git a/src/test/ui/issues/issue-20616-3.rs b/src/test/ui/issues/issue-20616-3.rs
index e84506e..9bfd5bf 100644
--- a/src/test/ui/issues/issue-20616-3.rs
+++ b/src/test/ui/issues/issue-20616-3.rs
@@ -1,8 +1,6 @@
 // We need all these 9 issue-20616-N.rs files
 // because we can only catch one parsing error at a time
 
-
-
 type Type_1_<'a, T> = &'a T;
 
 
@@ -12,7 +10,8 @@
 //type Type_2 = Type_1_<'static ()>; // error: expected `,` or `>` after lifetime name, found `(`
 
 
-type Type_3<T> = Box<T,,>; //~ error: expected one of `>`, identifier, lifetime, or type, found `,`
+type Type_3<T> = Box<T,,>;
+//~^ error: expected one of `>`, const, identifier, lifetime, or type, found `,`
 
 
 //type Type_4<T> = Type_1_<'static,, T>; // error: expected type, found `,`
diff --git a/src/test/ui/issues/issue-20616-3.stderr b/src/test/ui/issues/issue-20616-3.stderr
index 5247298..f51fb94 100644
--- a/src/test/ui/issues/issue-20616-3.stderr
+++ b/src/test/ui/issues/issue-20616-3.stderr
@@ -1,8 +1,8 @@
-error: expected one of `>`, identifier, lifetime, or type, found `,`
-  --> $DIR/issue-20616-3.rs:15:24
+error: expected one of `>`, const, identifier, lifetime, or type, found `,`
+  --> $DIR/issue-20616-3.rs:13:24
    |
-LL | type Type_3<T> = Box<T,,>; //~ error: expected one of `>`, identifier, lifetime, or type, found `,`
-   |                        ^ expected one of `>`, identifier, lifetime, or type here
+LL | type Type_3<T> = Box<T,,>;
+   |                        ^ expected one of `>`, const, identifier, lifetime, or type here
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/issues/issue-20616-4.rs b/src/test/ui/issues/issue-20616-4.rs
index 785a6fa..e9a34a0 100644
--- a/src/test/ui/issues/issue-20616-4.rs
+++ b/src/test/ui/issues/issue-20616-4.rs
@@ -1,8 +1,6 @@
 // We need all these 9 issue-20616-N.rs files
 // because we can only catch one parsing error at a time
 
-
-
 type Type_1_<'a, T> = &'a T;
 
 
@@ -16,7 +14,7 @@
 
 
 type Type_4<T> = Type_1_<'static,, T>;
-//~^ error: expected one of `>`, identifier, lifetime, or type, found `,`
+//~^ error: expected one of `>`, const, identifier, lifetime, or type, found `,`
 
 
 type Type_5_<'a> = Type_1_<'a, ()>;
diff --git a/src/test/ui/issues/issue-20616-4.stderr b/src/test/ui/issues/issue-20616-4.stderr
index 74c38d9..22a6554 100644
--- a/src/test/ui/issues/issue-20616-4.stderr
+++ b/src/test/ui/issues/issue-20616-4.stderr
@@ -1,8 +1,8 @@
-error: expected one of `>`, identifier, lifetime, or type, found `,`
-  --> $DIR/issue-20616-4.rs:18:34
+error: expected one of `>`, const, identifier, lifetime, or type, found `,`
+  --> $DIR/issue-20616-4.rs:16:34
    |
 LL | type Type_4<T> = Type_1_<'static,, T>;
-   |                                  ^ expected one of `>`, identifier, lifetime, or type here
+   |                                  ^ expected one of `>`, const, identifier, lifetime, or type here
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/issues/issue-20616-5.rs b/src/test/ui/issues/issue-20616-5.rs
index 71dcc1f..2386251 100644
--- a/src/test/ui/issues/issue-20616-5.rs
+++ b/src/test/ui/issues/issue-20616-5.rs
@@ -1,8 +1,6 @@
 // We need all these 9 issue-20616-N.rs files
 // because we can only catch one parsing error at a time
 
-
-
 type Type_1_<'a, T> = &'a T;
 
 
@@ -22,7 +20,7 @@
 
 
 type Type_5<'a> = Type_1_<'a, (),,>;
-//~^ error: expected one of `>`, identifier, lifetime, or type, found `,`
+//~^ error: expected one of `>`, const, identifier, lifetime, or type, found `,`
 
 
 //type Type_6 = Type_5_<'a,,>; // error: expected type, found `,`
diff --git a/src/test/ui/issues/issue-20616-5.stderr b/src/test/ui/issues/issue-20616-5.stderr
index 38457be..d83fc41 100644
--- a/src/test/ui/issues/issue-20616-5.stderr
+++ b/src/test/ui/issues/issue-20616-5.stderr
@@ -1,8 +1,8 @@
-error: expected one of `>`, identifier, lifetime, or type, found `,`
-  --> $DIR/issue-20616-5.rs:24:34
+error: expected one of `>`, const, identifier, lifetime, or type, found `,`
+  --> $DIR/issue-20616-5.rs:22:34
    |
 LL | type Type_5<'a> = Type_1_<'a, (),,>;
-   |                                  ^ expected one of `>`, identifier, lifetime, or type here
+   |                                  ^ expected one of `>`, const, identifier, lifetime, or type here
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/issues/issue-20616-6.rs b/src/test/ui/issues/issue-20616-6.rs
index da32da4..dc327f3 100644
--- a/src/test/ui/issues/issue-20616-6.rs
+++ b/src/test/ui/issues/issue-20616-6.rs
@@ -1,8 +1,6 @@
 // We need all these 9 issue-20616-N.rs files
 // because we can only catch one parsing error at a time
 
-
-
 type Type_1_<'a, T> = &'a T;
 
 
@@ -25,7 +23,7 @@
 
 
 type Type_6 = Type_5_<'a,,>;
-//~^ error: expected one of `>`, identifier, lifetime, or type, found `,`
+//~^ error: expected one of `>`, const, identifier, lifetime, or type, found `,`
 
 
 //type Type_7 = Box<(),,>; // error: expected type, found `,`
diff --git a/src/test/ui/issues/issue-20616-6.stderr b/src/test/ui/issues/issue-20616-6.stderr
index 55b1d03..0740df5 100644
--- a/src/test/ui/issues/issue-20616-6.stderr
+++ b/src/test/ui/issues/issue-20616-6.stderr
@@ -1,8 +1,8 @@
-error: expected one of `>`, identifier, lifetime, or type, found `,`
-  --> $DIR/issue-20616-6.rs:27:26
+error: expected one of `>`, const, identifier, lifetime, or type, found `,`
+  --> $DIR/issue-20616-6.rs:25:26
    |
 LL | type Type_6 = Type_5_<'a,,>;
-   |                          ^ expected one of `>`, identifier, lifetime, or type here
+   |                          ^ expected one of `>`, const, identifier, lifetime, or type here
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/issues/issue-20616-7.rs b/src/test/ui/issues/issue-20616-7.rs
index feaaff2..ffd1620 100644
--- a/src/test/ui/issues/issue-20616-7.rs
+++ b/src/test/ui/issues/issue-20616-7.rs
@@ -1,8 +1,6 @@
 // We need all these 9 issue-20616-N.rs files
 // because we can only catch one parsing error at a time
 
-
-
 type Type_1_<'a, T> = &'a T;
 
 
@@ -27,7 +25,8 @@
 //type Type_6 = Type_5_<'a,,>; // error: expected type, found `,`
 
 
-type Type_7 = Box<(),,>; //~ error: expected one of `>`, identifier, lifetime, or type, found `,`
+type Type_7 = Box<(),,>;
+//~^ error: expected one of `>`, const, identifier, lifetime, or type, found `,`
 
 
 //type Type_8<'a,,> = &'a (); // error: expected ident, found `,`
diff --git a/src/test/ui/issues/issue-20616-7.stderr b/src/test/ui/issues/issue-20616-7.stderr
index 8b5f67c..c0e1083 100644
--- a/src/test/ui/issues/issue-20616-7.stderr
+++ b/src/test/ui/issues/issue-20616-7.stderr
@@ -1,8 +1,8 @@
-error: expected one of `>`, identifier, lifetime, or type, found `,`
-  --> $DIR/issue-20616-7.rs:30:22
+error: expected one of `>`, const, identifier, lifetime, or type, found `,`
+  --> $DIR/issue-20616-7.rs:28:22
    |
-LL | type Type_7 = Box<(),,>; //~ error: expected one of `>`, identifier, lifetime, or type, found `,`
-   |                      ^ expected one of `>`, identifier, lifetime, or type here
+LL | type Type_7 = Box<(),,>;
+   |                      ^ expected one of `>`, const, identifier, lifetime, or type here
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/issues/issue-20616-8.rs b/src/test/ui/issues/issue-20616-8.rs
index 2fc7243..c9e8b61 100644
--- a/src/test/ui/issues/issue-20616-8.rs
+++ b/src/test/ui/issues/issue-20616-8.rs
@@ -1,8 +1,6 @@
 // We need all these 9 issue-20616-N.rs files
 // because we can only catch one parsing error at a time
 
-
-
 type Type_1_<'a, T> = &'a T;
 
 
@@ -30,7 +28,8 @@
 //type Type_7 = Box<(),,>; // error: expected type, found `,`
 
 
-type Type_8<'a,,> = &'a (); //~ error: expected one of `>`, identifier, or lifetime, found `,`
+type Type_8<'a,,> = &'a ();
+//~^ error: expected one of `>`, `const`, identifier, or lifetime, found `,`
 
 
 //type Type_9<T,,> = Box<T>; // error: expected identifier, found `,`
diff --git a/src/test/ui/issues/issue-20616-8.stderr b/src/test/ui/issues/issue-20616-8.stderr
index cdeb544..0ef9192 100644
--- a/src/test/ui/issues/issue-20616-8.stderr
+++ b/src/test/ui/issues/issue-20616-8.stderr
@@ -1,8 +1,8 @@
-error: expected one of `>`, identifier, or lifetime, found `,`
-  --> $DIR/issue-20616-8.rs:33:16
+error: expected one of `>`, `const`, identifier, or lifetime, found `,`
+  --> $DIR/issue-20616-8.rs:31:16
    |
-LL | type Type_8<'a,,> = &'a (); //~ error: expected one of `>`, identifier, or lifetime, found `,`
-   |                ^ expected one of `>`, identifier, or lifetime here
+LL | type Type_8<'a,,> = &'a ();
+   |                ^ expected one of `>`, `const`, identifier, or lifetime here
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/issues/issue-20616-9.rs b/src/test/ui/issues/issue-20616-9.rs
index b14a5b0..1c509f2 100644
--- a/src/test/ui/issues/issue-20616-9.rs
+++ b/src/test/ui/issues/issue-20616-9.rs
@@ -1,8 +1,6 @@
 // We need all these 9 issue-20616-N.rs files
 // because we can only catch one parsing error at a time
 
-
-
 type Type_1_<'a, T> = &'a T;
 
 
@@ -33,4 +31,5 @@
 //type Type_8<'a,,> = &'a (); // error: expected identifier, found `,`
 
 
-type Type_9<T,,> = Box<T>; //~ error: expected one of `>`, identifier, or lifetime, found `,`
+type Type_9<T,,> = Box<T>;
+//~^ error: expected one of `>`, `const`, identifier, or lifetime, found `,`
diff --git a/src/test/ui/issues/issue-20616-9.stderr b/src/test/ui/issues/issue-20616-9.stderr
index dfe705c..5fd1400 100644
--- a/src/test/ui/issues/issue-20616-9.stderr
+++ b/src/test/ui/issues/issue-20616-9.stderr
@@ -1,8 +1,8 @@
-error: expected one of `>`, identifier, or lifetime, found `,`
-  --> $DIR/issue-20616-9.rs:36:15
+error: expected one of `>`, `const`, identifier, or lifetime, found `,`
+  --> $DIR/issue-20616-9.rs:34:15
    |
-LL | type Type_9<T,,> = Box<T>; //~ error: expected one of `>`, identifier, or lifetime, found `,`
-   |               ^ expected one of `>`, identifier, or lifetime here
+LL | type Type_9<T,,> = Box<T>;
+   |               ^ expected one of `>`, `const`, identifier, or lifetime here
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/issues/issue-27433.rs b/src/test/ui/issues/issue-27433.rs
index 2cc7d05..156ae68 100644
--- a/src/test/ui/issues/issue-27433.rs
+++ b/src/test/ui/issues/issue-27433.rs
@@ -1,5 +1,5 @@
 fn main() {
     let foo = 42u32;
     const FOO : u32 = foo;
-                   //~^ ERROR can't capture dynamic environment
+                   //~^ ERROR attempt to use a non-constant value in a constant
 }
diff --git a/src/test/ui/issues/issue-27433.stderr b/src/test/ui/issues/issue-27433.stderr
index 78a193d..e232d17 100644
--- a/src/test/ui/issues/issue-27433.stderr
+++ b/src/test/ui/issues/issue-27433.stderr
@@ -1,11 +1,9 @@
-error[E0434]: can't capture dynamic environment in a fn item
+error[E0435]: attempt to use a non-constant value in a constant
   --> $DIR/issue-27433.rs:3:23
    |
 LL |     const FOO : u32 = foo;
-   |                       ^^^
-   |
-   = help: use the `|| { ... }` closure form instead
+   |                       ^^^ non-constant value
 
 error: aborting due to previous error
 
-For more information about this error, try `rustc --explain E0434`.
+For more information about this error, try `rustc --explain E0435`.
diff --git a/src/test/ui/issues/issue-3021-c.rs b/src/test/ui/issues/issue-3021-c.rs
index 4913362..94ed1fd 100644
--- a/src/test/ui/issues/issue-3021-c.rs
+++ b/src/test/ui/issues/issue-3021-c.rs
@@ -1,8 +1,8 @@
 fn siphash<T>() {
 
     trait U {
-        fn g(&self, x: T) -> T;  //~ ERROR can't use type parameters from outer function
-        //~^ ERROR can't use type parameters from outer function
+        fn g(&self, x: T) -> T;  //~ ERROR can't use generic parameters from outer function
+        //~^ ERROR can't use generic parameters from outer function
     }
 }
 
diff --git a/src/test/ui/issues/issue-3021-c.stderr b/src/test/ui/issues/issue-3021-c.stderr
index 323ce4f..5eadf78 100644
--- a/src/test/ui/issues/issue-3021-c.stderr
+++ b/src/test/ui/issues/issue-3021-c.stderr
@@ -1,24 +1,24 @@
-error[E0401]: can't use type parameters from outer function
+error[E0401]: can't use generic parameters from outer function
   --> $DIR/issue-3021-c.rs:4:24
    |
 LL | fn siphash<T>() {
    |            - type variable from outer function
 ...
-LL |         fn g(&self, x: T) -> T;  //~ ERROR can't use type parameters from outer function
-   |            -           ^ use of type variable from outer function
+LL |         fn g(&self, x: T) -> T;  //~ ERROR can't use generic parameters from outer function
+   |            -           ^ use of generic parameter from outer function
    |            |
-   |            help: try using a local type parameter instead: `g<T>`
+   |            help: try using a local generic parameter instead: `g<T>`
 
-error[E0401]: can't use type parameters from outer function
+error[E0401]: can't use generic parameters from outer function
   --> $DIR/issue-3021-c.rs:4:30
    |
 LL | fn siphash<T>() {
    |            - type variable from outer function
 ...
-LL |         fn g(&self, x: T) -> T;  //~ ERROR can't use type parameters from outer function
-   |            -                 ^ use of type variable from outer function
+LL |         fn g(&self, x: T) -> T;  //~ ERROR can't use generic parameters from outer function
+   |            -                 ^ use of generic parameter from outer function
    |            |
-   |            help: try using a local type parameter instead: `g<T>`
+   |            help: try using a local generic parameter instead: `g<T>`
 
 error: aborting due to 2 previous errors
 
diff --git a/src/test/ui/issues/issue-30730.stderr b/src/test/ui/issues/issue-30730.stderr
index 0a90107..3cfadd3 100644
--- a/src/test/ui/issues/issue-30730.stderr
+++ b/src/test/ui/issues/issue-30730.stderr
@@ -2,7 +2,7 @@
   --> $DIR/issue-30730.rs:3:5
    |
 LL | use std::thread;
-   |     ^^^^^^^^^^^
+   | ----^^^^^^^^^^^- help: remove the whole `use` item
    |
 note: lint level defined here
   --> $DIR/issue-30730.rs:2:9
diff --git a/src/test/ui/issues/issue-3214.rs b/src/test/ui/issues/issue-3214.rs
index 85eae26..9a727aa 100644
--- a/src/test/ui/issues/issue-3214.rs
+++ b/src/test/ui/issues/issue-3214.rs
@@ -1,6 +1,6 @@
 fn foo<T>() {
     struct Foo {
-        x: T, //~ ERROR can't use type parameters from outer function
+        x: T, //~ ERROR can't use generic parameters from outer function
     }
 
     impl<T> Drop for Foo<T> {
diff --git a/src/test/ui/issues/issue-3214.stderr b/src/test/ui/issues/issue-3214.stderr
index 4ecea4f..e6526ba 100644
--- a/src/test/ui/issues/issue-3214.stderr
+++ b/src/test/ui/issues/issue-3214.stderr
@@ -1,13 +1,13 @@
-error[E0401]: can't use type parameters from outer function
+error[E0401]: can't use generic parameters from outer function
   --> $DIR/issue-3214.rs:3:12
    |
 LL | fn foo<T>() {
    |    --- - type variable from outer function
    |    |
-   |    try adding a local type parameter in this method instead
+   |    try adding a local generic parameter in this method instead
 LL |     struct Foo {
-LL |         x: T, //~ ERROR can't use type parameters from outer function
-   |            ^ use of type variable from outer function
+LL |         x: T, //~ ERROR can't use generic parameters from outer function
+   |            ^ use of generic parameter from outer function
 
 error[E0107]: wrong number of type arguments: expected 0, found 1
   --> $DIR/issue-3214.rs:6:26
diff --git a/src/test/ui/issues/issue-3521-2.rs b/src/test/ui/issues/issue-3521-2.rs
index 39f7fcb..871394f 100644
--- a/src/test/ui/issues/issue-3521-2.rs
+++ b/src/test/ui/issues/issue-3521-2.rs
@@ -2,7 +2,7 @@
     let foo = 100;
 
     static y: isize = foo + 1;
-    //~^ ERROR can't capture dynamic environment
+    //~^ ERROR attempt to use a non-constant value in a constant
 
     println!("{}", y);
 }
diff --git a/src/test/ui/issues/issue-3521-2.stderr b/src/test/ui/issues/issue-3521-2.stderr
index 1464fd7..d54bbbc 100644
--- a/src/test/ui/issues/issue-3521-2.stderr
+++ b/src/test/ui/issues/issue-3521-2.stderr
@@ -1,11 +1,9 @@
-error[E0434]: can't capture dynamic environment in a fn item
+error[E0435]: attempt to use a non-constant value in a constant
   --> $DIR/issue-3521-2.rs:4:23
    |
 LL |     static y: isize = foo + 1;
-   |                       ^^^
-   |
-   = help: use the `|| { ... }` closure form instead
+   |                       ^^^ non-constant value
 
 error: aborting due to previous error
 
-For more information about this error, try `rustc --explain E0434`.
+For more information about this error, try `rustc --explain E0435`.
diff --git a/src/test/ui/issues/issue-3668-2.rs b/src/test/ui/issues/issue-3668-2.rs
index 265a884..525f6f5 100644
--- a/src/test/ui/issues/issue-3668-2.rs
+++ b/src/test/ui/issues/issue-3668-2.rs
@@ -1,6 +1,6 @@
 fn f(x:isize) {
     static child: isize = x + 1;
-    //~^ ERROR can't capture dynamic environment
+    //~^ ERROR attempt to use a non-constant value in a constant
 }
 
 fn main() {}
diff --git a/src/test/ui/issues/issue-3668-2.stderr b/src/test/ui/issues/issue-3668-2.stderr
index 8dd6f49..d6a6e83 100644
--- a/src/test/ui/issues/issue-3668-2.stderr
+++ b/src/test/ui/issues/issue-3668-2.stderr
@@ -1,11 +1,9 @@
-error[E0434]: can't capture dynamic environment in a fn item
+error[E0435]: attempt to use a non-constant value in a constant
   --> $DIR/issue-3668-2.rs:2:27
    |
 LL |     static child: isize = x + 1;
-   |                           ^
-   |
-   = help: use the `|| { ... }` closure form instead
+   |                           ^ non-constant value
 
 error: aborting due to previous error
 
-For more information about this error, try `rustc --explain E0434`.
+For more information about this error, try `rustc --explain E0435`.
diff --git a/src/test/ui/issues/issue-3668.rs b/src/test/ui/issues/issue-3668.rs
index 3f61b1b..0e1f19a 100644
--- a/src/test/ui/issues/issue-3668.rs
+++ b/src/test/ui/issues/issue-3668.rs
@@ -6,7 +6,7 @@
 impl PTrait for P {
    fn getChildOption(&self) -> Option<Box<P>> {
        static childVal: Box<P> = self.child.get();
-       //~^ ERROR can't capture dynamic environment
+       //~^ ERROR attempt to use a non-constant value in a constant
        panic!();
    }
 }
diff --git a/src/test/ui/issues/issue-3668.stderr b/src/test/ui/issues/issue-3668.stderr
index 7f974de..98cd363 100644
--- a/src/test/ui/issues/issue-3668.stderr
+++ b/src/test/ui/issues/issue-3668.stderr
@@ -1,11 +1,9 @@
-error[E0434]: can't capture dynamic environment in a fn item
+error[E0435]: attempt to use a non-constant value in a constant
   --> $DIR/issue-3668.rs:8:34
    |
 LL |        static childVal: Box<P> = self.child.get();
-   |                                  ^^^^
-   |
-   = help: use the `|| { ... }` closure form instead
+   |                                  ^^^^ non-constant value
 
 error: aborting due to previous error
 
-For more information about this error, try `rustc --explain E0434`.
+For more information about this error, try `rustc --explain E0435`.
diff --git a/src/test/ui/issues/issue-52891.stderr b/src/test/ui/issues/issue-52891.stderr
index 55d6110..65b2b94 100644
--- a/src/test/ui/issues/issue-52891.stderr
+++ b/src/test/ui/issues/issue-52891.stderr
@@ -90,7 +90,7 @@
 LL |       m,
    |  ______-
 LL | |     a}; //~ ERROR `a` is defined multiple times
-   | |     -
+   | |     ^
    | |     |
    | |_____`a` reimported here
    |       help: remove unnecessary import
diff --git a/src/test/ui/issues/issue-5997-enum.rs b/src/test/ui/issues/issue-5997-enum.rs
index 0987117..3ff4e03 100644
--- a/src/test/ui/issues/issue-5997-enum.rs
+++ b/src/test/ui/issues/issue-5997-enum.rs
@@ -1,6 +1,6 @@
 fn f<Z>() -> bool {
     enum E { V(Z) }
-    //~^ ERROR can't use type parameters from outer function
+    //~^ ERROR can't use generic parameters from outer function
     true
 }
 
diff --git a/src/test/ui/issues/issue-5997-enum.stderr b/src/test/ui/issues/issue-5997-enum.stderr
index 5c26dc9..5c77814 100644
--- a/src/test/ui/issues/issue-5997-enum.stderr
+++ b/src/test/ui/issues/issue-5997-enum.stderr
@@ -1,12 +1,12 @@
-error[E0401]: can't use type parameters from outer function
+error[E0401]: can't use generic parameters from outer function
   --> $DIR/issue-5997-enum.rs:2:16
    |
 LL | fn f<Z>() -> bool {
    |    - - type variable from outer function
    |    |
-   |    try adding a local type parameter in this method instead
+   |    try adding a local generic parameter in this method instead
 LL |     enum E { V(Z) }
-   |                ^ use of type variable from outer function
+   |                ^ use of generic parameter from outer function
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/issues/issue-5997-struct.rs b/src/test/ui/issues/issue-5997-struct.rs
index 04ac489..6cf510b 100644
--- a/src/test/ui/issues/issue-5997-struct.rs
+++ b/src/test/ui/issues/issue-5997-struct.rs
@@ -1,5 +1,5 @@
 fn f<T>() -> bool {
-    struct S(T); //~ ERROR can't use type parameters from outer function
+    struct S(T); //~ ERROR can't use generic parameters from outer function
 
     true
 }
diff --git a/src/test/ui/issues/issue-5997-struct.stderr b/src/test/ui/issues/issue-5997-struct.stderr
index 1d05d13..a60987b 100644
--- a/src/test/ui/issues/issue-5997-struct.stderr
+++ b/src/test/ui/issues/issue-5997-struct.stderr
@@ -1,12 +1,12 @@
-error[E0401]: can't use type parameters from outer function
+error[E0401]: can't use generic parameters from outer function
   --> $DIR/issue-5997-struct.rs:2:14
    |
 LL | fn f<T>() -> bool {
    |    - - type variable from outer function
    |    |
-   |    try adding a local type parameter in this method instead
-LL |     struct S(T); //~ ERROR can't use type parameters from outer function
-   |              ^ use of type variable from outer function
+   |    try adding a local generic parameter in this method instead
+LL |     struct S(T); //~ ERROR can't use generic parameters from outer function
+   |              ^ use of generic parameter from outer function
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/lifetime-before-type-params.stderr b/src/test/ui/lifetime-before-type-params.stderr
index 7ac8dff..3cef5db 100644
--- a/src/test/ui/lifetime-before-type-params.stderr
+++ b/src/test/ui/lifetime-before-type-params.stderr
@@ -2,41 +2,25 @@
   --> $DIR/lifetime-before-type-params.rs:2:13
    |
 LL | fn first<T, 'a, 'b>() {}
-   |             ^^  ^^
-help: move the lifetime parameter prior to the first type parameter
-   |
-LL | fn first<'a, 'b, T>() {}
-   |          ^^^ ^^^ --
+   |         ----^^--^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, 'b, T>`
 
 error: lifetime parameters must be declared prior to type parameters
   --> $DIR/lifetime-before-type-params.rs:4:18
    |
 LL | fn second<'a, T, 'b>() {}
-   |                  ^^
-help: move the lifetime parameter prior to the first type parameter
-   |
-LL | fn second<'a, 'b, T>() {}
-   |               ^^^ --
+   |          --------^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, 'b, T>`
 
 error: lifetime parameters must be declared prior to type parameters
   --> $DIR/lifetime-before-type-params.rs:6:16
    |
 LL | fn third<T, U, 'a>() {}
-   |                ^^
-help: move the lifetime parameter prior to the first type parameter
-   |
-LL | fn third<'a, T, U>() {}
-   |          ^^^    --
+   |         -------^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, T, U>`
 
 error: lifetime parameters must be declared prior to type parameters
   --> $DIR/lifetime-before-type-params.rs:8:18
    |
 LL | fn fourth<'a, T, 'b, U, 'c, V>() {}
-   |                  ^^     ^^
-help: move the lifetime parameter prior to the first type parameter
-   |
-LL | fn fourth<'a, 'b, 'c, T, U, V>() {}
-   |               ^^^ ^^^ -- --
+   |          --------^^-----^^---- help: reorder the parameters: lifetimes, then types, then consts: `<'a, 'b, 'c, T, U, V>`
 
 error[E0601]: `main` function not found in crate `lifetime_before_type_params`
    |
diff --git a/src/test/ui/lint/lint-directives-on-use-items-issue-10534.stderr b/src/test/ui/lint/lint-directives-on-use-items-issue-10534.stderr
index 170b98a..e588d24 100644
--- a/src/test/ui/lint/lint-directives-on-use-items-issue-10534.stderr
+++ b/src/test/ui/lint/lint-directives-on-use-items-issue-10534.stderr
@@ -2,7 +2,7 @@
   --> $DIR/lint-directives-on-use-items-issue-10534.rs:12:9
    |
 LL |     use a::x; //~ ERROR: unused import
-   |         ^^^^
+   |     ----^^^^- help: remove the whole `use` item
    |
 note: lint level defined here
   --> $DIR/lint-directives-on-use-items-issue-10534.rs:1:9
@@ -14,7 +14,7 @@
   --> $DIR/lint-directives-on-use-items-issue-10534.rs:21:9
    |
 LL |     use a::y; //~ ERROR: unused import
-   |         ^^^^
+   |     ----^^^^- help: remove the whole `use` item
    |
 note: lint level defined here
   --> $DIR/lint-directives-on-use-items-issue-10534.rs:20:12
diff --git a/src/test/ui/lint/lint-unused-imports.rs b/src/test/ui/lint/lint-unused-imports.rs
index 4892524..9c5b206 100644
--- a/src/test/ui/lint/lint-unused-imports.rs
+++ b/src/test/ui/lint/lint-unused-imports.rs
@@ -6,7 +6,7 @@
 use std::mem::*;            // shouldn't get errors for not using
                             // everything imported
 use std::fmt::{};
-//~^ ERROR unused import: `use std::fmt::{};`
+//~^ ERROR unused import: `std::fmt::{}`
 
 // Should get errors for both 'Some' and 'None'
 use std::option::Option::{Some, None};
diff --git a/src/test/ui/lint/lint-unused-imports.stderr b/src/test/ui/lint/lint-unused-imports.stderr
index 214f4a4..7970b02 100644
--- a/src/test/ui/lint/lint-unused-imports.stderr
+++ b/src/test/ui/lint/lint-unused-imports.stderr
@@ -1,8 +1,8 @@
-error: unused import: `use std::fmt::{};`
-  --> $DIR/lint-unused-imports.rs:8:1
+error: unused import: `std::fmt::{}`
+  --> $DIR/lint-unused-imports.rs:8:5
    |
 LL | use std::fmt::{};
-   | ^^^^^^^^^^^^^^^^^
+   | ----^^^^^^^^^^^^- help: remove the whole `use` item
    |
 note: lint level defined here
   --> $DIR/lint-unused-imports.rs:1:9
@@ -14,37 +14,39 @@
   --> $DIR/lint-unused-imports.rs:12:27
    |
 LL | use std::option::Option::{Some, None};
-   |                           ^^^^  ^^^^
+   | --------------------------^^^^--^^^^-- help: remove the whole `use` item
 
 error: unused import: `test::A`
   --> $DIR/lint-unused-imports.rs:15:5
    |
 LL | use test::A;       //~ ERROR unused import: `test::A`
-   |     ^^^^^^^
+   | ----^^^^^^^- help: remove the whole `use` item
 
 error: unused import: `bar`
   --> $DIR/lint-unused-imports.rs:24:18
    |
 LL | use test2::{foo, bar}; //~ ERROR unused import: `bar`
-   |                  ^^^
+   |                --^^^
+   |                |
+   |                help: remove the unused import
 
 error: unused import: `foo::Square`
   --> $DIR/lint-unused-imports.rs:52:13
    |
 LL |         use foo::Square; //~ ERROR unused import: `foo::Square`
-   |             ^^^^^^^^^^^
+   |         ----^^^^^^^^^^^- help: remove the whole `use` item
 
 error: unused import: `self::g`
   --> $DIR/lint-unused-imports.rs:68:9
    |
 LL |     use self::g; //~ ERROR unused import: `self::g`
-   |         ^^^^^^^
+   |     ----^^^^^^^- help: remove the whole `use` item
 
 error: unused import: `test2::foo`
   --> $DIR/lint-unused-imports.rs:77:9
    |
 LL |     use test2::foo; //~ ERROR unused import: `test2::foo`
-   |         ^^^^^^^^^^
+   |     ----^^^^^^^^^^- help: remove the whole `use` item
 
 error: unused import: `test::B2`
   --> $DIR/lint-unused-imports.rs:20:5
diff --git a/src/test/ui/lint/lints-in-foreign-macros.stderr b/src/test/ui/lint/lints-in-foreign-macros.stderr
index 8287ca5..b808ca7 100644
--- a/src/test/ui/lint/lints-in-foreign-macros.stderr
+++ b/src/test/ui/lint/lints-in-foreign-macros.stderr
@@ -2,7 +2,7 @@
   --> $DIR/lints-in-foreign-macros.rs:11:16
    |
 LL |     () => {use std::string::ToString;} //~ WARN: unused import
-   |                ^^^^^^^^^^^^^^^^^^^^^
+   |            ----^^^^^^^^^^^^^^^^^^^^^- help: remove the whole `use` item
 ...
 LL | mod a { foo!(); }
    |         ------- in this macro invocation
@@ -17,13 +17,13 @@
   --> $DIR/lints-in-foreign-macros.rs:16:18
    |
 LL | mod c { baz!(use std::string::ToString;); } //~ WARN: unused import
-   |                  ^^^^^^^^^^^^^^^^^^^^^
+   |              ----^^^^^^^^^^^^^^^^^^^^^- help: remove the whole `use` item
 
 warning: unused import: `std::string::ToString`
   --> $DIR/lints-in-foreign-macros.rs:17:19
    |
 LL | mod d { baz2!(use std::string::ToString;); } //~ WARN: unused import
-   |                   ^^^^^^^^^^^^^^^^^^^^^
+   |               ----^^^^^^^^^^^^^^^^^^^^^- help: remove the whole `use` item
 
 warning: missing documentation for crate
   --> $DIR/lints-in-foreign-macros.rs:4:1
diff --git a/src/test/ui/macros/macro-follow.rs b/src/test/ui/macros/macro-follow.rs
index f4a1931..10b44e0 100644
--- a/src/test/ui/macros/macro-follow.rs
+++ b/src/test/ui/macros/macro-follow.rs
@@ -12,11 +12,11 @@
     ($p:pat >) => {};        //~ERROR `$p:pat` is followed by `>`
     ($p:pat +) => {};        //~ERROR `$p:pat` is followed by `+`
     ($p:pat ident) => {};    //~ERROR `$p:pat` is followed by `ident`
-    ($p:pat $p:pat) => {};   //~ERROR `$p:pat` is followed by `$p:pat`
+    ($p:pat $q:pat) => {};   //~ERROR `$p:pat` is followed by `$q:pat`
     ($p:pat $e:expr) => {};  //~ERROR `$p:pat` is followed by `$e:expr`
     ($p:pat $t:ty) => {};    //~ERROR `$p:pat` is followed by `$t:ty`
     ($p:pat $s:stmt) => {};  //~ERROR `$p:pat` is followed by `$s:stmt`
-    ($p:pat $p:path) => {};  //~ERROR `$p:pat` is followed by `$p:path`
+    ($p:pat $q:path) => {};  //~ERROR `$p:pat` is followed by `$q:path`
     ($p:pat $b:block) => {}; //~ERROR `$p:pat` is followed by `$b:block`
     ($p:pat $i:ident) => {}; //~ERROR `$p:pat` is followed by `$i:ident`
     ($p:pat $t:tt) => {};    //~ERROR `$p:pat` is followed by `$t:tt`
@@ -37,7 +37,7 @@
     ($e:expr if) => {};       //~ERROR `$e:expr` is followed by `if`
     ($e:expr in) => {};       //~ERROR `$e:expr` is followed by `in`
     ($e:expr $p:pat) => {};   //~ERROR `$e:expr` is followed by `$p:pat`
-    ($e:expr $e:expr) => {};  //~ERROR `$e:expr` is followed by `$e:expr`
+    ($e:expr $f:expr) => {};  //~ERROR `$e:expr` is followed by `$f:expr`
     ($e:expr $t:ty) => {};    //~ERROR `$e:expr` is followed by `$t:ty`
     ($e:expr $s:stmt) => {};  //~ERROR `$e:expr` is followed by `$s:stmt`
     ($e:expr $p:path) => {};  //~ERROR `$e:expr` is followed by `$p:path`
@@ -57,12 +57,12 @@
     ($t:ty if) => {};       //~ERROR `$t:ty` is followed by `if`
     ($t:ty $p:pat) => {};   //~ERROR `$t:ty` is followed by `$p:pat`
     ($t:ty $e:expr) => {};  //~ERROR `$t:ty` is followed by `$e:expr`
-    ($t:ty $t:ty) => {};    //~ERROR `$t:ty` is followed by `$t:ty`
+    ($t:ty $r:ty) => {};    //~ERROR `$t:ty` is followed by `$r:ty`
     ($t:ty $s:stmt) => {};  //~ERROR `$t:ty` is followed by `$s:stmt`
     ($t:ty $p:path) => {};  //~ERROR `$t:ty` is followed by `$p:path`
     ($t:ty $b:block) => {}; // ok (RFC 1494)
     ($t:ty $i:ident) => {}; //~ERROR `$t:ty` is followed by `$i:ident`
-    ($t:ty $t:tt) => {};    //~ERROR `$t:ty` is followed by `$t:tt`
+    ($t:ty $r:tt) => {};    //~ERROR `$t:ty` is followed by `$r:tt`
     ($t:ty $i:item) => {};  //~ERROR `$t:ty` is followed by `$i:item`
     ($t:ty $m:meta) => {};  //~ERROR `$t:ty` is followed by `$m:meta`
 }
@@ -82,7 +82,7 @@
     ($s:stmt $p:pat) => {};   //~ERROR `$s:stmt` is followed by `$p:pat`
     ($s:stmt $e:expr) => {};  //~ERROR `$s:stmt` is followed by `$e:expr`
     ($s:stmt $t:ty) => {};    //~ERROR `$s:stmt` is followed by `$t:ty`
-    ($s:stmt $s:stmt) => {};  //~ERROR `$s:stmt` is followed by `$s:stmt`
+    ($s:stmt $t:stmt) => {};  //~ERROR `$s:stmt` is followed by `$t:stmt`
     ($s:stmt $p:path) => {};  //~ERROR `$s:stmt` is followed by `$p:path`
     ($s:stmt $b:block) => {}; //~ERROR `$s:stmt` is followed by `$b:block`
     ($s:stmt $i:ident) => {}; //~ERROR `$s:stmt` is followed by `$i:ident`
@@ -97,11 +97,11 @@
     ($p:path +) => {};        //~ERROR `$p:path` is followed by `+`
     ($p:path ident) => {};    //~ERROR `$p:path` is followed by `ident`
     ($p:path if) => {};       //~ERROR `$p:path` is followed by `if`
-    ($p:path $p:pat) => {};   //~ERROR `$p:path` is followed by `$p:pat`
+    ($p:path $q:pat) => {};   //~ERROR `$p:path` is followed by `$q:pat`
     ($p:path $e:expr) => {};  //~ERROR `$p:path` is followed by `$e:expr`
     ($p:path $t:ty) => {};    //~ERROR `$p:path` is followed by `$t:ty`
     ($p:path $s:stmt) => {};  //~ERROR `$p:path` is followed by `$s:stmt`
-    ($p:path $p:path) => {};  //~ERROR `$p:path` is followed by `$p:path`
+    ($p:path $q:path) => {};  //~ERROR `$p:path` is followed by `$q:path`
     ($p:path $b:block) => {}; // ok (RFC 1494)
     ($p:path $i:ident) => {}; //~ERROR `$p:path` is followed by `$i:ident`
     ($p:path $t:tt) => {};    //~ERROR `$p:path` is followed by `$t:tt`
diff --git a/src/test/ui/macros/macro-follow.stderr b/src/test/ui/macros/macro-follow.stderr
index 4aea5cc..e3302ea 100644
--- a/src/test/ui/macros/macro-follow.stderr
+++ b/src/test/ui/macros/macro-follow.stderr
@@ -54,10 +54,10 @@
    |
    = note: allowed there are: `=>`, `,`, `=`, `|`, `if` or `in`
 
-error: `$p:pat` is followed by `$p:pat`, which is not allowed for `pat` fragments
+error: `$p:pat` is followed by `$q:pat`, which is not allowed for `pat` fragments
   --> $DIR/macro-follow.rs:15:13
    |
-LL |     ($p:pat $p:pat) => {};   //~ERROR `$p:pat` is followed by `$p:pat`
+LL |     ($p:pat $q:pat) => {};   //~ERROR `$p:pat` is followed by `$q:pat`
    |             ^^^^^^ not allowed after `pat` fragments
    |
    = note: allowed there are: `=>`, `,`, `=`, `|`, `if` or `in`
@@ -86,10 +86,10 @@
    |
    = note: allowed there are: `=>`, `,`, `=`, `|`, `if` or `in`
 
-error: `$p:pat` is followed by `$p:path`, which is not allowed for `pat` fragments
+error: `$p:pat` is followed by `$q:path`, which is not allowed for `pat` fragments
   --> $DIR/macro-follow.rs:19:13
    |
-LL |     ($p:pat $p:path) => {};  //~ERROR `$p:pat` is followed by `$p:path`
+LL |     ($p:pat $q:path) => {};  //~ERROR `$p:pat` is followed by `$q:path`
    |             ^^^^^^^ not allowed after `pat` fragments
    |
    = note: allowed there are: `=>`, `,`, `=`, `|`, `if` or `in`
@@ -230,10 +230,10 @@
    |
    = note: allowed there are: `=>`, `,` or `;`
 
-error: `$e:expr` is followed by `$e:expr`, which is not allowed for `expr` fragments
+error: `$e:expr` is followed by `$f:expr`, which is not allowed for `expr` fragments
   --> $DIR/macro-follow.rs:40:14
    |
-LL |     ($e:expr $e:expr) => {};  //~ERROR `$e:expr` is followed by `$e:expr`
+LL |     ($e:expr $f:expr) => {};  //~ERROR `$e:expr` is followed by `$f:expr`
    |              ^^^^^^^ not allowed after `expr` fragments
    |
    = note: allowed there are: `=>`, `,` or `;`
@@ -350,10 +350,10 @@
    |
    = note: allowed there are: `{`, `[`, `=>`, `,`, `>`, `=`, `:`, `;`, `|`, `as` or `where`
 
-error: `$t:ty` is followed by `$t:ty`, which is not allowed for `ty` fragments
+error: `$t:ty` is followed by `$r:ty`, which is not allowed for `ty` fragments
   --> $DIR/macro-follow.rs:60:12
    |
-LL |     ($t:ty $t:ty) => {};    //~ERROR `$t:ty` is followed by `$t:ty`
+LL |     ($t:ty $r:ty) => {};    //~ERROR `$t:ty` is followed by `$r:ty`
    |            ^^^^^ not allowed after `ty` fragments
    |
    = note: allowed there are: `{`, `[`, `=>`, `,`, `>`, `=`, `:`, `;`, `|`, `as` or `where`
@@ -382,10 +382,10 @@
    |
    = note: allowed there are: `{`, `[`, `=>`, `,`, `>`, `=`, `:`, `;`, `|`, `as` or `where`
 
-error: `$t:ty` is followed by `$t:tt`, which is not allowed for `ty` fragments
+error: `$t:ty` is followed by `$r:tt`, which is not allowed for `ty` fragments
   --> $DIR/macro-follow.rs:65:12
    |
-LL |     ($t:ty $t:tt) => {};    //~ERROR `$t:ty` is followed by `$t:tt`
+LL |     ($t:ty $r:tt) => {};    //~ERROR `$t:ty` is followed by `$r:tt`
    |            ^^^^^ not allowed after `ty` fragments
    |
    = note: allowed there are: `{`, `[`, `=>`, `,`, `>`, `=`, `:`, `;`, `|`, `as` or `where`
@@ -518,10 +518,10 @@
    |
    = note: allowed there are: `=>`, `,` or `;`
 
-error: `$s:stmt` is followed by `$s:stmt`, which is not allowed for `stmt` fragments
+error: `$s:stmt` is followed by `$t:stmt`, which is not allowed for `stmt` fragments
   --> $DIR/macro-follow.rs:85:14
    |
-LL |     ($s:stmt $s:stmt) => {};  //~ERROR `$s:stmt` is followed by `$s:stmt`
+LL |     ($s:stmt $t:stmt) => {};  //~ERROR `$s:stmt` is followed by `$t:stmt`
    |              ^^^^^^^ not allowed after `stmt` fragments
    |
    = note: allowed there are: `=>`, `,` or `;`
@@ -606,10 +606,10 @@
    |
    = note: allowed there are: `{`, `[`, `=>`, `,`, `>`, `=`, `:`, `;`, `|`, `as` or `where`
 
-error: `$p:path` is followed by `$p:pat`, which is not allowed for `path` fragments
+error: `$p:path` is followed by `$q:pat`, which is not allowed for `path` fragments
   --> $DIR/macro-follow.rs:100:14
    |
-LL |     ($p:path $p:pat) => {};   //~ERROR `$p:path` is followed by `$p:pat`
+LL |     ($p:path $q:pat) => {};   //~ERROR `$p:path` is followed by `$q:pat`
    |              ^^^^^^ not allowed after `path` fragments
    |
    = note: allowed there are: `{`, `[`, `=>`, `,`, `>`, `=`, `:`, `;`, `|`, `as` or `where`
@@ -638,10 +638,10 @@
    |
    = note: allowed there are: `{`, `[`, `=>`, `,`, `>`, `=`, `:`, `;`, `|`, `as` or `where`
 
-error: `$p:path` is followed by `$p:path`, which is not allowed for `path` fragments
+error: `$p:path` is followed by `$q:path`, which is not allowed for `path` fragments
   --> $DIR/macro-follow.rs:104:14
    |
-LL |     ($p:path $p:path) => {};  //~ERROR `$p:path` is followed by `$p:path`
+LL |     ($p:path $q:path) => {};  //~ERROR `$p:path` is followed by `$q:path`
    |              ^^^^^^^ not allowed after `path` fragments
    |
    = note: allowed there are: `{`, `[`, `=>`, `,`, `>`, `=`, `:`, `;`, `|`, `as` or `where`
diff --git a/src/test/ui/macros/macro-multiple-matcher-bindings.rs b/src/test/ui/macros/macro-multiple-matcher-bindings.rs
new file mode 100644
index 0000000..9e0fa38
--- /dev/null
+++ b/src/test/ui/macros/macro-multiple-matcher-bindings.rs
@@ -0,0 +1,25 @@
+// Test that duplicate matcher binding names are caught at declaration time, rather than at macro
+// invocation time.
+//
+// FIXME(mark-i-m): Update this when it becomes a hard error.
+
+// compile-pass
+
+#![allow(unused_macros)]
+
+macro_rules! foo1 {
+    ($a:ident, $a:ident) => {}; //~WARNING duplicate matcher binding
+    ($a:ident, $a:path) => {};  //~WARNING duplicate matcher binding
+}
+
+macro_rules! foo2 {
+    ($a:ident) => {}; // OK
+    ($a:path) => {};  // OK
+}
+
+macro_rules! foo3 {
+    ($a:ident, $($a:ident),*) => {}; //~WARNING duplicate matcher binding
+    ($($a:ident)+ # $($($a:path),+);*) => {}; //~WARNING duplicate matcher binding
+}
+
+fn main() {}
diff --git a/src/test/ui/macros/macro-multiple-matcher-bindings.stderr b/src/test/ui/macros/macro-multiple-matcher-bindings.stderr
new file mode 100644
index 0000000..bc78b471
--- /dev/null
+++ b/src/test/ui/macros/macro-multiple-matcher-bindings.stderr
@@ -0,0 +1,37 @@
+warning: duplicate matcher binding
+  --> $DIR/macro-multiple-matcher-bindings.rs:11:6
+   |
+LL |     ($a:ident, $a:ident) => {}; //~WARNING duplicate matcher binding
+   |      ^^^^^^^^  ^^^^^^^^
+   |
+   = note: #[warn(duplicate_matcher_binding_name)] on by default
+   = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
+   = note: for more information, see issue #57593 <https://github.com/rust-lang/rust/issues/57593>
+
+warning: duplicate matcher binding
+  --> $DIR/macro-multiple-matcher-bindings.rs:12:6
+   |
+LL |     ($a:ident, $a:path) => {};  //~WARNING duplicate matcher binding
+   |      ^^^^^^^^  ^^^^^^^
+   |
+   = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
+   = note: for more information, see issue #57593 <https://github.com/rust-lang/rust/issues/57593>
+
+warning: duplicate matcher binding
+  --> $DIR/macro-multiple-matcher-bindings.rs:21:6
+   |
+LL |     ($a:ident, $($a:ident),*) => {}; //~WARNING duplicate matcher binding
+   |      ^^^^^^^^    ^^^^^^^^
+   |
+   = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
+   = note: for more information, see issue #57593 <https://github.com/rust-lang/rust/issues/57593>
+
+warning: duplicate matcher binding
+  --> $DIR/macro-multiple-matcher-bindings.rs:22:8
+   |
+LL |     ($($a:ident)+ # $($($a:path),+);*) => {}; //~WARNING duplicate matcher binding
+   |        ^^^^^^^^         ^^^^^^^
+   |
+   = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
+   = note: for more information, see issue #57593 <https://github.com/rust-lang/rust/issues/57593>
+
diff --git a/src/test/ui/methods/method-deref-to-same-trait-object-with-separate-params.rs b/src/test/ui/methods/method-deref-to-same-trait-object-with-separate-params.rs
new file mode 100644
index 0000000..a5dae1c
--- /dev/null
+++ b/src/test/ui/methods/method-deref-to-same-trait-object-with-separate-params.rs
@@ -0,0 +1,177 @@
+#![feature(arbitrary_self_types, coerce_unsized, dispatch_from_dyn, unsize, unsized_locals)]
+
+// This tests a few edge-cases around `arbitrary_self_types`. Most specifically,
+// it checks that the `ObjectCandidate` you get from method matching can't
+// match a trait with the same DefId as a supertrait but a bad type parameter.
+
+use std::marker::PhantomData;
+
+mod internal {
+    use std::ops::{CoerceUnsized, Deref, DispatchFromDyn};
+    use std::marker::{PhantomData, Unsize};
+
+    pub struct Smaht<T: ?Sized, MISC>(pub Box<T>, pub PhantomData<MISC>);
+
+    impl<T: ?Sized, MISC> Deref for Smaht<T, MISC> {
+        type Target = T;
+
+        fn deref(&self) -> &Self::Target {
+            &self.0
+        }
+    }
+    impl<T: ?Sized + Unsize<U>, U: ?Sized, MISC> CoerceUnsized<Smaht<U, MISC>>
+        for Smaht<T, MISC>
+    {}
+    impl<T: ?Sized + Unsize<U>, U: ?Sized, MISC> DispatchFromDyn<Smaht<U, MISC>>
+        for Smaht<T, MISC>
+    {}
+
+    pub trait Foo: X<u32> {}
+    pub trait X<T> {
+        fn foo(self: Smaht<Self, T>) -> T;
+    }
+
+    impl X<u32> for () {
+        fn foo(self: Smaht<Self, u32>) -> u32 {
+            0
+        }
+    }
+
+    pub trait Marker {}
+    impl Marker for dyn Foo {}
+    impl<T: Marker + ?Sized> X<u64> for T {
+        fn foo(self: Smaht<Self, u64>) -> u64 {
+            1
+        }
+    }
+
+    impl Deref for dyn Foo {
+        type Target = ();
+        fn deref(&self) -> &() { &() }
+    }
+
+    impl Foo for () {}
+}
+
+pub trait FinalFoo {
+    fn foo(&self) -> u8;
+}
+
+impl FinalFoo for () {
+    fn foo(&self) -> u8 { 0 }
+}
+
+mod nuisance_foo {
+    pub trait NuisanceFoo {
+        fn foo(self);
+    }
+
+    impl<T: ?Sized> NuisanceFoo for T {
+        fn foo(self) {}
+    }
+}
+
+
+fn objectcandidate_impl() {
+    let x: internal::Smaht<(), u32> = internal::Smaht(Box::new(()), PhantomData);
+    let x: internal::Smaht<dyn internal::Foo, u32> = x;
+
+    // This picks `<dyn internal::Foo as X<u32>>::foo` via `ObjectCandidate`.
+    //
+    // The `TraitCandidate` is not relevant because `X` is not in scope.
+    let z = x.foo();
+
+    // Observe the type of `z` is `u32`
+    let _seetype: () = z; //~ ERROR mismatched types
+    //~| expected (), found u32
+}
+
+fn traitcandidate_impl() {
+    use internal::X;
+
+    let x: internal::Smaht<(), u64> = internal::Smaht(Box::new(()), PhantomData);
+    let x: internal::Smaht<dyn internal::Foo, u64> = x;
+
+    // This picks `<dyn internal::Foo as X<u64>>::foo` via `TraitCandidate`.
+    //
+    // The `ObjectCandidate` does not apply, as it only applies to
+    // `X<u32>` (and not `X<u64>`).
+    let z = x.foo();
+
+    // Observe the type of `z` is `u64`
+    let _seetype: () = z; //~ ERROR mismatched types
+    //~| expected (), found u64
+}
+
+fn traitcandidate_impl_with_nuisance() {
+    use internal::X;
+    use nuisance_foo::NuisanceFoo;
+
+    let x: internal::Smaht<(), u64> = internal::Smaht(Box::new(()), PhantomData);
+    let x: internal::Smaht<dyn internal::Foo, u64> = x;
+
+    // This picks `<dyn internal::Foo as X<u64>>::foo` via `TraitCandidate`.
+    //
+    // The `ObjectCandidate` does not apply, as it only applies to
+    // `X<u32>` (and not `X<u64>`).
+    //
+    // The NuisanceFoo impl has the same priority as the `X` impl,
+    // so we get a conflict.
+    let z = x.foo(); //~ ERROR multiple applicable items in scope
+}
+
+
+fn neither_impl() {
+    let x: internal::Smaht<(), u64> = internal::Smaht(Box::new(()), PhantomData);
+    let x: internal::Smaht<dyn internal::Foo, u64> = x;
+
+    // This can't pick the `TraitCandidate` impl, because `Foo` is not
+    // imported. However, this also can't pick the `ObjectCandidate`
+    // impl, because it only applies to `X<u32>` (and not `X<u64>`).
+    //
+    // Therefore, neither of the candidates is applicable, and we pick
+    // the `FinalFoo` impl after another deref, which will return `u8`.
+    let z = x.foo();
+
+    // Observe the type of `z` is `u8`
+    let _seetype: () = z; //~ ERROR mismatched types
+    //~| expected (), found u8
+}
+
+fn both_impls() {
+    use internal::X;
+
+    let x: internal::Smaht<(), u32> = internal::Smaht(Box::new(()), PhantomData);
+    let x: internal::Smaht<dyn internal::Foo, u32> = x;
+
+    // This can pick both the `TraitCandidate` and the `ObjectCandidate` impl.
+    //
+    // However, the `ObjectCandidate` is considered an "inherent candidate",
+    // and therefore has priority over both the `TraitCandidate` as well as
+    // any other "nuisance" candidate" (if present).
+    let z = x.foo();
+
+    // Observe the type of `z` is `u32`
+    let _seetype: () = z; //~ ERROR mismatched types
+    //~| expected (), found u32
+}
+
+
+fn both_impls_with_nuisance() {
+    // Similar to the `both_impls` example, except with a nuisance impl to
+    // make sure the `ObjectCandidate` indeed has a higher priority.
+
+    use internal::X;
+    use nuisance_foo::NuisanceFoo;
+
+    let x: internal::Smaht<(), u32> = internal::Smaht(Box::new(()), PhantomData);
+    let x: internal::Smaht<dyn internal::Foo, u32> = x;
+    let z = x.foo();
+
+    // Observe the type of `z` is `u32`
+    let _seetype: () = z; //~ ERROR mismatched types
+    //~| expected (), found u32
+}
+
+fn main() {
+}
diff --git a/src/test/ui/methods/method-deref-to-same-trait-object-with-separate-params.stderr b/src/test/ui/methods/method-deref-to-same-trait-object-with-separate-params.stderr
new file mode 100644
index 0000000..2d8449b
--- /dev/null
+++ b/src/test/ui/methods/method-deref-to-same-trait-object-with-separate-params.stderr
@@ -0,0 +1,72 @@
+error[E0308]: mismatched types
+  --> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:85:24
+   |
+LL |     let _seetype: () = z; //~ ERROR mismatched types
+   |                        ^ expected (), found u32
+   |
+   = note: expected type `()`
+              found type `u32`
+
+error[E0308]: mismatched types
+  --> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:102:24
+   |
+LL |     let _seetype: () = z; //~ ERROR mismatched types
+   |                        ^ expected (), found u64
+   |
+   = note: expected type `()`
+              found type `u64`
+
+error[E0034]: multiple applicable items in scope
+  --> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:120:15
+   |
+LL |     let z = x.foo(); //~ ERROR multiple applicable items in scope
+   |               ^^^ multiple `foo` found
+   |
+note: candidate #1 is defined in an impl of the trait `internal::X` for the type `_`
+  --> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:43:9
+   |
+LL |         fn foo(self: Smaht<Self, u64>) -> u64 {
+   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+note: candidate #2 is defined in an impl of the trait `nuisance_foo::NuisanceFoo` for the type `_`
+  --> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:70:9
+   |
+LL |         fn foo(self) {}
+   |         ^^^^^^^^^^^^
+note: candidate #3 is defined in the trait `FinalFoo`
+  --> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:57:5
+   |
+LL |     fn foo(&self) -> u8;
+   |     ^^^^^^^^^^^^^^^^^^^^
+   = help: to disambiguate the method call, write `FinalFoo::foo(x)` instead
+
+error[E0308]: mismatched types
+  --> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:137:24
+   |
+LL |     let _seetype: () = z; //~ ERROR mismatched types
+   |                        ^ expected (), found u8
+   |
+   = note: expected type `()`
+              found type `u8`
+
+error[E0308]: mismatched types
+  --> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:155:24
+   |
+LL |     let _seetype: () = z; //~ ERROR mismatched types
+   |                        ^ expected (), found u32
+   |
+   = note: expected type `()`
+              found type `u32`
+
+error[E0308]: mismatched types
+  --> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:172:24
+   |
+LL |     let _seetype: () = z; //~ ERROR mismatched types
+   |                        ^ expected (), found u32
+   |
+   = note: expected type `()`
+              found type `u32`
+
+error: aborting due to 6 previous errors
+
+Some errors occurred: E0034, E0308.
+For more information about an error, try `rustc --explain E0034`.
diff --git a/src/test/ui/methods/method-trait-object-with-hrtb.rs b/src/test/ui/methods/method-trait-object-with-hrtb.rs
new file mode 100644
index 0000000..da2f13f
--- /dev/null
+++ b/src/test/ui/methods/method-trait-object-with-hrtb.rs
@@ -0,0 +1,41 @@
+// compile-pass
+
+// Check that method probing ObjectCandidate works in the presence of
+// auto traits and/or HRTBs.
+
+mod internal {
+    pub trait MyObject<'a> {
+        type Output;
+
+        fn foo(&self) -> Self::Output;
+    }
+
+    impl<'a> MyObject<'a> for () {
+        type Output = &'a u32;
+
+        fn foo(&self) -> Self::Output { &4 }
+    }
+}
+
+fn t1(d: &dyn for<'a> internal::MyObject<'a, Output=&'a u32>) {
+    d.foo();
+}
+
+fn t2(d: &dyn internal::MyObject<'static, Output=&'static u32>) {
+    d.foo();
+}
+
+fn t3(d: &(dyn for<'a> internal::MyObject<'a, Output=&'a u32> + Sync)) {
+    d.foo();
+}
+
+fn t4(d: &(dyn internal::MyObject<'static, Output=&'static u32> + Sync)) {
+    d.foo();
+}
+
+fn main() {
+    t1(&());
+    t2(&());
+    t3(&());
+    t4(&());
+}
diff --git a/src/test/ui/nested-ty-params.rs b/src/test/ui/nested-ty-params.rs
index 102f8d0..85413ac 100644
--- a/src/test/ui/nested-ty-params.rs
+++ b/src/test/ui/nested-ty-params.rs
@@ -1,4 +1,4 @@
-// error-pattern:can't use type parameters from outer function
+// error-pattern:can't use generic parameters from outer function
 fn hd<U>(v: Vec<U> ) -> U {
     fn hd1(w: [U]) -> U { return w[0]; }
 
diff --git a/src/test/ui/nested-ty-params.stderr b/src/test/ui/nested-ty-params.stderr
index 617eddf..37adeff 100644
--- a/src/test/ui/nested-ty-params.stderr
+++ b/src/test/ui/nested-ty-params.stderr
@@ -1,22 +1,22 @@
-error[E0401]: can't use type parameters from outer function
+error[E0401]: can't use generic parameters from outer function
   --> $DIR/nested-ty-params.rs:3:16
    |
 LL | fn hd<U>(v: Vec<U> ) -> U {
    |       - type variable from outer function
 LL |     fn hd1(w: [U]) -> U { return w[0]; }
-   |        ---     ^ use of type variable from outer function
+   |        ---     ^ use of generic parameter from outer function
    |        |
-   |        help: try using a local type parameter instead: `hd1<U>`
+   |        help: try using a local generic parameter instead: `hd1<U>`
 
-error[E0401]: can't use type parameters from outer function
+error[E0401]: can't use generic parameters from outer function
   --> $DIR/nested-ty-params.rs:3:23
    |
 LL | fn hd<U>(v: Vec<U> ) -> U {
    |       - type variable from outer function
 LL |     fn hd1(w: [U]) -> U { return w[0]; }
-   |        ---            ^ use of type variable from outer function
+   |        ---            ^ use of generic parameter from outer function
    |        |
-   |        help: try using a local type parameter instead: `hd1<U>`
+   |        help: try using a local generic parameter instead: `hd1<U>`
 
 error: aborting due to 2 previous errors
 
diff --git a/src/test/ui/nll/issue-57960.rs b/src/test/ui/nll/issue-57960.rs
new file mode 100644
index 0000000..0b52e46
--- /dev/null
+++ b/src/test/ui/nll/issue-57960.rs
@@ -0,0 +1,39 @@
+// run-pass
+
+#![allow(dead_code)]
+
+trait Range {
+    const FIRST: u8;
+    const LAST: u8;
+}
+
+struct OneDigit;
+impl Range for OneDigit {
+    const FIRST: u8 = 0;
+    const LAST: u8 = 9;
+}
+
+struct TwoDigits;
+impl Range for TwoDigits {
+    const FIRST: u8 = 10;
+    const LAST: u8 = 99;
+}
+
+struct ThreeDigits;
+impl Range for ThreeDigits {
+    const FIRST: u8 = 100;
+    const LAST: u8 = 255;
+}
+
+fn digits(x: u8) -> u32 {
+    match x {
+        OneDigit::FIRST...OneDigit::LAST => 1,
+        TwoDigits::FIRST...TwoDigits::LAST => 2,
+        ThreeDigits::FIRST...ThreeDigits::LAST => 3,
+        _ => unreachable!(),
+    }
+}
+
+fn main() {
+    assert_eq!(digits(100), 3);
+}
diff --git a/src/test/ui/nll/issue-58053.rs b/src/test/ui/nll/issue-58053.rs
new file mode 100644
index 0000000..d433890
--- /dev/null
+++ b/src/test/ui/nll/issue-58053.rs
@@ -0,0 +1,14 @@
+#![allow(warnings)]
+#![feature(nll)]
+
+fn main() {
+    let i = &3;
+
+    let f = |x: &i32| -> &i32 { x };
+    //~^ ERROR lifetime may not live long enough
+    let j = f(i);
+
+    let g = |x: &i32| { x };
+    //~^ ERROR lifetime may not live long enough
+    let k = g(i);
+}
diff --git a/src/test/ui/nll/issue-58053.stderr b/src/test/ui/nll/issue-58053.stderr
new file mode 100644
index 0000000..9048983
--- /dev/null
+++ b/src/test/ui/nll/issue-58053.stderr
@@ -0,0 +1,20 @@
+error: lifetime may not live long enough
+  --> $DIR/issue-58053.rs:7:33
+   |
+LL |     let f = |x: &i32| -> &i32 { x };
+   |                 -        ----   ^ returning this value requires that `'1` must outlive `'2`
+   |                 |        |
+   |                 |        return type of closure is &'2 i32
+   |                 let's call the lifetime of this reference `'1`
+
+error: lifetime may not live long enough
+  --> $DIR/issue-58053.rs:11:25
+   |
+LL |     let g = |x: &i32| { x };
+   |                 -   -   ^ returning this value requires that `'1` must outlive `'2`
+   |                 |   |
+   |                 |   return type of closure is &'2 i32
+   |                 let's call the lifetime of this reference `'1`
+
+error: aborting due to 2 previous errors
+
diff --git a/src/test/ui/parser-recovery-2.stderr b/src/test/ui/parser-recovery-2.stderr
index 92d8cbc..76f7af3 100644
--- a/src/test/ui/parser-recovery-2.stderr
+++ b/src/test/ui/parser-recovery-2.stderr
@@ -1,3 +1,9 @@
+error: unexpected token: `;`
+  --> $DIR/parser-recovery-2.rs:12:15
+   |
+LL |     let x = y.;  //~ ERROR unexpected token
+   |               ^
+
 error: incorrect close delimiter: `)`
   --> $DIR/parser-recovery-2.rs:8:5
    |
@@ -7,12 +13,6 @@
 LL |     ) //~ ERROR incorrect close delimiter: `)`
    |     ^ incorrect close delimiter
 
-error: unexpected token: `;`
-  --> $DIR/parser-recovery-2.rs:12:15
-   |
-LL |     let x = y.;  //~ ERROR unexpected token
-   |               ^
-
 error[E0425]: cannot find function `foo` in this scope
   --> $DIR/parser-recovery-2.rs:7:17
    |
diff --git a/src/test/ui/parser/bounds-lifetime.rs b/src/test/ui/parser/bounds-lifetime.rs
index 89a969b..9225cfc 100644
--- a/src/test/ui/parser/bounds-lifetime.rs
+++ b/src/test/ui/parser/bounds-lifetime.rs
@@ -6,6 +6,6 @@
 type A = for<'a: 'b,> fn(); // OK(rejected later by ast_validation)
 type A = for<'a: 'b +> fn(); // OK (rejected later by ast_validation)
 type A = for<'a, T> fn(); // OK (rejected later by ast_validation)
-type A = for<,> fn(); //~ ERROR expected one of `>`, identifier, or lifetime, found `,`
+type A = for<,> fn(); //~ ERROR expected one of `>`, `const`, identifier, or lifetime, found `,`
 
 fn main() {}
diff --git a/src/test/ui/parser/bounds-lifetime.stderr b/src/test/ui/parser/bounds-lifetime.stderr
index f39e5be..191ea3e 100644
--- a/src/test/ui/parser/bounds-lifetime.stderr
+++ b/src/test/ui/parser/bounds-lifetime.stderr
@@ -1,8 +1,8 @@
-error: expected one of `>`, identifier, or lifetime, found `,`
+error: expected one of `>`, `const`, identifier, or lifetime, found `,`
   --> $DIR/bounds-lifetime.rs:9:14
    |
-LL | type A = for<,> fn(); //~ ERROR expected one of `>`, identifier, or lifetime, found `,`
-   |              ^ expected one of `>`, identifier, or lifetime here
+LL | type A = for<,> fn(); //~ ERROR expected one of `>`, `const`, identifier, or lifetime, found `,`
+   |              ^ expected one of `>`, `const`, identifier, or lifetime here
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/parser/issue-10636-2.rs b/src/test/ui/parser/issue-10636-2.rs
index a02fd41..6fb6363 100644
--- a/src/test/ui/parser/issue-10636-2.rs
+++ b/src/test/ui/parser/issue-10636-2.rs
@@ -5,7 +5,7 @@
     option.map(|some| 42;
                           //~^ ERROR: expected one of
 
-} //~ ERROR: incorrect close delimiter
+}
 //~^ ERROR: expected expression, found `)`
 
 fn main() {}
diff --git a/src/test/ui/parser/issue-10636-2.stderr b/src/test/ui/parser/issue-10636-2.stderr
index 9b3115c..38d57ce 100644
--- a/src/test/ui/parser/issue-10636-2.stderr
+++ b/src/test/ui/parser/issue-10636-2.stderr
@@ -1,25 +1,17 @@
-error: incorrect close delimiter: `}`
-  --> $DIR/issue-10636-2.rs:8:1
-   |
-LL | pub fn trace_option(option: Option<isize>) {
-   |                                            - close delimiter possibly meant for this
-LL |     option.map(|some| 42;
-   |               - un-closed delimiter
-...
-LL | } //~ ERROR: incorrect close delimiter
-   | ^ incorrect close delimiter
-
 error: expected one of `)`, `,`, `.`, `?`, or an operator, found `;`
   --> $DIR/issue-10636-2.rs:5:25
    |
 LL |     option.map(|some| 42;
-   |                         ^ expected one of `)`, `,`, `.`, `?`, or an operator here
+   |               -         ^
+   |               |         |
+   |               |         help: `)` may belong here
+   |               unclosed delimiter
 
 error: expected expression, found `)`
   --> $DIR/issue-10636-2.rs:8:1
    |
-LL | } //~ ERROR: incorrect close delimiter
+LL | }
    | ^ expected expression
 
-error: aborting due to 3 previous errors
+error: aborting due to 2 previous errors
 
diff --git a/src/test/ui/parser/issue-14303-enum.stderr b/src/test/ui/parser/issue-14303-enum.stderr
index a31429e..bcecd75 100644
--- a/src/test/ui/parser/issue-14303-enum.stderr
+++ b/src/test/ui/parser/issue-14303-enum.stderr
@@ -2,11 +2,7 @@
   --> $DIR/issue-14303-enum.rs:1:15
    |
 LL | enum X<'a, T, 'b> {
-   |               ^^
-help: move the lifetime parameter prior to the first type parameter
-   |
-LL | enum X<'a, 'b, T> {
-   |            ^^^ --
+   |       --------^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, 'b, T>`
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/parser/issue-14303-fn-def.stderr b/src/test/ui/parser/issue-14303-fn-def.stderr
index 4582aee..082c37e 100644
--- a/src/test/ui/parser/issue-14303-fn-def.stderr
+++ b/src/test/ui/parser/issue-14303-fn-def.stderr
@@ -2,11 +2,7 @@
   --> $DIR/issue-14303-fn-def.rs:1:15
    |
 LL | fn foo<'a, T, 'b>(x: &'a T) {}
-   |               ^^
-help: move the lifetime parameter prior to the first type parameter
-   |
-LL | fn foo<'a, 'b, T>(x: &'a T) {}
-   |            ^^^ --
+   |       --------^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, 'b, T>`
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/parser/issue-14303-fncall.rs b/src/test/ui/parser/issue-14303-fncall.rs
index 17b9b76..3969419 100644
--- a/src/test/ui/parser/issue-14303-fncall.rs
+++ b/src/test/ui/parser/issue-14303-fncall.rs
@@ -11,7 +11,7 @@
     let _x = (*start..*end)
         .map(|x| S { a: start, b: end })
         .collect::<Vec<S<_, 'a>>>();
-        //~^ ERROR lifetime parameters must be declared prior to type parameters
+        //~^ ERROR lifetime arguments must be declared prior to type arguments
 }
 
 fn main() {}
diff --git a/src/test/ui/parser/issue-14303-fncall.stderr b/src/test/ui/parser/issue-14303-fncall.stderr
index 2a73649..8ef9f1a 100644
--- a/src/test/ui/parser/issue-14303-fncall.stderr
+++ b/src/test/ui/parser/issue-14303-fncall.stderr
@@ -1,12 +1,8 @@
-error: lifetime parameters must be declared prior to type parameters
+error: lifetime arguments must be declared prior to type arguments
   --> $DIR/issue-14303-fncall.rs:13:29
    |
 LL |         .collect::<Vec<S<_, 'a>>>();
-   |                             ^^ must be declared prior to type parameters
-help: move the lifetime parameter prior to the first type parameter
-   |
-LL |         .collect::<Vec<S<'a, _>>>();
-   |                          ^^^ --
+   |                             ^^
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/parser/issue-14303-impl.stderr b/src/test/ui/parser/issue-14303-impl.stderr
index a195339..3b5615d 100644
--- a/src/test/ui/parser/issue-14303-impl.stderr
+++ b/src/test/ui/parser/issue-14303-impl.stderr
@@ -2,11 +2,7 @@
   --> $DIR/issue-14303-impl.rs:3:13
    |
 LL | impl<'a, T, 'b> X<T> {}
-   |             ^^
-help: move the lifetime parameter prior to the first type parameter
-   |
-LL | impl<'a, 'b, T> X<T> {}
-   |          ^^^ --
+   |     --------^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, 'b, T>`
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/parser/issue-14303-path.rs b/src/test/ui/parser/issue-14303-path.rs
index a08c89f..386d198 100644
--- a/src/test/ui/parser/issue-14303-path.rs
+++ b/src/test/ui/parser/issue-14303-path.rs
@@ -8,6 +8,6 @@
 }
 
 fn bar<'a, 'b, 'c, T>(x: foo::X<'a, T, 'b, 'c>) {}
-//~^ ERROR lifetime parameters must be declared prior to type parameters
+//~^ ERROR lifetime arguments must be declared prior to type arguments
 
 fn main() {}
diff --git a/src/test/ui/parser/issue-14303-path.stderr b/src/test/ui/parser/issue-14303-path.stderr
index fb4fb32..19f2995 100644
--- a/src/test/ui/parser/issue-14303-path.stderr
+++ b/src/test/ui/parser/issue-14303-path.stderr
@@ -1,14 +1,8 @@
-error: lifetime parameters must be declared prior to type parameters
+error: lifetime arguments must be declared prior to type arguments
   --> $DIR/issue-14303-path.rs:10:40
    |
 LL | fn bar<'a, 'b, 'c, T>(x: foo::X<'a, T, 'b, 'c>) {}
-   |                                        ^^  ^^ must be declared prior to type parameters
-   |                                        |
-   |                                        must be declared prior to type parameters
-help: move the lifetime parameters prior to the first type parameter
-   |
-LL | fn bar<'a, 'b, 'c, T>(x: foo::X<'a, 'b, 'c, T>) {}
-   |                                     ^^^ ^^^ --
+   |                                        ^^  ^^
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/parser/issue-14303-struct.stderr b/src/test/ui/parser/issue-14303-struct.stderr
index 668b8d1..dbd0b98 100644
--- a/src/test/ui/parser/issue-14303-struct.stderr
+++ b/src/test/ui/parser/issue-14303-struct.stderr
@@ -2,11 +2,7 @@
   --> $DIR/issue-14303-struct.rs:1:17
    |
 LL | struct X<'a, T, 'b> {
-   |                 ^^
-help: move the lifetime parameter prior to the first type parameter
-   |
-LL | struct X<'a, 'b, T> {
-   |              ^^^ --
+   |         --------^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, 'b, T>`
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/parser/issue-14303-trait.stderr b/src/test/ui/parser/issue-14303-trait.stderr
index 11ce0c4..7dfa62d 100644
--- a/src/test/ui/parser/issue-14303-trait.stderr
+++ b/src/test/ui/parser/issue-14303-trait.stderr
@@ -2,11 +2,7 @@
   --> $DIR/issue-14303-trait.rs:1:18
    |
 LL | trait Foo<'a, T, 'b> {}
-   |                  ^^
-help: move the lifetime parameter prior to the first type parameter
-   |
-LL | trait Foo<'a, 'b, T> {}
-   |               ^^^ --
+   |          --------^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, 'b, T>`
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/parser/issue-32214.rs b/src/test/ui/parser/issue-32214.rs
index 7e55bc0..7191a32 100644
--- a/src/test/ui/parser/issue-32214.rs
+++ b/src/test/ui/parser/issue-32214.rs
@@ -3,6 +3,6 @@
 trait Trait<T> { type Item; }
 
 pub fn test<W, I: Trait<Item=(), W> >() {}
-//~^ ERROR type parameters must be declared prior to associated type bindings
+//~^ ERROR associated type bindings must be declared after generic parameters
 
 fn main() { }
diff --git a/src/test/ui/parser/issue-32214.stderr b/src/test/ui/parser/issue-32214.stderr
index 660e517..7022019 100644
--- a/src/test/ui/parser/issue-32214.stderr
+++ b/src/test/ui/parser/issue-32214.stderr
@@ -1,12 +1,10 @@
-error: type parameters must be declared prior to associated type bindings
-  --> $DIR/issue-32214.rs:5:34
+error: associated type bindings must be declared after generic parameters
+  --> $DIR/issue-32214.rs:5:25
    |
 LL | pub fn test<W, I: Trait<Item=(), W> >() {}
-   |                                  ^ must be declared prior to associated type bindings
-help: move the type parameter prior to the first associated type binding
-   |
-LL | pub fn test<W, I: Trait<W, Item=()> >() {}
-   |                         ^^       --
+   |                         -------^^^
+   |                         |
+   |                         this associated type binding should be moved after the generic parameters
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/parser/macro-mismatched-delim-paren-brace.stderr b/src/test/ui/parser/macro-mismatched-delim-paren-brace.stderr
index 805ba8b..abb0820 100644
--- a/src/test/ui/parser/macro-mismatched-delim-paren-brace.stderr
+++ b/src/test/ui/parser/macro-mismatched-delim-paren-brace.stderr
@@ -1,3 +1,9 @@
+error: unexpected close delimiter: `}`
+  --> $DIR/macro-mismatched-delim-paren-brace.rs:5:1
+   |
+LL | } //~ ERROR unexpected close delimiter: `}`
+   | ^ unexpected close delimiter
+
 error: incorrect close delimiter: `}`
   --> $DIR/macro-mismatched-delim-paren-brace.rs:4:5
    |
@@ -7,11 +13,5 @@
 LL |     } //~ ERROR incorrect close delimiter
    |     ^ incorrect close delimiter
 
-error: unexpected close delimiter: `}`
-  --> $DIR/macro-mismatched-delim-paren-brace.rs:5:1
-   |
-LL | } //~ ERROR unexpected close delimiter: `}`
-   | ^ unexpected close delimiter
-
 error: aborting due to 2 previous errors
 
diff --git a/src/test/ui/parser/removed-syntax-uniq-mut-ty.rs b/src/test/ui/parser/removed-syntax-uniq-mut-ty.rs
index 12de76d..79d51f5 100644
--- a/src/test/ui/parser/removed-syntax-uniq-mut-ty.rs
+++ b/src/test/ui/parser/removed-syntax-uniq-mut-ty.rs
@@ -1 +1 @@
-type mut_box = Box<mut isize>; //~ ERROR expected one of `>`, lifetime, or type, found `mut`
+type mut_box = Box<mut isize>; //~ ERROR expected one of `>`, const, lifetime, or type, found `mut`
diff --git a/src/test/ui/parser/removed-syntax-uniq-mut-ty.stderr b/src/test/ui/parser/removed-syntax-uniq-mut-ty.stderr
index 0177b19..b275977 100644
--- a/src/test/ui/parser/removed-syntax-uniq-mut-ty.stderr
+++ b/src/test/ui/parser/removed-syntax-uniq-mut-ty.stderr
@@ -1,8 +1,8 @@
-error: expected one of `>`, lifetime, or type, found `mut`
+error: expected one of `>`, const, lifetime, or type, found `mut`
   --> $DIR/removed-syntax-uniq-mut-ty.rs:1:20
    |
-LL | type mut_box = Box<mut isize>; //~ ERROR expected one of `>`, lifetime, or type, found `mut`
-   |                    ^^^ expected one of `>`, lifetime, or type here
+LL | type mut_box = Box<mut isize>; //~ ERROR expected one of `>`, const, lifetime, or type, found `mut`
+   |                    ^^^ expected one of `>`, const, lifetime, or type here
 
 error: aborting due to previous error
 
diff --git a/src/test/ui/resolve/resolve-type-param-in-item-in-trait.rs b/src/test/ui/resolve/resolve-type-param-in-item-in-trait.rs
index 112427a..c77a665 100644
--- a/src/test/ui/resolve/resolve-type-param-in-item-in-trait.rs
+++ b/src/test/ui/resolve/resolve-type-param-in-item-in-trait.rs
@@ -6,7 +6,7 @@
     fn outer(&self) {
         enum Foo<B> {
             Variance(A)
-                //~^ ERROR can't use type parameters from outer function
+                //~^ ERROR can't use generic parameters from outer function
         }
     }
 }
@@ -14,21 +14,21 @@
 trait TraitB<A> {
     fn outer(&self) {
         struct Foo<B>(A);
-                //~^ ERROR can't use type parameters from outer function
+                //~^ ERROR can't use generic parameters from outer function
     }
 }
 
 trait TraitC<A> {
     fn outer(&self) {
         struct Foo<B> { a: A }
-                //~^ ERROR can't use type parameters from outer function
+                //~^ ERROR can't use generic parameters from outer function
     }
 }
 
 trait TraitD<A> {
     fn outer(&self) {
         fn foo<B>(a: A) { }
-                //~^ ERROR can't use type parameters from outer function
+                //~^ ERROR can't use generic parameters from outer function
     }
 }
 
diff --git a/src/test/ui/resolve/resolve-type-param-in-item-in-trait.stderr b/src/test/ui/resolve/resolve-type-param-in-item-in-trait.stderr
index 8eca720..f6b8abf 100644
--- a/src/test/ui/resolve/resolve-type-param-in-item-in-trait.stderr
+++ b/src/test/ui/resolve/resolve-type-param-in-item-in-trait.stderr
@@ -1,44 +1,44 @@
-error[E0401]: can't use type parameters from outer function
+error[E0401]: can't use generic parameters from outer function
   --> $DIR/resolve-type-param-in-item-in-trait.rs:8:22
    |
 LL | trait TraitA<A> {
    |              - type variable from outer function
 LL |     fn outer(&self) {
-   |        ----- try adding a local type parameter in this method instead
+   |        ----- try adding a local generic parameter in this method instead
 LL |         enum Foo<B> {
 LL |             Variance(A)
-   |                      ^ use of type variable from outer function
+   |                      ^ use of generic parameter from outer function
 
-error[E0401]: can't use type parameters from outer function
+error[E0401]: can't use generic parameters from outer function
   --> $DIR/resolve-type-param-in-item-in-trait.rs:16:23
    |
 LL | trait TraitB<A> {
    |              - type variable from outer function
 LL |     fn outer(&self) {
-   |        ----- try adding a local type parameter in this method instead
+   |        ----- try adding a local generic parameter in this method instead
 LL |         struct Foo<B>(A);
-   |                       ^ use of type variable from outer function
+   |                       ^ use of generic parameter from outer function
 
-error[E0401]: can't use type parameters from outer function
+error[E0401]: can't use generic parameters from outer function
   --> $DIR/resolve-type-param-in-item-in-trait.rs:23:28
    |
 LL | trait TraitC<A> {
    |              - type variable from outer function
 LL |     fn outer(&self) {
-   |        ----- try adding a local type parameter in this method instead
+   |        ----- try adding a local generic parameter in this method instead
 LL |         struct Foo<B> { a: A }
-   |                            ^ use of type variable from outer function
+   |                            ^ use of generic parameter from outer function
 
-error[E0401]: can't use type parameters from outer function
+error[E0401]: can't use generic parameters from outer function
   --> $DIR/resolve-type-param-in-item-in-trait.rs:30:22
    |
 LL | trait TraitD<A> {
    |              - type variable from outer function
 LL |     fn outer(&self) {
 LL |         fn foo<B>(a: A) { }
-   |            ------    ^ use of type variable from outer function
+   |            ------    ^ use of generic parameter from outer function
    |            |
-   |            help: try using a local type parameter instead: `foo<B, A>`
+   |            help: try using a local generic parameter instead: `foo<B, A>`
 
 error: aborting due to 4 previous errors
 
diff --git a/src/test/ui/resolve/token-error-correct-3.rs b/src/test/ui/resolve/token-error-correct-3.rs
index 86cf711..b1ca0bb 100644
--- a/src/test/ui/resolve/token-error-correct-3.rs
+++ b/src/test/ui/resolve/token-error-correct-3.rs
@@ -17,7 +17,7 @@
             //~| expected type `()`
             //~| found type `std::result::Result<bool, std::io::Error>`
             //~| expected one of
-        } else { //~ ERROR: incorrect close delimiter: `}`
+        } else {
             //~^ ERROR: expected one of
             //~| unexpected token
             Ok(false);
diff --git a/src/test/ui/resolve/token-error-correct-3.stderr b/src/test/ui/resolve/token-error-correct-3.stderr
index 2164d27..a6bb83c 100644
--- a/src/test/ui/resolve/token-error-correct-3.stderr
+++ b/src/test/ui/resolve/token-error-correct-3.stderr
@@ -1,19 +1,11 @@
-error: incorrect close delimiter: `}`
-  --> $DIR/token-error-correct-3.rs:20:9
-   |
-LL |         if !is_directory(path.as_ref()) { //~ ERROR: cannot find function `is_directory`
-   |                                         - close delimiter possibly meant for this
-LL |             callback(path.as_ref(); //~ ERROR expected one of
-   |                     - un-closed delimiter
-...
-LL |         } else { //~ ERROR: incorrect close delimiter: `}`
-   |         ^ incorrect close delimiter
-
 error: expected one of `)`, `,`, `.`, `?`, or an operator, found `;`
   --> $DIR/token-error-correct-3.rs:14:35
    |
 LL |             callback(path.as_ref(); //~ ERROR expected one of
-   |                                   ^ expected one of `)`, `,`, `.`, `?`, or an operator here
+   |                     -             ^
+   |                     |             |
+   |                     |             help: `)` may belong here
+   |                     unclosed delimiter
 
 error: expected one of `.`, `;`, `?`, `}`, or an operator, found `)`
   --> $DIR/token-error-correct-3.rs:20:9
@@ -21,7 +13,7 @@
 LL |             fs::create_dir_all(path.as_ref()).map(|()| true) //~ ERROR: mismatched types
    |                                                             - expected one of `.`, `;`, `?`, `}`, or an operator here
 ...
-LL |         } else { //~ ERROR: incorrect close delimiter: `}`
+LL |         } else {
    |         ^ unexpected token
 
 error[E0425]: cannot find function `is_directory` in this scope
@@ -41,7 +33,7 @@
    = note: expected type `()`
               found type `std::result::Result<bool, std::io::Error>`
 
-error: aborting due to 5 previous errors
+error: aborting due to 4 previous errors
 
 Some errors occurred: E0308, E0425.
 For more information about an error, try `rustc --explain E0308`.
diff --git a/src/test/ui/resolve/token-error-correct.rs b/src/test/ui/resolve/token-error-correct.rs
index b97e22f..d649077 100644
--- a/src/test/ui/resolve/token-error-correct.rs
+++ b/src/test/ui/resolve/token-error-correct.rs
@@ -2,6 +2,8 @@
 
 fn main() {
     foo(bar(;
-    //~^ ERROR: expected expression, found `;`
+    //~^ ERROR cannot find function `bar` in this scope
 }
 //~^ ERROR: incorrect close delimiter: `}`
+
+fn foo(_: usize) {}
diff --git a/src/test/ui/resolve/token-error-correct.stderr b/src/test/ui/resolve/token-error-correct.stderr
index 0a45904..b0827ea 100644
--- a/src/test/ui/resolve/token-error-correct.stderr
+++ b/src/test/ui/resolve/token-error-correct.stderr
@@ -5,15 +5,16 @@
    |           - close delimiter possibly meant for this
 LL |     foo(bar(;
    |            - un-closed delimiter
-LL |     //~^ ERROR: expected expression, found `;`
+LL |     //~^ ERROR cannot find function `bar` in this scope
 LL | }
    | ^ incorrect close delimiter
 
-error: expected expression, found `;`
-  --> $DIR/token-error-correct.rs:4:13
+error[E0425]: cannot find function `bar` in this scope
+  --> $DIR/token-error-correct.rs:4:9
    |
 LL |     foo(bar(;
-   |             ^ expected expression
+   |         ^^^ not found in this scope
 
 error: aborting due to 2 previous errors
 
+For more information about this error, try `rustc --explain E0425`.
diff --git a/src/test/ui/rfc-2166-underscore-imports/basic.stderr b/src/test/ui/rfc-2166-underscore-imports/basic.stderr
index 3080359..c7b36ea 100644
--- a/src/test/ui/rfc-2166-underscore-imports/basic.stderr
+++ b/src/test/ui/rfc-2166-underscore-imports/basic.stderr
@@ -2,7 +2,7 @@
   --> $DIR/basic.rs:26:9
    |
 LL |     use m::Tr1 as _; //~ WARN unused import
-   |         ^^^^^^^^^^^
+   |     ----^^^^^^^^^^^- help: remove the whole `use` item
    |
 note: lint level defined here
   --> $DIR/basic.rs:4:9
@@ -14,5 +14,5 @@
   --> $DIR/basic.rs:27:9
    |
 LL |     use S as _; //~ WARN unused import
-   |         ^^^^^^
+   |     ----^^^^^^- help: remove the whole `use` item
 
diff --git a/src/test/ui/rfc-2166-underscore-imports/unused-2018.stderr b/src/test/ui/rfc-2166-underscore-imports/unused-2018.stderr
index 4163c28..0bbc172 100644
--- a/src/test/ui/rfc-2166-underscore-imports/unused-2018.stderr
+++ b/src/test/ui/rfc-2166-underscore-imports/unused-2018.stderr
@@ -2,7 +2,7 @@
   --> $DIR/unused-2018.rs:6:9
    |
 LL |     use core::any; //~ ERROR unused import: `core::any`
-   |         ^^^^^^^^^
+   |     ----^^^^^^^^^- help: remove the whole `use` item
    |
 note: lint level defined here
   --> $DIR/unused-2018.rs:3:9
@@ -14,7 +14,7 @@
   --> $DIR/unused-2018.rs:10:9
    |
 LL |     use core; //~ ERROR unused import: `core`
-   |         ^^^^
+   |     ----^^^^- help: remove the whole `use` item
 
 error: aborting due to 2 previous errors
 
diff --git a/src/test/ui/rfc1598-generic-associated-types/empty_generics.rs b/src/test/ui/rfc1598-generic-associated-types/empty_generics.rs
index 158ebc7..afc2770 100644
--- a/src/test/ui/rfc1598-generic-associated-types/empty_generics.rs
+++ b/src/test/ui/rfc1598-generic-associated-types/empty_generics.rs
@@ -3,7 +3,7 @@
 
 trait Foo {
     type Bar<,>;
-    //~^ ERROR expected one of `>`, identifier, or lifetime, found `,`
+    //~^ ERROR expected one of `>`, `const`, identifier, or lifetime, found `,`
 }
 
 fn main() {}
diff --git a/src/test/ui/rfc1598-generic-associated-types/empty_generics.stderr b/src/test/ui/rfc1598-generic-associated-types/empty_generics.stderr
index 2a01b2a..5b98302 100644
--- a/src/test/ui/rfc1598-generic-associated-types/empty_generics.stderr
+++ b/src/test/ui/rfc1598-generic-associated-types/empty_generics.stderr
@@ -1,8 +1,8 @@
-error: expected one of `>`, identifier, or lifetime, found `,`
+error: expected one of `>`, `const`, identifier, or lifetime, found `,`
   --> $DIR/empty_generics.rs:5:14
    |
 LL |     type Bar<,>;
-   |              ^ expected one of `>`, identifier, or lifetime here
+   |              ^ expected one of `>`, `const`, identifier, or lifetime here
 
 warning: the feature `generic_associated_types` is incomplete and may cause the compiler to crash
   --> $DIR/empty_generics.rs:1:12
diff --git a/src/test/ui/span/multispan-import-lint.stderr b/src/test/ui/span/multispan-import-lint.stderr
index a730d08..6bd0e9b 100644
--- a/src/test/ui/span/multispan-import-lint.stderr
+++ b/src/test/ui/span/multispan-import-lint.stderr
@@ -10,4 +10,8 @@
 LL | #![warn(unused)]
    |         ^^^^^^
    = note: #[warn(unused_imports)] implied by #[warn(unused)]
+help: remove the unused imports
+   |
+LL | use std::cmp::{min};
+   |               -- --
 
diff --git a/src/test/ui/suggestions/suggest-move-lifetimes.stderr b/src/test/ui/suggestions/suggest-move-lifetimes.stderr
index b36e927..2d6dee0 100644
--- a/src/test/ui/suggestions/suggest-move-lifetimes.stderr
+++ b/src/test/ui/suggestions/suggest-move-lifetimes.stderr
@@ -2,41 +2,25 @@
   --> $DIR/suggest-move-lifetimes.rs:1:13
    |
 LL | struct A<T, 'a> { //~ ERROR lifetime parameters must be declared
-   |             ^^
-help: move the lifetime parameter prior to the first type parameter
-   |
-LL | struct A<'a, T> { //~ ERROR lifetime parameters must be declared
-   |          ^^^ --
+   |         ----^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, T>`
 
 error: lifetime parameters must be declared prior to type parameters
   --> $DIR/suggest-move-lifetimes.rs:5:13
    |
 LL | struct B<T, 'a, U> { //~ ERROR lifetime parameters must be declared
-   |             ^^
-help: move the lifetime parameter prior to the first type parameter
-   |
-LL | struct B<'a, T, U> { //~ ERROR lifetime parameters must be declared
-   |          ^^^ --
+   |         ----^^---- help: reorder the parameters: lifetimes, then types, then consts: `<'a, T, U>`
 
 error: lifetime parameters must be declared prior to type parameters
   --> $DIR/suggest-move-lifetimes.rs:10:16
    |
 LL | struct C<T, U, 'a> { //~ ERROR lifetime parameters must be declared
-   |                ^^
-help: move the lifetime parameter prior to the first type parameter
-   |
-LL | struct C<'a, T, U> { //~ ERROR lifetime parameters must be declared
-   |          ^^^    --
+   |         -------^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, T, U>`
 
 error: lifetime parameters must be declared prior to type parameters
   --> $DIR/suggest-move-lifetimes.rs:15:16
    |
 LL | struct D<T, U, 'a, 'b, V, 'c> { //~ ERROR lifetime parameters must be declared
-   |                ^^  ^^     ^^
-help: move the lifetime parameter prior to the first type parameter
-   |
-LL | struct D<'a, 'b, 'c, T, U, V> { //~ ERROR lifetime parameters must be declared
-   |          ^^^ ^^^ ^^^    -- --
+   |         -------^^--^^-----^^- help: reorder the parameters: lifetimes, then types, then consts: `<'a, 'b, 'c, T, U, V>`
 
 error: aborting due to 4 previous errors
 
diff --git a/src/test/ui/suggestions/suggest-move-types.rs b/src/test/ui/suggestions/suggest-move-types.rs
index fd10ba4..890950e 100644
--- a/src/test/ui/suggestions/suggest-move-types.rs
+++ b/src/test/ui/suggestions/suggest-move-types.rs
@@ -25,19 +25,20 @@
   type C;
 }
 
-struct A<T, M: One<A=(), T>> { //~ ERROR type parameters must be declared
+struct A<T, M: One<A=(), T>> { //~ ERROR associated type bindings must be declared after generic parameters
     m: M,
     t: T,
 }
 
 
 struct Al<'a, T, M: OneWithLifetime<A=(), T, 'a>> {
-//~^ ERROR generic arguments must declare lifetimes, types and associated type bindings in that order
+//~^ ERROR associated type bindings must be declared after generic parameters
+//~^^ ERROR lifetime arguments must be declared prior to type arguments
     m: M,
     t: &'a T,
 }
 
-struct B<T, U, V, M: Three<A=(), B=(), C=(), T, U, V>> { //~ ERROR type parameters must be declared
+struct B<T, U, V, M: Three<A=(), B=(), C=(), T, U, V>> { //~ ERROR associated type bindings must be declared after generic parameters
     m: M,
     t: T,
     u: U,
@@ -45,14 +46,15 @@
 }
 
 struct Bl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime<A=(), B=(), C=(), T, U, V, 'a, 'b, 'c>> {
-//~^ ERROR generic arguments must declare lifetimes, types and associated type bindings in that order
+//~^ ERROR associated type bindings must be declared after generic parameters
+//~^^ ERROR lifetime arguments must be declared prior to type arguments
     m: M,
     t: &'a T,
     u: &'b U,
     v: &'c V,
 }
 
-struct C<T, U, V, M: Three<T, A=(), B=(), C=(), U, V>> { //~ ERROR type parameters must be declared
+struct C<T, U, V, M: Three<T, A=(), B=(), C=(), U, V>> { //~ ERROR associated type bindings must be declared after generic parameters
     m: M,
     t: T,
     u: U,
@@ -60,14 +62,15 @@
 }
 
 struct Cl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime<T, 'a, A=(), B=(), C=(), U, 'b, V, 'c>> {
-//~^ ERROR generic arguments must declare lifetimes, types and associated type bindings in that order
+//~^ ERROR associated type bindings must be declared after generic parameters
+//~^^ ERROR lifetime arguments must be declared prior to type arguments
     m: M,
     t: &'a T,
     u: &'b U,
     v: &'c V,
 }
 
-struct D<T, U, V, M: Three<T, A=(), B=(), U, C=(), V>> { //~ ERROR type parameters must be declared
+struct D<T, U, V, M: Three<T, A=(), B=(), U, C=(), V>> { //~ ERROR associated type bindings must be declared after generic parameters
     m: M,
     t: T,
     u: U,
@@ -75,7 +78,8 @@
 }
 
 struct Dl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime<T, 'a, A=(), B=(), U, 'b, C=(), V, 'c>> {
-//~^ ERROR generic arguments must declare lifetimes, types and associated type bindings in that order
+//~^ ERROR associated type bindings must be declared after generic parameters
+//~^^ ERROR lifetime arguments must be declared prior to type arguments
     m: M,
     t: &'a T,
     u: &'b U,
diff --git a/src/test/ui/suggestions/suggest-move-types.stderr b/src/test/ui/suggestions/suggest-move-types.stderr
index 3643d9a..0901b71 100644
--- a/src/test/ui/suggestions/suggest-move-types.stderr
+++ b/src/test/ui/suggestions/suggest-move-types.stderr
@@ -1,107 +1,102 @@
-error: type parameters must be declared prior to associated type bindings
-  --> $DIR/suggest-move-types.rs:28:26
+error: associated type bindings must be declared after generic parameters
+  --> $DIR/suggest-move-types.rs:28:20
    |
-LL | struct A<T, M: One<A=(), T>> { //~ ERROR type parameters must be declared
-   |                          ^ must be declared prior to associated type bindings
-help: move the type parameter prior to the first associated type binding
-   |
-LL | struct A<T, M: One<T, A=()>> { //~ ERROR type parameters must be declared
-   |                    ^^    --
+LL | struct A<T, M: One<A=(), T>> { //~ ERROR associated type bindings must be declared after generic parameters
+   |                    ----^^^
+   |                    |
+   |                    this associated type binding should be moved after the generic parameters
 
-error: generic arguments must declare lifetimes, types and associated type bindings in that order
+error: associated type bindings must be declared after generic parameters
+  --> $DIR/suggest-move-types.rs:34:37
+   |
+LL | struct Al<'a, T, M: OneWithLifetime<A=(), T, 'a>> {
+   |                                     ----^^^^^^^
+   |                                     |
+   |                                     this associated type binding should be moved after the generic parameters
+
+error: associated type bindings must be declared after generic parameters
+  --> $DIR/suggest-move-types.rs:41:28
+   |
+LL | struct B<T, U, V, M: Three<A=(), B=(), C=(), T, U, V>> { //~ ERROR associated type bindings must be declared after generic parameters
+   |                            ----^^----^^----^^^^^^^^^
+   |                            |     |     |
+   |                            |     |     this associated type binding should be moved after the generic parameters
+   |                            |     this associated type binding should be moved after the generic parameters
+   |                            this associated type binding should be moved after the generic parameters
+
+error: associated type bindings must be declared after generic parameters
+  --> $DIR/suggest-move-types.rs:48:53
+   |
+LL | struct Bl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime<A=(), B=(), C=(), T, U, V, 'a, 'b, 'c>> {
+   |                                                     ----^^----^^----^^^^^^^^^^^^^^^^^^^^^
+   |                                                     |     |     |
+   |                                                     |     |     this associated type binding should be moved after the generic parameters
+   |                                                     |     this associated type binding should be moved after the generic parameters
+   |                                                     this associated type binding should be moved after the generic parameters
+
+error: associated type bindings must be declared after generic parameters
+  --> $DIR/suggest-move-types.rs:57:28
+   |
+LL | struct C<T, U, V, M: Three<T, A=(), B=(), C=(), U, V>> { //~ ERROR associated type bindings must be declared after generic parameters
+   |                            ^^^----^^----^^----^^^^^^
+   |                               |     |     |
+   |                               |     |     this associated type binding should be moved after the generic parameters
+   |                               |     this associated type binding should be moved after the generic parameters
+   |                               this associated type binding should be moved after the generic parameters
+
+error: associated type bindings must be declared after generic parameters
+  --> $DIR/suggest-move-types.rs:64:53
+   |
+LL | struct Cl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime<T, 'a, A=(), B=(), C=(), U, 'b, V, 'c>> {
+   |                                                     ^^^^^^^----^^----^^----^^^^^^^^^^^^^^
+   |                                                            |     |     |
+   |                                                            |     |     this associated type binding should be moved after the generic parameters
+   |                                                            |     this associated type binding should be moved after the generic parameters
+   |                                                            this associated type binding should be moved after the generic parameters
+
+error: associated type bindings must be declared after generic parameters
+  --> $DIR/suggest-move-types.rs:73:28
+   |
+LL | struct D<T, U, V, M: Three<T, A=(), B=(), U, C=(), V>> { //~ ERROR associated type bindings must be declared after generic parameters
+   |                            ^^^----^^----^^^^^----^^^
+   |                               |     |        |
+   |                               |     |        this associated type binding should be moved after the generic parameters
+   |                               |     this associated type binding should be moved after the generic parameters
+   |                               this associated type binding should be moved after the generic parameters
+
+error: associated type bindings must be declared after generic parameters
+  --> $DIR/suggest-move-types.rs:80:53
+   |
+LL | struct Dl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime<T, 'a, A=(), B=(), U, 'b, C=(), V, 'c>> {
+   |                                                     ^^^^^^^----^^----^^^^^^^^^----^^^^^^^
+   |                                                            |     |            |
+   |                                                            |     |            this associated type binding should be moved after the generic parameters
+   |                                                            |     this associated type binding should be moved after the generic parameters
+   |                                                            this associated type binding should be moved after the generic parameters
+
+error: lifetime arguments must be declared prior to type arguments
   --> $DIR/suggest-move-types.rs:34:46
    |
 LL | struct Al<'a, T, M: OneWithLifetime<A=(), T, 'a>> {
-   |                                           ^  ^^ must be declared prior to type parameters
-   |                                           |
-   |                                           must be declared prior to associated type bindings
-help: move the parameters
-   |
-LL | struct Al<'a, T, M: OneWithLifetime<'a, T, A=()>> {
-   |                                     ^^^ ^^    --
+   |                                              ^^
 
-error: type parameters must be declared prior to associated type bindings
-  --> $DIR/suggest-move-types.rs:40:46
-   |
-LL | struct B<T, U, V, M: Three<A=(), B=(), C=(), T, U, V>> { //~ ERROR type parameters must be declared
-   |                                              ^  ^  ^ must be declared prior to associated type bindings
-   |                                              |  |
-   |                                              |  must be declared prior to associated type bindings
-   |                                              must be declared prior to associated type bindings
-help: move the type parameters prior to the first associated type binding
-   |
-LL | struct B<T, U, V, M: Three<T, U, V, A=(), B=(), C=()>> { //~ ERROR type parameters must be declared
-   |                            ^^ ^^ ^^                --
-
-error: generic arguments must declare lifetimes, types and associated type bindings in that order
-  --> $DIR/suggest-move-types.rs:47:80
+error: lifetime arguments must be declared prior to type arguments
+  --> $DIR/suggest-move-types.rs:48:80
    |
 LL | struct Bl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime<A=(), B=(), C=(), T, U, V, 'a, 'b, 'c>> {
-   |                                                                       ^  ^  ^  ^^  ^^  ^^ must be declared prior to type parameters
-   |                                                                       |  |  |  |   |
-   |                                                                       |  |  |  |   must be declared prior to type parameters
-   |                                                                       |  |  |  must be declared prior to type parameters
-   |                                                                       |  |  must be declared prior to associated type bindings
-   |                                                                       |  must be declared prior to associated type bindings
-   |                                                                       must be declared prior to associated type bindings
-help: move the parameters
-   |
-LL | struct Bl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime<'a, 'b, 'c, T, U, V, A=(), B=(), C=()>> {
-   |                                                     ^^^ ^^^ ^^^ ^^ ^^ ^^                --
+   |                                                                                ^^  ^^  ^^
 
-error: type parameters must be declared prior to associated type bindings
-  --> $DIR/suggest-move-types.rs:55:49
-   |
-LL | struct C<T, U, V, M: Three<T, A=(), B=(), C=(), U, V>> { //~ ERROR type parameters must be declared
-   |                                                 ^  ^ must be declared prior to associated type bindings
-   |                                                 |
-   |                                                 must be declared prior to associated type bindings
-help: move the type parameters prior to the first associated type binding
-   |
-LL | struct C<T, U, V, M: Three<T, U, V, A=(), B=(), C=()>> { //~ ERROR type parameters must be declared
-   |                               ^^ ^^                --
-
-error: generic arguments must declare lifetimes, types and associated type bindings in that order
-  --> $DIR/suggest-move-types.rs:62:56
+error: lifetime arguments must be declared prior to type arguments
+  --> $DIR/suggest-move-types.rs:64:56
    |
 LL | struct Cl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime<T, 'a, A=(), B=(), C=(), U, 'b, V, 'c>> {
-   |                                                        ^^                    ^  ^^  ^  ^^ must be declared prior to type parameters
-   |                                                        |                     |  |   |
-   |                                                        |                     |  |   must be declared prior to associated type bindings
-   |                                                        |                     |  must be declared prior to type parameters
-   |                                                        |                     must be declared prior to associated type bindings
-   |                                                        must be declared prior to type parameters
-help: move the parameters
-   |
-LL | struct Cl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime<'a, 'b, 'c, T, U, V, A=(), B=(), C=()>> {
-   |                                                     ^^^ ^^^ ^^^ -- ^^ ^^                --
+   |                                                        ^^                       ^^     ^^
 
-error: type parameters must be declared prior to associated type bindings
-  --> $DIR/suggest-move-types.rs:70:43
-   |
-LL | struct D<T, U, V, M: Three<T, A=(), B=(), U, C=(), V>> { //~ ERROR type parameters must be declared
-   |                                           ^        ^ must be declared prior to associated type bindings
-   |                                           |
-   |                                           must be declared prior to associated type bindings
-help: move the type parameters prior to the first associated type binding
-   |
-LL | struct D<T, U, V, M: Three<T, U, V, A=(), B=(), C=()>> { //~ ERROR type parameters must be declared
-   |                               ^^ ^^          --    --
-
-error: generic arguments must declare lifetimes, types and associated type bindings in that order
-  --> $DIR/suggest-move-types.rs:77:56
+error: lifetime arguments must be declared prior to type arguments
+  --> $DIR/suggest-move-types.rs:80:56
    |
 LL | struct Dl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime<T, 'a, A=(), B=(), U, 'b, C=(), V, 'c>> {
-   |                                                        ^^              ^  ^^        ^  ^^ must be declared prior to type parameters
-   |                                                        |               |  |         |
-   |                                                        |               |  |         must be declared prior to associated type bindings
-   |                                                        |               |  must be declared prior to type parameters
-   |                                                        |               must be declared prior to associated type bindings
-   |                                                        must be declared prior to type parameters
-help: move the parameters
-   |
-LL | struct Dl<'a, 'b, 'c, T, U, V, M: ThreeWithLifetime<'a, 'b, 'c, T, U, V, A=(), B=(), C=()>> {
-   |                                                     ^^^ ^^^ ^^^ -- ^^ ^^          --    --
+   |                                                        ^^                 ^^           ^^
 
-error: aborting due to 8 previous errors
+error: aborting due to 12 previous errors
 
diff --git a/src/test/ui/traits/trait-object-vs-lifetime.rs b/src/test/ui/traits/trait-object-vs-lifetime.rs
index a12429c..36dec21 100644
--- a/src/test/ui/traits/trait-object-vs-lifetime.rs
+++ b/src/test/ui/traits/trait-object-vs-lifetime.rs
@@ -12,6 +12,6 @@
     //~^ ERROR wrong number of lifetime arguments: expected 1, found 2
     //~| ERROR wrong number of type arguments: expected 1, found 0
     let _: S<'static +, 'static>;
-    //~^ ERROR lifetime parameters must be declared prior to type parameters
+    //~^ ERROR lifetime arguments must be declared prior to type arguments
     //~| ERROR at least one non-builtin trait is required for an object type
 }
diff --git a/src/test/ui/traits/trait-object-vs-lifetime.stderr b/src/test/ui/traits/trait-object-vs-lifetime.stderr
index 4cc96ba..e0c52a7 100644
--- a/src/test/ui/traits/trait-object-vs-lifetime.stderr
+++ b/src/test/ui/traits/trait-object-vs-lifetime.stderr
@@ -1,12 +1,8 @@
-error: lifetime parameters must be declared prior to type parameters
+error: lifetime arguments must be declared prior to type arguments
   --> $DIR/trait-object-vs-lifetime.rs:14:25
    |
 LL |     let _: S<'static +, 'static>;
-   |                         ^^^^^^^ must be declared prior to type parameters
-help: move the lifetime parameter prior to the first type parameter
-   |
-LL |     let _: S<'static, 'static +>;
-   |              ^^^^^^^^         --
+   |                         ^^^^^^^
 
 error[E0224]: at least one non-builtin trait is required for an object type
   --> $DIR/trait-object-vs-lifetime.rs:9:23
diff --git a/src/test/ui/type/type-arg-out-of-scope.rs b/src/test/ui/type/type-arg-out-of-scope.rs
index b96c9bf..d5b815f 100644
--- a/src/test/ui/type/type-arg-out-of-scope.rs
+++ b/src/test/ui/type/type-arg-out-of-scope.rs
@@ -1,4 +1,4 @@
-// error-pattern:can't use type parameters from outer function
+// error-pattern:can't use generic parameters from outer function
 fn foo<T>(x: T) {
     fn bar(f: Box<FnMut(T) -> T>) { }
 }
diff --git a/src/test/ui/type/type-arg-out-of-scope.stderr b/src/test/ui/type/type-arg-out-of-scope.stderr
index 62b6a86..645cbb3 100644
--- a/src/test/ui/type/type-arg-out-of-scope.stderr
+++ b/src/test/ui/type/type-arg-out-of-scope.stderr
@@ -1,22 +1,22 @@
-error[E0401]: can't use type parameters from outer function
+error[E0401]: can't use generic parameters from outer function
   --> $DIR/type-arg-out-of-scope.rs:3:25
    |
 LL | fn foo<T>(x: T) {
    |        - type variable from outer function
 LL |     fn bar(f: Box<FnMut(T) -> T>) { }
-   |        ---              ^ use of type variable from outer function
+   |        ---              ^ use of generic parameter from outer function
    |        |
-   |        help: try using a local type parameter instead: `bar<T>`
+   |        help: try using a local generic parameter instead: `bar<T>`
 
-error[E0401]: can't use type parameters from outer function
+error[E0401]: can't use generic parameters from outer function
   --> $DIR/type-arg-out-of-scope.rs:3:31
    |
 LL | fn foo<T>(x: T) {
    |        - type variable from outer function
 LL |     fn bar(f: Box<FnMut(T) -> T>) { }
-   |        ---                    ^ use of type variable from outer function
+   |        ---                    ^ use of generic parameter from outer function
    |        |
-   |        help: try using a local type parameter instead: `bar<T>`
+   |        help: try using a local generic parameter instead: `bar<T>`
 
 error: aborting due to 2 previous errors
 
diff --git a/src/test/ui/type/type-dependent-def-issue-49241.rs b/src/test/ui/type/type-dependent-def-issue-49241.rs
index 4c366a8..51bd116 100644
--- a/src/test/ui/type/type-dependent-def-issue-49241.rs
+++ b/src/test/ui/type/type-dependent-def-issue-49241.rs
@@ -1,6 +1,6 @@
 fn main() {
     let v = vec![0];
-    const l: usize = v.count(); //~ ERROR can't capture dynamic environment in a fn item
+    const l: usize = v.count(); //~ ERROR attempt to use a non-constant value in a constant
     let s: [u32; l] = v.into_iter().collect();
     //~^ ERROR evaluation of constant value failed
 }
diff --git a/src/test/ui/type/type-dependent-def-issue-49241.stderr b/src/test/ui/type/type-dependent-def-issue-49241.stderr
index 8783959..0af777f 100644
--- a/src/test/ui/type/type-dependent-def-issue-49241.stderr
+++ b/src/test/ui/type/type-dependent-def-issue-49241.stderr
@@ -1,10 +1,8 @@
-error[E0434]: can't capture dynamic environment in a fn item
+error[E0435]: attempt to use a non-constant value in a constant
   --> $DIR/type-dependent-def-issue-49241.rs:3:22
    |
-LL |     const l: usize = v.count(); //~ ERROR can't capture dynamic environment in a fn item
-   |                      ^
-   |
-   = help: use the `|| { ... }` closure form instead
+LL |     const l: usize = v.count(); //~ ERROR attempt to use a non-constant value in a constant
+   |                      ^ non-constant value
 
 error[E0080]: evaluation of constant value failed
   --> $DIR/type-dependent-def-issue-49241.rs:4:18
@@ -14,5 +12,5 @@
 
 error: aborting due to 2 previous errors
 
-Some errors occurred: E0080, E0434.
+Some errors occurred: E0080, E0435.
 For more information about an error, try `rustc --explain E0080`.
diff --git a/src/test/ui/use-self-in-inner-fn.rs b/src/test/ui/use-self-in-inner-fn.rs
index cde96dc..eccb315 100644
--- a/src/test/ui/use-self-in-inner-fn.rs
+++ b/src/test/ui/use-self-in-inner-fn.rs
@@ -4,8 +4,8 @@
 //~^ NOTE `Self` type implicitly declared here, by this `impl`
     fn banana(&mut self) {
         fn peach(this: &Self) {
-        //~^ ERROR can't use type parameters from outer function
-        //~| NOTE use of type variable from outer function
+        //~^ ERROR can't use generic parameters from outer function
+        //~| NOTE use of generic parameter from outer function
         //~| NOTE use a type here instead
         }
     }
diff --git a/src/test/ui/use-self-in-inner-fn.stderr b/src/test/ui/use-self-in-inner-fn.stderr
index a613804..9660934 100644
--- a/src/test/ui/use-self-in-inner-fn.stderr
+++ b/src/test/ui/use-self-in-inner-fn.stderr
@@ -1,4 +1,4 @@
-error[E0401]: can't use type parameters from outer function
+error[E0401]: can't use generic parameters from outer function
   --> $DIR/use-self-in-inner-fn.rs:6:25
    |
 LL | impl A {
@@ -7,7 +7,7 @@
 LL |         fn peach(this: &Self) {
    |                         ^^^^
    |                         |
-   |                         use of type variable from outer function
+   |                         use of generic parameter from outer function
    |                         use a type here instead
 
 error: aborting due to previous error
diff --git a/src/test/ui/use/use-nested-groups-unused-imports.rs b/src/test/ui/use/use-nested-groups-unused-imports.rs
index 5bdc7b2..5fe8595 100644
--- a/src/test/ui/use/use-nested-groups-unused-imports.rs
+++ b/src/test/ui/use/use-nested-groups-unused-imports.rs
@@ -18,7 +18,7 @@
 use foo::bar::baz::{*, *};
     //~^ ERROR unused import: `*`
 use foo::{};
-    //~^ ERROR unused import: `use foo::{};`
+    //~^ ERROR unused import: `foo::{}`
 
 fn main() {
     let _: Bar;
diff --git a/src/test/ui/use/use-nested-groups-unused-imports.stderr b/src/test/ui/use/use-nested-groups-unused-imports.stderr
index f60c7f5..6af6f44 100644
--- a/src/test/ui/use/use-nested-groups-unused-imports.stderr
+++ b/src/test/ui/use/use-nested-groups-unused-imports.stderr
@@ -2,7 +2,7 @@
   --> $DIR/use-nested-groups-unused-imports.rs:16:11
    |
 LL | use foo::{Foo, bar::{baz::{}, foobar::*}, *};
-   |           ^^^        ^^^^^^^  ^^^^^^^^^   ^
+   | ----------^^^--------^^^^^^^--^^^^^^^^^---^-- help: remove the whole `use` item
    |
 note: lint level defined here
   --> $DIR/use-nested-groups-unused-imports.rs:3:9
@@ -14,13 +14,15 @@
   --> $DIR/use-nested-groups-unused-imports.rs:18:24
    |
 LL | use foo::bar::baz::{*, *};
-   |                        ^
+   |                      --^
+   |                      |
+   |                      help: remove the unused import
 
-error: unused import: `use foo::{};`
-  --> $DIR/use-nested-groups-unused-imports.rs:20:1
+error: unused import: `foo::{}`
+  --> $DIR/use-nested-groups-unused-imports.rs:20:5
    |
 LL | use foo::{};
-   | ^^^^^^^^^^^^
+   | ----^^^^^^^- help: remove the whole `use` item
 
 error: aborting due to 3 previous errors
 
diff --git a/src/tools/cargo b/src/tools/cargo
index 4e74e2f..865cb70 160000
--- a/src/tools/cargo
+++ b/src/tools/cargo
@@ -1 +1 @@
-Subproject commit 4e74e2fc0908524d17735c768067117d3e84ee9c
+Subproject commit 865cb70106a6b1171a500ff68f93ab52eea56e72
diff --git a/src/tools/compiletest/Cargo.toml b/src/tools/compiletest/Cargo.toml
index edf4aea..00e1a53 100644
--- a/src/tools/compiletest/Cargo.toml
+++ b/src/tools/compiletest/Cargo.toml
@@ -2,6 +2,7 @@
 authors = ["The Rust Project Developers"]
 name = "compiletest"
 version = "0.0.0"
+edition = "2018"
 
 [dependencies]
 diff = "0.1.10"
diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs
index f6f8ef1..42afb72 100644
--- a/src/tools/compiletest/src/common.rs
+++ b/src/tools/compiletest/src/common.rs
@@ -5,7 +5,7 @@
 use std::str::FromStr;
 
 use test::ColorConfig;
-use util::PathBufExt;
+use crate::util::PathBufExt;
 
 #[derive(Clone, Copy, PartialEq, Debug)]
 pub enum Mode {
@@ -66,7 +66,7 @@
 }
 
 impl fmt::Display for Mode {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         let s = match *self {
             CompileFail => "compile-fail",
             RunFail => "run-fail",
diff --git a/src/tools/compiletest/src/errors.rs b/src/tools/compiletest/src/errors.rs
index fd3f002..0329fb0 100644
--- a/src/tools/compiletest/src/errors.rs
+++ b/src/tools/compiletest/src/errors.rs
@@ -33,7 +33,7 @@
 }
 
 impl fmt::Display for ErrorKind {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match *self {
             ErrorKind::Help => write!(f, "help message"),
             ErrorKind::Error => write!(f, "error"),
diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs
index 591d92f..80a015d 100644
--- a/src/tools/compiletest/src/header.rs
+++ b/src/tools/compiletest/src/header.rs
@@ -4,10 +4,10 @@
 use std::io::BufReader;
 use std::path::{Path, PathBuf};
 
-use common::{self, CompareMode, Config, Mode};
-use util;
+use crate::common::{self, CompareMode, Config, Mode};
+use crate::util;
 
-use extract_gdb_version;
+use crate::extract_gdb_version;
 
 /// Whether to ignore the test.
 #[derive(Clone, Copy, PartialEq, Debug)]
diff --git a/src/tools/compiletest/src/json.rs b/src/tools/compiletest/src/json.rs
index 106aa67..12aae30 100644
--- a/src/tools/compiletest/src/json.rs
+++ b/src/tools/compiletest/src/json.rs
@@ -1,5 +1,5 @@
-use errors::{Error, ErrorKind};
-use runtest::ProcRes;
+use crate::errors::{Error, ErrorKind};
+use crate::runtest::ProcRes;
 use serde_json;
 use std::path::Path;
 use std::str::FromStr;
diff --git a/src/tools/compiletest/src/main.rs b/src/tools/compiletest/src/main.rs
index 15d53f1..1f9b4b2 100644
--- a/src/tools/compiletest/src/main.rs
+++ b/src/tools/compiletest/src/main.rs
@@ -1,29 +1,21 @@
 #![crate_name = "compiletest"]
 #![feature(test)]
-#![deny(warnings)]
+#![deny(warnings, rust_2018_idioms)]
 
-extern crate diff;
-extern crate env_logger;
-extern crate filetime;
-extern crate getopts;
 #[cfg(unix)]
 extern crate libc;
 #[macro_use]
 extern crate log;
-extern crate regex;
 #[macro_use]
 extern crate lazy_static;
 #[macro_use]
 extern crate serde_derive;
-extern crate serde_json;
 extern crate test;
-extern crate rustfix;
-extern crate walkdir;
 
-use common::CompareMode;
-use common::{expected_output_path, output_base_dir, output_relative_path, UI_EXTENSIONS};
-use common::{Config, TestPaths};
-use common::{DebugInfoBoth, DebugInfoGdb, DebugInfoLldb, Mode, Pretty};
+use crate::common::CompareMode;
+use crate::common::{expected_output_path, output_base_dir, output_relative_path, UI_EXTENSIONS};
+use crate::common::{Config, TestPaths};
+use crate::common::{DebugInfoBoth, DebugInfoGdb, DebugInfoLldb, Mode, Pretty};
 use filetime::FileTime;
 use getopts::Options;
 use std::env;
@@ -33,8 +25,10 @@
 use std::path::{Path, PathBuf};
 use std::process::Command;
 use test::ColorConfig;
-use util::logv;
+use crate::util::logv;
 use walkdir::WalkDir;
+use env_logger;
+use getopts;
 
 use self::header::{EarlyProps, Ignore};
 
diff --git a/src/tools/compiletest/src/read2.rs b/src/tools/compiletest/src/read2.rs
index 5a4cadd..6dfd8e9 100644
--- a/src/tools/compiletest/src/read2.rs
+++ b/src/tools/compiletest/src/read2.rs
@@ -100,18 +100,15 @@
 
 #[cfg(windows)]
 mod imp {
-    extern crate miow;
-    extern crate winapi;
-
     use std::io;
     use std::os::windows::prelude::*;
     use std::process::{ChildStderr, ChildStdout};
     use std::slice;
 
-    use self::miow::iocp::{CompletionPort, CompletionStatus};
-    use self::miow::pipe::NamedPipe;
-    use self::miow::Overlapped;
-    use self::winapi::shared::winerror::ERROR_BROKEN_PIPE;
+    use miow::iocp::{CompletionPort, CompletionStatus};
+    use miow::pipe::NamedPipe;
+    use miow::Overlapped;
+    use winapi::shared::winerror::ERROR_BROKEN_PIPE;
 
     struct Pipe<'a> {
         dst: &'a mut Vec<u8>,
diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs
index ff201b0..3152981 100644
--- a/src/tools/compiletest/src/runtest.rs
+++ b/src/tools/compiletest/src/runtest.rs
@@ -1,18 +1,18 @@
-use common::CompareMode;
-use common::{expected_output_path, UI_EXTENSIONS, UI_FIXED, UI_STDERR, UI_STDOUT};
-use common::{output_base_dir, output_base_name, output_testname_unique};
-use common::{Codegen, CodegenUnits, DebugInfoBoth, DebugInfoGdb, DebugInfoLldb, Rustdoc};
-use common::{CompileFail, Pretty, RunFail, RunPass, RunPassValgrind};
-use common::{Config, TestPaths};
-use common::{Incremental, MirOpt, RunMake, Ui};
+use crate::common::CompareMode;
+use crate::common::{expected_output_path, UI_EXTENSIONS, UI_FIXED, UI_STDERR, UI_STDOUT};
+use crate::common::{output_base_dir, output_base_name, output_testname_unique};
+use crate::common::{Codegen, CodegenUnits, DebugInfoBoth, DebugInfoGdb, DebugInfoLldb, Rustdoc};
+use crate::common::{CompileFail, Pretty, RunFail, RunPass, RunPassValgrind};
+use crate::common::{Config, TestPaths};
+use crate::common::{Incremental, MirOpt, RunMake, Ui};
 use diff;
-use errors::{self, Error, ErrorKind};
+use crate::errors::{self, Error, ErrorKind};
 use filetime::FileTime;
-use header::TestProps;
-use json;
+use crate::header::TestProps;
+use crate::json;
 use regex::Regex;
 use rustfix::{apply_suggestions, get_suggestions_from_json, Filter};
-use util::{logv, PathBufExt};
+use crate::util::{logv, PathBufExt};
 
 use std::collections::hash_map::DefaultHasher;
 use std::collections::{HashMap, HashSet, VecDeque};
@@ -27,8 +27,8 @@
 use std::process::{Child, Command, ExitStatus, Output, Stdio};
 use std::str;
 
-use extract_gdb_version;
-use is_android_gdb_target;
+use crate::extract_gdb_version;
+use crate::is_android_gdb_target;
 
 #[cfg(windows)]
 fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
@@ -1937,7 +1937,7 @@
     }
 
     fn make_cmdline(&self, command: &Command, libpath: &str) -> String {
-        use util;
+        use crate::util;
 
         // Linux and mac don't require adjusting the library search path
         if cfg!(unix) {
@@ -3255,7 +3255,7 @@
     }
 
     fn create_stamp(&self) {
-        let stamp = ::stamp(&self.config, self.testpaths, self.revision);
+        let stamp = crate::stamp(&self.config, self.testpaths, self.revision);
         fs::write(&stamp, compute_stamp_hash(&self.config)).unwrap();
     }
 }
@@ -3311,7 +3311,7 @@
 where
     T: AsRef<str> + fmt::Debug,
 {
-    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
         if let &ExpectedLine::Text(ref t) = self {
             write!(formatter, "{:?}", t)
         } else {
@@ -3334,7 +3334,7 @@
 }
 
 fn read2_abbreviated(mut child: Child) -> io::Result<Output> {
-    use read2::read2;
+    use crate::read2::read2;
     use std::mem::replace;
 
     const HEAD_LEN: usize = 160 * 1024;
diff --git a/src/tools/compiletest/src/util.rs b/src/tools/compiletest/src/util.rs
index 90dfade..85be2fe 100644
--- a/src/tools/compiletest/src/util.rs
+++ b/src/tools/compiletest/src/util.rs
@@ -1,7 +1,7 @@
 use std::ffi::OsStr;
 use std::env;
 use std::path::PathBuf;
-use common::Config;
+use crate::common::Config;
 
 /// Conversion table from triple OS name to Rust SYSNAME
 const OS_TABLE: &'static [(&'static str, &'static str)] = &[
diff --git a/src/tools/error_index_generator/Cargo.toml b/src/tools/error_index_generator/Cargo.toml
index 7f8783c..116be23 100644
--- a/src/tools/error_index_generator/Cargo.toml
+++ b/src/tools/error_index_generator/Cargo.toml
@@ -2,6 +2,7 @@
 authors = ["The Rust Project Developers"]
 name = "error_index_generator"
 version = "0.0.0"
+edition = "2018"
 
 [dependencies]
 rustdoc = { path = "../../librustdoc" }
diff --git a/src/tools/error_index_generator/main.rs b/src/tools/error_index_generator/main.rs
index 72cfd7d..ef04549 100644
--- a/src/tools/error_index_generator/main.rs
+++ b/src/tools/error_index_generator/main.rs
@@ -1,8 +1,9 @@
 #![feature(rustc_private)]
 
+#![deny(rust_2018_idioms)]
+
 extern crate env_logger;
 extern crate syntax;
-extern crate rustdoc;
 extern crate serialize as rustc_serialize;
 
 use std::collections::BTreeMap;
diff --git a/src/tools/rustc-std-workspace-core/Cargo.toml b/src/tools/rustc-std-workspace-core/Cargo.toml
index f000d63..d527ce1 100644
--- a/src/tools/rustc-std-workspace-core/Cargo.toml
+++ b/src/tools/rustc-std-workspace-core/Cargo.toml
@@ -6,6 +6,7 @@
 description = """
 Hack for the compiler's own build system
 """
+edition = "2018"
 
 [lib]
 path = "lib.rs"
diff --git a/src/tools/rustc-std-workspace-core/lib.rs b/src/tools/rustc-std-workspace-core/lib.rs
index e2946fe..99d51bc 100644
--- a/src/tools/rustc-std-workspace-core/lib.rs
+++ b/src/tools/rustc-std-workspace-core/lib.rs
@@ -1,6 +1,5 @@
 #![feature(no_core)]
 #![no_core]
-
-extern crate core;
+#![deny(rust_2018_idioms)]
 
 pub use core::*;
diff --git a/src/tools/rustdoc/Cargo.toml b/src/tools/rustdoc/Cargo.toml
index d388150..36aa591 100644
--- a/src/tools/rustdoc/Cargo.toml
+++ b/src/tools/rustdoc/Cargo.toml
@@ -2,6 +2,7 @@
 name = "rustdoc-tool"
 version = "0.0.0"
 authors = ["The Rust Project Developers"]
+edition = "2018"
 
 # Cargo adds a number of paths to the dylib search path on windows, which results in
 # the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool"
diff --git a/src/tools/rustdoc/main.rs b/src/tools/rustdoc/main.rs
index df9d2c6..8bdc365 100644
--- a/src/tools/rustdoc/main.rs
+++ b/src/tools/rustdoc/main.rs
@@ -1,3 +1,5 @@
+#![deny(rust_2018_idioms)]
+
 #![feature(link_args)]
 
 #[allow(unused_attributes)]
@@ -10,6 +12,4 @@
 // See src/rustc/rustc.rs for the corresponding rustc settings.
 extern {}
 
-extern crate rustdoc;
-
 fn main() { rustdoc::main() }